2017-06-26 41 views
0

我試圖獲取帶有文件URL(「file:///var/mobile/Media/DCIM/100APPLE/IMG_0056.JPG」)的圖像,this method很好用,但有沒有辦法讓它變得更好?因爲檢索圖像需要很長時間。直接使用文件URL返回的圖像

我曾嘗試與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 

我如何才能訪問到該圖像直接?

回答

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 
} 
相關問題