How to get image from library with URL in Swift?

1.1k Views Asked by At

I have an this URL file:///var/mobile/Media/DCIM/101APPLE/IMG_1426.JPG. How do I get image from library with it? I got that URL from the previous time run the app. Now I want to fetch only this image without fetching all image from library. I tried to use:

if let url = URL(string: url) {
            let imgData = NSData(contentsOf: url)
            let image = UIImage(data: imgData! as Data)
        }

But I got this error:

Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_1426.JPG” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Media/DCIM/101APPLE/IMG_1426.JPG, NSUnderlyingError=0x28200bfc0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I got URL from this:

let options: PHContentEditingInputRequestOptions = PHContentEditingInputRequestOptions()
            options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData) -> Bool in
                return true
            }
        
            self.requestContentEditingInput(with: options, completionHandler: {(contentEditingInput: PHContentEditingInput?, info: [AnyHashable : Any]) -> Void in
                if let url = contentEditingInput?.fullSizeImageURL {
                    //this
                }

            })

I don't want to save that photo in my app documents, how to I achieve it? Or at least how do I open the Photo App with showing that image? Thanks.

1

There are 1 best solutions below

0
workingdog support Ukraine On

you gave you app permission to the to access photo library and camera, but you are trying to read a file. That is different. I tested the following code successfully, using these permissions:

<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.files.bookmarks.app-scope</key>
<true/>


            if let url = URL(string: "file:///private/var/mobile/workingdog.png") {
                do {
                    let imgData = try Data(contentsOf: url)
                    if let image = UIImage(data: imgData) {
                        print("\n---> image: \(image)")
                    }
                } catch {
                   print("error")
                }
            }