我想知道为什么contentsOf为AVURLAsset的URL返回nil。从带有Photos框架的自定义库中挑选后,我尝试从PHAsset请求资产,如下所示:
PHCachingImageManager().requestAVAsset(forVideo: asset, options: nil) { (avAsset, _, _) in
DispatchQueue.main.async {
guard let asset = avAsset as? AVURLAsset else {
return
}
print(asset.url) // file:///var/mobile/Media/DCIM/101APPLE/IMG_1513.MP4
}
}
使用AVPlayer可以正常显示上面带有URL的视频。但是当我尝试使用以下方法获取与url相关联的数据时:
do {
let videoData = try Data(contentsOf: mediaURL!)
} catch (let error){
print(error.localizedDescription ?? "") // "The file “IMG_1490.MP4” couldn’t be opened because you don’t have permission to view it."
}
答案 0 :(得分:0)
请找到我从图库中检索到最近视频的工作源代码,然后我使用AVURLAsset将该视频转换为 AVURLAsset ,并将其转换为数据。
Swift 4
override func viewDidLoad() {
super.viewDidLoad()
//For fetching Videos from Photo Library.
let phFetchOptions = PHFetchOptions()
phFetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
ascending: false)]
phFetchOptions.predicate = NSPredicate(format: "mediaType == %d",
PHAssetMediaType.video.rawValue)
phFetchOptions.fetchLimit = 2
let videoPhAssetResult = PHAsset.fetchAssets(with:phFetchOptions)
print(videoPhAssetResult.count)
let videoPHAsset = videoPhAssetResult.object(at: 0)
//For Fetching AvAsset from PHAsset and along with that getting Data from AvAsset
PHCachingImageManager().requestAVAsset(forVideo:videoPHAsset , options: nil) { (vidAvAsset, _, _) in
DispatchQueue.main.async {
if vidAvAsset != nil {
let assetURL = vidAvAsset as? AVURLAsset
print(assetURL?.url)
do {
let videoData = try Data(contentsOf:(assetURL?.url)!)
print(videoData)
} catch (let error){
print(error.localizedDescription)
}
}
}
}
}
(注意:请不要忘记添加隐私 - 照片库使用说明访问设备或模拟器照片库的权限)