美文网首页
2021-09-01

2021-09-01

作者: JackeyJin | 来源:发表于2021-09-01 11:17 被阅读0次

    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)
                    }
                })
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:2021-09-01

          本文链接:https://www.haomeiwen.com/subject/knjxwltx.html