我正在使用第三方库从照片库中选择多个图像。在选择多个图像时,它返回一组PHAsset对象。 现在,我想在核心数据中保存这些对象的URL(或一些引用)。但我不知道如何获取URL。我可以在核心数据中存储任何其他参考资料,这可以帮助我从照片库中获取相同的图像吗?
答案 0 :(得分:27)
我使用@iMHitesh Surani 回答并且它完美无缺,我将其转换为Swift 3.1并将其放入PHAsset的扩展中,以便在任何地方使用该方法,这里是:
extension PHAsset {
func getURL(completionHandler : @escaping ((_ responseURL : URL?) -> Void)){
if self.mediaType == .image {
let options: PHContentEditingInputRequestOptions = PHContentEditingInputRequestOptions()
options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData) -> Bool in
return true
}
self.requestContentEditingInput(with: options, completionHandler: {(contentEditingInput: PHContentEditingInput?, info: [AnyHashable : Any]) -> Void in
completionHandler(contentEditingInput!.fullSizeImageURL as URL?)
})
} else if self.mediaType == .video {
let options: PHVideoRequestOptions = PHVideoRequestOptions()
options.version = .original
PHImageManager.default().requestAVAsset(forVideo: self, options: options, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable : Any]?) -> Void in
if let urlAsset = asset as? AVURLAsset {
let localVideoUrl: URL = urlAsset.url as URL
completionHandler(localVideoUrl)
} else {
completionHandler(nil)
}
})
}
}
}