Search code examples
iosswiftnsfilemanager

Can not get image from file


I have cache images in file like so:

enter image description here

I want to get these images, I have tried like this:

let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let imagePath = documentsURL.absoluteString.stringByAppendingString("1.png")
let image = UIImage(contentsOfFile: imagePath)
print(image) 

the imagePath give me:

"file:///Users/entropy/Library/Developer/CoreSimulator/Devices/3A41D467-B991-4F85-93CD-10C227ED4F69/data/Containers/Data/Application/F5005FAA-7107-41DD-86D2-38C302742063/Documents/1.png"

You see it gives me exactly the image path, but when I print(image), the image is nil.

What I am doing wrong here?


Solution

  • Try this EDIT

    let path = "~/1.png"
    let expandedPath = path.stringByExpandingTildeInPath
    let data = NSData(contentsOfURL: NSURL(string: expandedPath)!)
    
    let image = UIImage(data: data!)
    print(image)
    

    Hope this helps.