这是我从PhotoLibrary获取所有资产的功能。
// MARK: Album photos
func getPhotos() {
ImageManger.photoAuthorization { (granted: Bool) in
if granted {
// Asynchronous get photos, avoid taking the main thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.photoGroups = ImageManger.photoLibrarys()
if self.photoGroups?.count == 0 {
return
}
let group = self.photoGroups?[0]
self.photoAssets = ImageManger.photoAssetsForAlbum(group!)
for asset: PHAsset in self.photoAssets! {
ImageManger.imageFromAsset(asset, isOriginal: false, toSize: CGSize(width: 150, height: 150), resultHandler: { (image: UIImage?) in
guard image != nil else {
return
}
self.photos.append(image!)
})
}
dispatch_async(dispatch_get_main_queue(), {
// Reload data
self.albumCollection.reloadData()
})
})
} else {
self.presentAccessRestrictedMessage()
}
}
}
我在getPhotos()
中调用viewWillAppear
,因为它位于TabViewController
中,当App进入前景时我也会调用getPhotos
,以便在捕获资源时同步资产。它工作得很好。
问题是,当我在PhotoLibrary中有500多个资产时,加载需要几秒钟。到那时,如果我关闭应用程序并再次重新打开,或者,如果我切换选项卡并返回到同一个控制器,即,如果我强制getPhotos()
调用,则photos
数组混乱!
当闭包仍在运行时,如果我调用getPhotos()
,则数组元素会重复。我怎么能处理这种情况呢?