Search code examples
swiftuiimagensuserdefaultsnsdocumentdirectory

Saving and loading image paths by NSUserdefaults


My app allows the user to select a logo from their photo library and save it to their documents directory as follows:

 var fileName:String = "logo.png"

        var arrayPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString

        var pngFileName = arrayPaths.stringByAppendingPathComponent(fileName)

       UIImagePNGRepresentation(pickedImage).writeToFile(pngFileName, atomically:true)

        NSUserDefaults.standardUserDefaults().setObject(fileName, forKey: "pngFileName")
        NSUserDefaults.standardUserDefaults().synchronize()

I want to then use the image within another viewcontroller but I can't figure out how to access the image from their user defaults and then use in the current viewcontroller.


Solution

  • You have the file name stored in the user defaults, you can find the application documents directory in the usual way - combine the two and you have your url. With this, you can display the image.

    let path = NSSearchPathForDirectoriesInDomains(
           .DocumentDirectory, .UserDomainMask, true)[0] as NSString
    let fileName = NSUserDefaults.standardUserDefaults()
                   .stringForKey("pngFileName") ?? defaultName
    let imagePath = path.stringByAppendingPathComponent(fileName)!
    let image = UIImage(contentsOfFile: imagePath )
    
    // display the image
    someImageView.image = image