Swift之獲取本地所有圖片

項目中遇到了獲取本地所有圖片等需求,網(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ù)傳給后臺即可。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容