Josh O'Connor
Josh O'Connor

Reputation: 4962

Get image from local URL (iOS)

I am getting a photo's URL using requestContentEditingInput using the PHLibrary

asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (input, _) in
    let url = input?.fullSizeImageURL
}

This URL prints: file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG.

How do I retrieve this image? I've tried the following but it does not return anything:

var fileLocation = "file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG"
let url = URL(string: fileLocation)
let asset = PHAsset.fetchAssets(withALAssetURLs: [url!], options: nil)
if let result = asset.firstObject  {
    //asset.firstObject does not exist
}

Upvotes: 0

Views: 1259

Answers (1)

Josh O'Connor
Josh O'Connor

Reputation: 4962

apparently apple will not allow the developer to access any and every photo in the user's photo library even after they have accepted photos usage. If you are using an image that hasnt been picked from the imagePicker, (i.e. choosing last image in library), you have to store the image in the document directory before you can use the document directory URL. I guess this prevents people hacking into others photo library

//Storing the image (in my case, when selecting last photo NOT via imagePicker)

let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image01.jpg")
let imageData = UIImageJPEGRepresentation(image!, 1.0)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)


//Retrieving the image
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("image01.jpg")
    if let imageRetrieved = UIImage(contentsOfFile: imageURL.path) {
        //do whatever you want with this image
        print(imageRetrieved)
    }
}

Upvotes: 1

Related Questions