1、在viewDidLoad注册通知
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
2、在函数photoLibraryDidChange下添加如下内容
dispatch_async(dispatch_get_main_queue()) {
let collectionChanges = changeInstance.changeDetailsForFetchResult(self.allResults)
if collectionChanges != nil {
// 是否变化
if collectionChanges!.hasIncrementalChanges {
// 监听增加或者删除
if (collectionChanges!.insertedObjects.count > 0) || (collectionChanges!.removedObjects.count > 0) {
self.allResults = collectionChanges?.fetchResultAfterChanges
self.photosA = self.allResults
self.imageCollectionView.reloadData()
}
} else {
// 首次的时候走这里
if collectionChanges!.fetchResultBeforeChanges.count == 0 {
self.allResults = collectionChanges?.fetchResultAfterChanges
self.photosA = self.allResults
self.imageCollectionView.reloadData()
}
}
}
}
3、在cellForItemAtIndexPath里显示自定义的CollectionView
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellID", forIndexPath: indexPath) as! MyCollectionViewCell
PHCachingImageManager.defaultManager().requestImageForAsset(PCommon.photosA![PCommon.photosA!.count - indexPath.row - 1] as! PHAsset, targetSize: CGSizeZero, contentMode: .AspectFit, options: nil) { (result: UIImage?, dictionry: Dictionary?) in
cell.imageView.image = result ?? UIImage.init(named: "默认的图片")
}
至此,照片就很方便的展示在自定义的CollectionView中。
网友评论