Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage from path or filename in Swift 3

i have a bunch of images in my App's Documents Directory. i want to load one of them in an UIImage that i have in my view. this is what i do:

myImage.image = UIImage(named: "image.jpg") // the file exist but this returns nil

I also tried to init the image using:

myImage.image = UIImage(contentsOfFile: imagePath) //this also doesn't work but the path i got starts (at least in the sim) with file://

Anyone can suggest something? I'm kinda a noob in iOS programming.

Thanks

EDIT: imagePath comes from:

func getImgPath(name: String) -> String
{
    let documentsDirectory = self.getDocumentsDirectory()
    let fullpath = documentsDirectory.appendingPathComponent(name)
    return fullpath.absoluteString

}
like image 487
Andrea Avatar asked Dec 02 '22 12:12

Andrea


1 Answers

This might help

let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask    = FileManager.SearchPathDomainMask.userDomainMask
let paths             = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
if let dirPath        = paths.first
{
   let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("name.png")
   let image    = UIImage(contentsOfFile: imageURL.path)
   // Do whatever you want with the image
}
like image 141
Maulik Bhuptani Avatar answered Dec 12 '22 10:12

Maulik Bhuptani