Swift-如何从相机胶卷中获取视频并将其显示在UICollectionView中?

pig*_*_39 3 video ios uicollectionview swift

我想将所有相机胶卷视频及其持续时间加载到UICollectionView中(同样,视频显示在相机胶卷中)。怎么做?我检查了链接。但是他们将视频显示为图片。

Yog*_*ana 8

// get all videos from Photos library you need to import Photos framework
var photos: PHFetchResult<PHAsset>! // user photos array in collectionView for disaplying video thumnail
func getAssetFromPhoto() {
    let options = PHFetchOptions()
    options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: true) ]
    options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.video.rawValue)
    photos = PHAsset.fetchAssets(with: options)
    print(photos)
    photoCollectionView.reloadData() // reload your collectionView
}

// For displaying thumnait image and video dutation
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! PhotoCollectionViewCell
    let asset = photos!.object(at: indexPath.row)
    let width: CGFloat = 150
    let height: CGFloat = 150
    let size = CGSize(width:width, height:height)
    PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: PHImageContentMode.aspectFill, options: nil) { (image, userInfo) -> Void in

        self.photoImageView.image = image
        self.lblVideoTime.text = String(format: "%02d:%02d",Int((asset.duration / 60)),Int(asset.duration) % 60)

    }
    return cell
}
Run Code Online (Sandbox Code Playgroud)
  • 注意:隐私-图片库使用说明->我需要您的图片库将此密钥添加到info.plist文件中