【问题标题】:How to display Live-photos Videos from library and display in Collection-View in iOS Swift?如何在 iOS Swift 中显示库中的实时照片视频并在 Collection-View 中显示?
【发布时间】:2018-03-31 13:22:44
【问题描述】:

用于显示实时照片:

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 中两者都不显示。

【问题讨论】:

    标签: ios swift xcode phphotolibrary apple-live-photos


    【解决方案1】:

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

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

    还有:

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

    我已经构建了它并且运行良好。

    【讨论】:

    • 我还使用操作表显示实时照片和视频,但我需要在不使用操作表的情况下显示两者。
    • 使用操作表是什么意思?
    猜你喜欢
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    相关资源
    最近更新 更多