struct VideoPicker: UIViewControllerRepresentable { @Environment(.presentationMode) private var presentationMode let sourceType: UIImagePickerController.SourceType // let onImagePicked: (UIImage) -> Void let onURLPicked: (URL) -> Void final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @Binding private var presentationMode: PresentationMode private let sourceType: UIImagePickerController.SourceType private let onURLPicked: (URL) -> Void init(presentationMode: Binding<PresentationMode>, sourceType: UIImagePickerController.SourceType, onURLPicked: @escaping (URL) -> Void) { presentationMode = presentationMode self.sourceType = sourceType self.onURLPicked = onURLPicked } func imagePickerController( picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage // onImagePicked(uiImage) if let url = info[.mediaURL] as? URL{ onURLPicked(url) } presentationMode.dismiss() } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { presentationMode.dismiss() } } func makeCoordinator() -> Coordinator { return Coordinator(presentationMode: presentationMode, sourceType: sourceType, onURLPicked: onURLPicked) } func makeUIViewController(context: UIViewControllerRepresentableContext<VideoPicker>) -> UIImagePickerController { let picker = UIImagePickerController() picker.sourceType = sourceType picker.delegate = context.coordinator picker.mediaTypes = ["public.movie"] return picker } func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<VideoPicker>) { } }这段代码获取的url中绝对路径不准确
时间: 2023-07-16 19:13:43 浏览: 113
mapstruct-1.3.1.Final-API文档-中英对照版.zip
5星 · 资源好评率100%
这可能是因为在 iOS 14 中,苹果公司修改了媒体选择器的行为,使其返回的 URL 是相对路径而不是绝对路径。要获取正确的绝对路径,你可以使用 `PHAsset` 和 `PHAssetResource` 来获取 URL,其中 `PHAssetResource` 包含了媒体文件的原始名称和 URL。
以下是一个获取视频绝对路径的示例代码:
```swift
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let url = info[.mediaURL] as? URL else {
return
}
let assets = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
guard let asset = assets.firstObject else {
return
}
PHImageManager.default().requestAVAsset(forVideo: asset, options: nil) { (asset, _, _) in
guard let asset = asset as? AVURLAsset else {
return
}
let videoURL = asset.url
// 处理视频URL
}
presentationMode.dismiss()
}
```
这个方法首先从选择器返回的 URL 中获取 `PHAsset` 实例,然后使用 `PHImageManager` 请求该资源的 `AVURLAsset`,最后从 `AVURLAsset` 中获取视频的绝对 URL。
阅读全文