How to display image from document directory in UIImageView in Swift 3?

The following is an example of Swift 2:

String value does not have member 'stringByAppendingPathComponent'

Screenshot of Error

What do I need to change for Swift 3?

+6
source share
2 answers

Apple is trying to migrate everyone from the path-as-string paradigm to a URL (i.e. file:///path/to/file.text ). The Swift API pretty much removes all path in favor of the URL .

You can still find it in Objective-C ( NSString ):

 let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String let getImagePath = NSString.path(withComponents: [paths, "fileName"]) 

The more Swifty:

 let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String let url = URL(fileURLWithPath: paths).appendingPathComponent("fileName") 
+5
source

I personally like to receive this value from the application delegate. Put this code (stand alone, as a normal function) in AppDelegate.swift.

 lazy var applicationDocumentsDirectory: URL = { let urls = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask) return urls[urls.count-1] }() 

So in all of your files you can use it like this:

 let appDelegate = UIApplication.shared.delegate as! AppDelegate let imageUrl = appDelegate.applicationDocumentsDirectory.appendingPathComponent("YourFileName") let imageUrlString = imageUrl.urlString //if String is needed 
+1
source

All Articles