Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an image from documents directory to UIImageView in Swift 3?

Tags:

swift3

The below Swift 2 example gives this error:

Value of type String has no member 'stringByAppendingPathComponent'

Screenshot of Error

What do I need to change for Swift 3?

like image 501
Arkelyan Avatar asked Aug 18 '16 22:08

Arkelyan


2 Answers

Apple is trying to move everyone off the path-as-string paradigm to URL (i.e. file:///path/to/file.text). The Swift API pretty much removes all path in favor of 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 way:

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: paths).appendingPathComponent("fileName")
like image 144
Code Different Avatar answered Jan 04 '23 00:01

Code Different


I personally like getting of this value from the App delegate. Put this code (stands alone like normal function) into the 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 your files you can use it this way:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let imageUrl = appDelegate.applicationDocumentsDirectory.appendingPathComponent("YourFileName")
    let imageUrlString = imageUrl.urlString //if String is needed
like image 25
pedrouan Avatar answered Jan 03 '23 22:01

pedrouan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!