我对Swift相对较新。
我目前正在尝试抓取存储在照片库中的视频,并将其显示在集合视图中。在集合视图中选择视频后,我希望能够播放视频。
现在我已经写了部分函数grabVideos,我有2个问题:
注意:下面的代码位于名为getVideos()
的函数中 let imgManager = PHImageManager.default()
let requestOption = PHVideoRequestOptions()
requestOption.isSynchronous = true
requestOption.deliveryMode = .highQualityFormat
let fetchOption = PHFetchOptions()
fetchOption.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
if let fetchResult:PHFetchResult = PHAsset.fetchAssets(with: .video, options: fetchOption) {
if fetchResult.count > 0 {
for i in 0...fetchResult.count {
imgManager.requestAVAsset(forVideo: fetchResult.object(at: i) as! PHAsset, options: requestOption, resultHandler: {{ (<#AVAsset?#>, <#AVAudioMix?#>, <#[AnyHashable : Any]?#>) in
<#code#>
}})
}
} else {
print("Error: No Videos Found")
}
}
答案 0 :(得分:0)
首先,将一个变量添加到ViewController var fetchResults: PHFetchResult<PHAsset>?
然后执行viewDidLoad
中的fetch实例
let fetchOption = PHFetchOptions()
fetchOption.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let fetchResults = PHAsset.fetchAssets(with: .video, options: fetchOption);
self.fetchResults = fetchResults
if fetchResults.count == 0 {
print("Error: No Videos Found")
return
}
在collectionViewCell
中,您必须添加UIImageView
以便我们可以在每个单元格中显示缩略图,然后您只需在集合视图数据源方法中执行以下操作
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return fetchResults?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "reuse", for: indexPath) as! TestCollectionViewCell
let videoAsset = fetchResults!.object(at: indexPath.item)
PHImageManager.default().requestImage(for: videoAsset, targetSize: cell.bounds.size, contentMode: .aspectFill, options: nil) { (image: UIImage?, info: [AnyHashable : Any]?) in
cell.imageView.image = image
}
return cell
}
这可以获得批准,但第一次尝试就可以了,特别是使用PHCachingImageManager
代替PHImageManager
,更多信息请参见以下链接:
How to use PHCachingImageManager
如何播放来自PHAsset
的视频,您可以找到答案: