1

显示实时照片:

func fetchLivePhotos() {

    let options = PHFetchOptions()

    options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ]

    options.predicate = NSPredicate(format: "(mediaSubtype & %d) != 0",PHAssetMediaSubtype.photoLive.rawValue)

    DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
        self.livePhotoAssets = PHAsset.fetchAssets(with: options)

        DispatchQueue.main.async {
            self.collectionView?.reloadData()
        }
    }
}

并在网格代码中显示如下:

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MediaCell", for: indexPath) as! MediaCell

        if let asset = livePhotoAssets?[indexPath.row]{
            let options = PHImageRequestOptions()
            options.isNetworkAccessAllowed = true

            let targetSize = CGSize(width: 200, height: 200)
            PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: options, resultHandler: { (image: UIImage?, info: [AnyHashable : Any]?) in
                cell.backgroundImageView.image = image
            })
        }

        cell.selectedImage.isHidden = true
        return cell
    }

而对于获取视频,我正在使用这个谓词:

  option.predicate = NSPredicate(format: "mediaType == %i",PHAssetMediaType.video.rawValue)

但是在 Collectionview 中两者都没有显示。

4

1 回答 1

0

尝试覆盖 UICollectionViewDataSource 协议中的方法:

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if let count = livePhotoAssets?.count {
        return count
    }
    return 0
}

还:

不要忘记将 ViewController 设置为表视图数据源。如果您是从情节提要创建它,请不要忘记在情节提要中附加 collectionView 属性。

我已经构建了它并且可以完美运行。

于 2018-03-31T15:24:30.660 回答