注意访问权限
/// 从相册中获取视频数组----**-
private func getVideosFromAlbum(result: @escaping (([ContestChooseVideo.Video]) -> Void)){
var videos: [ContestChooseVideo.Video] = []
// 获取所有资源的集合,并按资源的创建时间排序如果不写就是乱序,并不好使
// let options = PHFetchOptions()
// options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let option = PHVideoRequestOptions()
option.version = .current
option.deliveryMode = .automatic
option.isNetworkAccessAllowed = true
let manager = PHImageManager.default()
let assets: PHFetchResult = PHAsset.fetchAssets(with: .video, options: nil)
var tempCount = assets.count
// 获取视频
for i in 0..<assets.count {
let asset = assets.object(at: i)
manager.requestAVAsset(forVideo: asset, options: option) { (avasset, audioMix, array) in
// 为了防止多次回调
tempCount = tempCount - 1
guard let urlAsset: AVURLAsset = avasset as? AVURLAsset else {
if tempCount == 0 {
showFailure("获取视频失败")
result([])
}
return
}
var model = ContestChooseVideo.Video()
model.asset = asset
model.avSet = avasset
model.videoUrl = urlAsset.url
model.image = UIImage.thumbnailImageForVideo(videoURL: urlAsset.url, time: 0.5)
model.duration = CMTimeGetSeconds(urlAsset.duration)
model.creationDate = asset.creationDate
videos.append(model)
if tempCount == 0 {
// 把视频按照日期排序
let newVideos = videos.sorted(by: { (video1, video2) -> Bool in
guard let date1 = video1.creationDate,
let date2 = video2.creationDate else {
return true
}
return date1 < date2
})
result(newVideos)
}
}
}
}
model:
enum ContestChooseVideo { }
extension ContestChooseVideo {
struct Video {
var image: UIImage? // 视频封面
var duration: Double? // 视频时长
var asset: PHAsset? // 操作信息的对象
var videoUrl: URL? // 视频本地地址
var avSet: AVAsset? // 剪辑控制
var creationDate: Date? // 视频创建时间
}
}