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 09:14:26 浏览: 116
这是因为在iOS中,应用程序沙盒机制会限制应用程序只能访问到自己的沙盒目录下的文件。因此,当我们从相机或相册中选择视频时,需要使用一个特殊的方法来获取视频的URL。
你可以尝试修改 `imagePickerController(_:didFinishPickingMediaWithInfo:)` 方法中的代码,将获取URL的方式改为如下方式:
```swift
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let url = info[.mediaURL] as? URL {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationURL = documentsDirectory.appendingPathComponent(url.lastPathComponent)
do {
try FileManager.default.moveItem(at: url, to: destinationURL)
onURLPicked(destinationURL)
} catch {
print(error)
}
}
presentationMode.dismiss()
}
```
该方法在获取到视频的URL后,先获取应用程序的文档目录,然后将视频文件移动到该目录下,并将移动后的URL传递给 `onURLPicked` 闭包。这样就可以确保获取到的URL是应用程序可以访问的。
阅读全文