-2

I want to list all photos from "My Photo Stream", here is my code:

private func fetchAssetCollection(){
    let result = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumMyPhotoStream, options: nil)
    result.enumerateObjects({ (collection, index, stop) in
        if let albumName = collection.localizedTitle {
            print("Album => \(collection.localIdentifier), \(collection.estimatedAssetCount), \(albumName) ")
        }

        let assResult = PHAsset.fetchAssets(in: collection, options: nil)

        let options = PHImageRequestOptions()
        options.resizeMode = .exact
        let scale = UIScreen.main.scale
        let dimension = CGFloat(78.0)
        let size = CGSize(width: dimension * scale, height: dimension * scale)

        assResult.enumerateObjects({ (asset, index, stop) in
            print("index \(index)")
            PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: options) { (image, info) in
                if let name = asset.originalFilename {
                    print("photo \(name) \(index) \(asset.localIdentifier)")
                }
            }

        })

    })
}



extension PHAsset {

var originalFilename: String? {

    var fname:String?

    if #available(iOS 9.0, *) {
        let resources = PHAssetResource.assetResources(for: self)
        if let resource = resources.first {
            fname = resource.originalFilename
        }
    }

    if fname == nil {
        // this is an undocumented workaround that works as of iOS 9.1
        fname = self.value(forKey: "filename") as? String
    }

    return fname
}

}

it works, but the problem is that it print duplicated record. It prints 329*2 records but actually I have 329 photos in my "My Photo stream".

photo IMG_0035.JPG 10 0671E1F3-CB7C-459E-8111-FCB381175F29/L0/001
photo IMG_0035.JPG 10 0671E1F3-CB7C-459E-8111-FCB381175F29/L0/001
......
4

1 回答 1

2

从文档中PHImageManager requestImage

默认情况下,此方法异步执行。如果您从后台线程调用它,您可以isSynchronous将 options 参数的属性更改true为阻止调用线程,直到请求的图像准备好或发生错误,此时 Photos 会调用您的结果处理程序。

对于异步请求,照片可能会多次调用您的结果处理程序块。照片首先调用该块以提供适合临时显示的低质量图像,同时准备高质量图像。(如果低质量图像数据立即可用,则第一次调用可能会在方法返回之前发生。)当高质量图像准备好时,Photos 会再次调用您的结果处理程序来提供它。如果图像管理器已经以完整质量缓存了请求的图像,则照片只调用一次结果处理程序。结果处理程序的 info 参数中的PHImageResultIsDegradedKey键指示照片何时提供临时低质量图像。

因此,要么使请求同步,要么检查字典中的PHImageResultIsDegradedKey值,info以查看该图像实例是否是您真正希望保留或忽略的实例。

于 2017-04-05T17:04:21.753 回答