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

时间:2017-02-14 05:56:34

标签: ios swift video uicollectionview

我想在UICollectionView中加载所有相机胶卷视频及其持续时间(同样,视频以相机胶卷显示)。怎么办? 我查看了this链接。但他们展示的视频就像是图像。

2 个答案:

答案 0 :(得分:5)

         // 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
    }
  • 注意:隐私 - 照片库使用说明 - &gt;我需要你将照片库添加到info.plist文件中

答案 1 :(得分:1)

我建议使用Apple已预先构建到Xcode中的照片框架。这个问题的答案已经在这里填写:

swift: How to load photos from photo library without using UIImagePickerController?

apple创建的照片框架:

https://developer.apple.com/library/prerelease/ios//documentation/Photos/Reference/Photos_Framework/index.html

要添加视频,您可以使用UIImagePickerCrollerSourceType:

picker.sourceType = UIImagePickerControllerSourceType.Camera