UIImagePickerControllerMediaURL 为nil

在最近的项目开发中,开发上传图片和视频的时候,测试说,选择视频闪退,然后通过打印日志得出,UIImagePickerControllerMediaURL 这个并不是所有的对象都会返回的。

查看下面两个视频的结构,两个显然不一样,类型都是为public.movie,但是第一个视频的结构缺少了UIImagePickerControllerMediaURL,导致上传的时候为空。

// 视频一:
{
    UIImagePickerControllerMediaType = "public.movie";
    UIImagePickerControllerPHAsset = " B065BB1D-E44F-4664-8B92-DAFE523A8C6A/L0/001 mediaType=2/0, sourceType=1, (2560x1440), creationDate=2021-12-17 08:19:42 +0000, location=0, hidden=0, favorite=0, adjusted=0 ";
    UIImagePickerControllerReferenceURL = "assets-library://asset/asset.MP4?id=B065BB1D-E44F-4664-8B92-DAFE523A8C6A&ext=MP4";
}
// 视频二:
{
    UIImagePickerControllerMediaType = "public.movie";
    UIImagePickerControllerMediaURL = "file:///private/var/mobile/Containers/Data/PluginKitPlugin/DFC74D67-EF9A-4750-8D7E-B6C5E6716367/tmp/trim.DF9E89B1-35E2-40FA-999A-429CA685FCCC.MOV";
    UIImagePickerControllerPHAsset = " 08BE0321-FC3E-4B04-8296-453288AE0509/L0/001 mediaType=2/0, sourceType=1, (1920x1080), creationDate=2021-12-28 06:35:44 +0000, location=0, hidden=0, favorite=0, adjusted=0 ";
    UIImagePickerControllerReferenceURL = "assets-library://asset/asset.MP4?id=08BE0321-FC3E-4B04-8296-453288AE0509&ext=MP4";
}

可以使用 下面的方法,处理,等到我们需要的URL。

public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let type = info[.mediaType] as? String {
            if type == "public.movie" {
                if let videoUrl = info[.mediaURL] as? URL {
                   // 做自己的处理
                } else {
                    if #available(iOS 11.0, *) {
                        if let phAsset = info[.phAsset] as? PHAsset {
                            PHImageManager.default().requestAVAsset(forVideo: phAsset, options: PHVideoRequestOptions(), resultHandler: { (asset, audioMix, info) -> Void in
                                DispatchQueue.main.async { [self] in
                                    if let asset = asset as? AVURLAsset {
                                        let videoData = NSData(contentsOf: asset.url)
                                        let videoPath = NSTemporaryDirectory() + "tmpMovie.MOV"
                                        let videoURL = NSURL(fileURLWithPath: videoPath)
 // 此时的 videoURL 就是 我们拿到的 “UIImagePickerControllerMediaURL” 这个key 里面的值
// 做自己的处理

                                        }
                                    }
                                }
                            })
                        }
                    } else {
                        /// 项目最低支持iOS11,无需兼容低版本
                    }
                }
            }else if type == "public.image" {
               // 做自己的处理
            }
        }
    }
}

你可能感兴趣的:(UIImagePickerControllerMediaURL 为nil)