在最近的項(xiàng)目開(kāi)發(fā)中笼痛,開(kāi)發(fā)上傳圖片和視頻的時(shí)候捞奕,測(cè)試說(shuō)芒珠,選擇視頻閃退桥狡,然后通過(guò)打印日志得出,UIImagePickerControllerMediaURL 這個(gè)并不是所有的對(duì)象都會(huì)返回的皱卓。
查看下面兩個(gè)視頻的結(jié)構(gòu)裹芝,兩個(gè)顯然不一樣,類型都是為public.movie
,但是第一個(gè)視頻的結(jié)構(gòu)缺少了UIImagePickerControllerMediaURL
,導(dǎo)致上傳的時(shí)候?yàn)榭铡?/p>
// 視頻一:
{
UIImagePickerControllerMediaType = "public.movie";
UIImagePickerControllerPHAsset = "<PHAsset: 0x10a59adc0> 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 = "<PHAsset: 0x15131dfa0> 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)
// 此時(shí)的 videoURL 就是 我們拿到的 “UIImagePickerControllerMediaURL” 這個(gè)key 里面的值
// 做自己的處理
}
}
}
})
}
} else {
/// 項(xiàng)目最低支持iOS11掐禁,無(wú)需兼容低版本
}
}
}else if type == "public.image" {
// 做自己的處理
}
}
}
}