2015-08-23 86 views
3

如何取回所有圖片來自自定義相冊?如何從自定義相冊獲取所有圖片 - swift

var fetchOptions = PHFetchOptions() 
fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)] 
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue) 
let allImages:PHFetchResult = PHAsset.fetchKeyAssetsInAssetCollection(albumList[index].collection, options: fetchOptions) 

此代碼塊僅提取其中的幾個。 謝謝。

- >albumList[index].collection的類型是PHAssetCollection

回答

6

使用這個答案https://stackoverflow.com/a/28904792/4795651編輯一點點自己。

import Photos 


func FetchCustomAlbumPhotos() 
{ 
    var albumName = "SwiftAlbum" 
    var assetCollection = PHAssetCollection() 
    var albumFound = Bool() 
    var photoAssets = PHFetchResult() 

    let fetchOptions = PHFetchOptions() 
    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName) 
    let collection:PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions) 

    if let first_Obj:AnyObject = collection.firstObject{ 
     //found the album 
     assetCollection = collection.firstObject as! PHAssetCollection 
     albumFound = true 
    } 
    else { albumFound = false } 
    var i = collection.count 
    photoAssets = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil) 
    let imageManager = PHCachingImageManager() 

    //  let imageManager = PHImageManager.defaultManager() 

    photoAssets.enumerateObjectsUsingBlock{(object: AnyObject!, 
     count: Int, 
     stop: UnsafeMutablePointer<ObjCBool>) in 

     if object is PHAsset{ 
      let asset = object as! PHAsset 
      print("Inside If object is PHAsset, This is number 1") 

      let imageSize = CGSize(width: asset.pixelWidth, 
       height: asset.pixelHeight) 

      /* For faster performance, and maybe degraded image */ 
      let options = PHImageRequestOptions() 
      options.deliveryMode = .FastFormat 
      options.synchronous = true 

      imageManager.requestImageForAsset(asset, 
       targetSize: imageSize, 
       contentMode: .AspectFill, 
       options: options, 
       resultHandler: { 
        (image, info) -> Void in 
        self.photo = image! 
        /* The image is now available to us */ 
        self.addImgToArray(self.photo) 
        print("enum for image, This is number 2") 

      }) 

     } 
    } 
} 

func addImgToArray(uploadImage:UIImage) 
{ 
    self.images.append(uploadImage) 

} 
+0

你能更新這個答覆對於iOS 11嗎? –

相關問題