項目中遇到了獲取本地所有圖片等需求,網(wǎng)上也找到了很好的教程,這里在記錄一下加深下印象。
多選圖片使用到了一個photos框架有一篇文章對這個框架講解的很詳細(xì)了。使用photos框架獲取到的圖片類型是PHAsset,PHAsset可以得到一些圖片的具體信息,可以根據(jù)項目需要來使用。

打印PHAsset
下面進(jìn)入代碼部分:
首先引入 Frameworks需要引入photos框架。然后代碼中引用包,并實現(xiàn)協(xié)議
import UIKit
import Photos
class SelectPhotoesViewController: PHPhotoLibraryChangeObserver {
// 數(shù)據(jù)源
private var photosArray = PHFetchResult()
獲取所有圖片:
func getAllPhotos() {
// 注冊通知
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
// 獲取所有系統(tǒng)圖片信息集合
let allOptions = PHFetchOptions()
// 按照時間排序
allOptions.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: true)]
// 將元素集合拆解開,此時 allResults 內(nèi)部是一個個的PHAsset單元
let allResults = PHAsset.fetchAssetsWithOptions(allOptions)
}
// 第一次獲取相冊信息,這個方法只會進(jìn)入一次
func photoLibraryDidChange(changeInstance: PHChange) {
getAllPhotos()
}
接下來就是展示圖片了,一般都是在colloectionView中展示出來所有的圖片:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell:SelectPhotosCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! SelectPhotosCollectionViewCell
PHCachingImageManager.defaultManager().requestImageForAsset(photosArray[indexPath.row] as! PHAsset, targetSize: CGSizeZero, contentMode: .AspectFit, options: nil) { (result: UIImage?, dictionry: Dictionary?) in
// 展示圖片
cell.imageView.image = result
}
return cell
}
有展示圖片也需要上傳圖片,我在項目中上傳到后臺的圖片數(shù)據(jù)是上傳的圖片的data數(shù)據(jù),首先定義一個seletedPhotosArray數(shù)組來保存選中的圖片,接著就是獲取data數(shù)據(jù)了:
func getImageData() -> NSMutableArray {
let photoArr = NSMutableArray()
for item in self.seletedPhotosArray {
PHImageManager.defaultManager().requestImageDataForAsset(item, options: nil, resultHandler: { (imageData:NSData?, dataUTI:String?, orientation:UIImageOrientation?, dictionary:Dictionary?) in
photoArr.addObject(imageData!)
})
}
return photoArr
}
然后就是根據(jù)項目需求,把數(shù)據(jù)中的圖片data數(shù)據(jù)傳給后臺即可。