我正在尝试使用文件URL获取图像(" file:///var/mobile/media/media/dcim/100apple/img_0056.jpg"(,此方法可以很好地工作但是没有办法使它变得更好吗?因为要检索我的图像需要很长时间。
我试图用URL直接获得图像,并使用此方法:
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
如何直接访问此图像?
我终于找到了一种使它更快的方法。我发现的唯一方法是将phasset对象的局部身份存储在对象中。
现在,我的方法看起来像这样:
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
}