Say I were using this code to save an image to the documents directroy
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) { if paths.count > 0 { if let dirPath = paths[0] as? String { let readPath = dirPath.stringByAppendingPathComponent("Image.png") let image = UIImage(named: readPath) let writePath = dirPath.stringByAppendingPathComponent("Image2.png") UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true) } } }
How would I then retrive it? Keeping in mind than in iOS8 the exact path changes often
In the iOS application we have to store files, images, audios, videos. We can do it by creating folder in Document directory. Document directory stores user data to the given path in the apps. You can read apps data from the path of document directory.
You are finding the document directory path at runtime for writing the image, for reading it back, you can use the exact logic:
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) if let dirPath = paths.first { let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("Image2.png") let image = UIImage(contentsOfFile: imageURL.path) // Do whatever you want with the image }
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) { if paths.count > 0 { if let dirPath = paths[0] as? String { let readPath = dirPath.stringByAppendingPathComponent("Image2.png") let image = UIImage(contentsOfFile: readPath) // Do whatever you want with the image } } }
Better as an extension.
extension URL { static var documentsDirectory: URL { let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! return try! documentsDirectory.asURL() } static func urlInDocumentsDirectory(with filename: String) -> URL { return documentsDirectory.appendingPathComponent(filename) } }
Used like this:
let path = URL.urlInDocumentsDirectory(with: filename).path let image = UIImage(contentsOfFile: path)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With