2017-10-21 163 views
1

我對Swift比較陌生。Swift3:以集合視圖顯示視頻

我目前正試圖抓取存儲在照片庫中的視頻並將它們顯示在集合視圖中。在收藏視圖中選擇視頻後,我希望能夠播放視頻。

現在我已經寫功能grabVideos的一部分,我有2個問題:

  1. 我應該如何儲存這些視頻嗎?它們可以作爲UIImage存儲嗎?我發現很多其他來源都是從在線來源獲取視頻,他們只是存儲視頻網址
  2. 我應該在resultHandler中做什麼?我會認爲這就是被我我的視頻存儲到一個全局數組

注意:下面的代碼是一個函數調用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

要顯示視頻的視頻或縮略圖(例如視頻的一個關鍵幀) – Ladislav

+0

我想顯示在集合視圖的縮略圖,但選擇後,我想播放視頻 –

回答

0

首先你一個變量添加到您的ViewController var fetchResults: PHFetchResult<PHAsset>?

然後你執行例如

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 
} 

viewDidLoad的獲取在你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 
} 

這可以在獲得批准,但將是第一次嘗試OK ,特別是看看使用PHCachingImageManager代替PHImageManager,更多關於這在下面的鏈接:

PHCachingImageManager

How to use PHCachingImageManager

如何從PHAsset播放視頻,你可以找到回答:

Swift - Playing Videos from iOS PHAsset