简体   繁体   中英

Swift - saving and retrieving images from userDefaults

I'm trying to save images retrieved from Parse.com like this:

                    let userImageFile = object["Image"] as PFFile
                    userImageFile.getDataInBackgroundWithBlock {
                        (imageData: NSData!, error: NSError!) -> Void in
                        if error == nil {
                            image = UIImage(data:imageData)
                            let imageToSave:NSData = UIImagePNGRepresentation(image)
                            self.saveImage(intRandomNumb, retImage: imageToSave)
                        }
                    }

where the saveImage-function looks like this:

func saveImage(imagepath:Int, retImage:NSData){

    println("image is being saved")

    let defaults = NSUserDefaults.standardUserDefaults()
    let imagePathName = "\(imagepath)"

    defaults.setObject(retImage, forKey: imagePathName)

}

and later, I'm trying to display this image like this:

        var point = gestureRecognizer.locationInView(self.tv)
        if let indexPath = self.tv.indexPathForRowAtPoint(point)
        {
            let data = mainList[indexPath.row] as SecondModel
            let fileRef = data.fileReference
            let intFileRef = Int(fileRef)
            println(intFileRef)

            let defaults = NSUserDefaults.standardUserDefaults()
            let usedKeyName = "\(intFileRef)"

            if let photo = defaults.objectForKey(usedKeyName) as? UIImage {
                println("Image created")
                let photo = defaults.objectForKey(usedKeyName) as UIImage

                var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
                imageView.image = photo
                self.view.addSubview(imageView)
            }

and the "Image created" never gets printed which means the retrieving somehow doesn't work. I'm not quite sure if you're able to save images to the userdefaults like I've done here, but that was the best I could come up with, and I couldn't find any previous questions like this for Swift.

Any suggestions on how to proceed would be appreciated.

SOLUTION: The problem was that I tried to load the image directly as a UIImage. I also had to convert the NSData to a UIImage, this all happens in the last section of the code displayed above. Finally my code looks like this:

        if let photo = defaults.objectForKey("\(intFileRef)") as? NSData {
            println("Image created")
            let photo = defaults.objectForKey("\(intFileRef)") as NSData
            let imageToView:UIImage = UIImage(data: photo)

            var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
            imageView.image = imageToView
            self.view.addSubview(imageView)
        }

I hope this can help others struggling with something similar to this.

Swift 3

Hey, try this beautiful code here:

  • Convert your UIImage to Data .

    PNG:

  yourDataImagePNG = UIImagePNGRepresentation(yourUIImageHere) 

JPEG :

  yourDataImageJPG = UIImage(data: yourUIImageHere,scale:1.0) 
  • Save in UserDefaults.
  UserDefaults().set(yourDataImagePNG, forKey: "image") 
  • Recover from:
  UserDefaults.standard.object(forKey: "image") as! Data 

I hope to help!

似乎您没有调用defaults.synchronize()因此未将其写入默认文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM