iOS获取PHAsset
的图片或视频资源的本地地址URL
- 项目中,之前使用
UIImagePickerController
来管理图片,获取动图后返回选取界面无法正常使用,这个是iOS系统设计UIImagePickerController
的bug,暂时无法修复,而且苹果自身也将不再更新维护这个API了,所以项目改用PHPickerViewController
管理图片资源。 - 但是项目需求需要获取保存图片的地址,但是
PHAsset
本身并不带URL
,而PHImageManager.default().requestImageData
获取到info
并不像UIImagePickerController代理方法中imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any])
携带imageURL。 - 不过
PHAsset
提供requestContentEditingInput
方法返回的闭包的PHContentEditingInput
的参数里有fullSizeImageURL
swift代码:
extension PHAsset {
func getURL(completionHandler: @escaping ((_ responseURL: URL?) -> Void)) {
if self.mediaType == .image {
let options: PHContentEditingInputRequestOptions = PHContentEditingInputRequestOptions()
options.isNetworkAccessAllowed = true //开通网络访问权限
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
options.isNetworkAccessAllowed = true
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)
}
})
}
}
}
网友评论