Search code examples
imageurlpathphasset

Retrived Image directly with file URL


I'm trying to get an image with the file URL ("file:///var/mobile/Media/DCIM/100APPLE/IMG_0056.JPG"), this method works great but there is no way to make it better ? Because it takes a long time to retrieved my image.

I have tried to get directly the image with the url, with this method :

if let url = URL(string: self.path) {
        print(url) (print = file:///var/mobile/Media/DCIM/100APPLE/IMG_0056.JPG)
        do {
            let data = try Data(contentsOf: url)
            print(data)
            let image2 = UIImage(data: data as Data)
            return image2
        } catch {
            print(error.localizedDescription)
            // (print = Impossible d’ouvrir le fichier « IMG_0056.JPG » car vous ne disposez pas de l’autorisation nécessaire pour l’afficher.)
            // Traduction : Unable to open file "IMG_0056.JPG" because you do not have permission to view it.
        }
    }

    return nil

How can i get access to this image directly ?


Solution

  • I finally found a way to make it quicker. The only way i found is to store in my object the localIdentifier of the PHAsset object.

    Now, my method look like this :

    func PHAssetForFileURL(url: NSURL) -> PHAsset? {
        let imageRequestOptions = PHImageRequestOptions()
        imageRequestOptions.version = .current
        imageRequestOptions.deliveryMode = .fastFormat
        imageRequestOptions.resizeMode = .fast
        imageRequestOptions.isSynchronous = true
    
        let options = PHFetchOptions()
        options.predicate = NSPredicate(format: "localIdentifier == %@", self.localIdentifier )
    
        let fetchResult = PHAsset.fetchAssets(with: options)
        for index in 0 ..< fetchResult.count {
            let asset = fetchResult[index] as PHAsset
            var found = false
            PHImageManager.default().requestImageData(for: asset, options: imageRequestOptions) { (_, _, _, info) in
                if let urlkey = info?["PHImageFileURLKey"] as? NSURL {
                    if urlkey.absoluteString! == url.absoluteString! {
                        found = true
                    }
                }
            }
            if (found) {
                return asset
    
            }
        }
    
        return nil
    }