直接使用文件URL重新传输图像

时间:2017-06-26 07:49:48

标签: image url path phasset

我尝试使用文件网址获取图片("文件:///var/mobile/Media/DCIM/100APPLE/IMG_0056.JPG"),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

如何直接访问此图片?

1 个答案:

答案 0 :(得分:0)

我终于找到了一种让它更快的方法。我找到的唯一方法是在我的对象中存储PHAsset对象的localIdentifier。

现在,我的方法看起来像这样:

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
}