2015-11-12 55 views
2

當我推出一個照片取象:獲取使用PHAssetCollection.fetchAssetCollectionsWithType在迅速從特定相冊的照片()

let assetCollections: PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .Any, options: nil) 

我得到幾張專輯的結果,這樣我就可以通過數組進行迭代,並把自己的冠軍在一個tableView中。

但是:當我使用一個謂詞來過濾並獲得例如專輯「Camera Roll」時,結果總是一個空數組:(並且我知道100%確定Camera Roll存在,因爲它沒有提取它的零選項)

let fetchOptions = PHFetchOptions() 
fetchOptions.predicate = NSPredicate(format: "title = %@", "Camera Roll") 
let assetCollections: PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .Any, options: fetchOptions) 
let album: PHAssetCollection = assetCollections.firstObject as! PHAssetCollection 

我讀過的人4或5個不同的方法在網上,他們都有這個斷言是否符合 「稱號=%@」,或 「localizedTitle =%@」 或 「localizedIdentifier =%@」 ...我沒有得到它。似乎爲人們工作,而不是爲我工作。編譯器在試圖「解包無可選值」的最後一行崩潰('取得結果爲空')。爲什麼只要包含提取選項,搜索就返回零?

回答

1

的解決方案似乎是使用:

PHAssetCollection.fetchAssetCollectionsWithLocalizedIdentifiesr(identifiers: [String], options: PHFetchOptions) 

因此,傳遞到參數「標識」和我們希望獲取專輯的標題字符串數組實現了相同的結果不是試圖謂詞方法,似乎不再工作。

+0

雖然這段代碼可能會回答這個問題,但最好解釋它如何解決問題而不介紹其他人以及爲什麼要使用它。從長遠來看,僅有代碼的答案是沒有用的。 – JAL

0

嘗試格式:

fetchOptions.predicate = NSPredicate(format: "%K == %@", "title", "Camera Roll")

fetchOptions.predicate = NSPredicate(format: "%K LIKE[cd] %@", "title", "Camera Roll")

4

如果您希望相機膠捲專輯,你可能會更好過要求它象徵:

let collections = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: nil) 

The SmartAlbumUserLibrary子類型是你如何獲得相機膠捲(並不總是被稱爲那個)。

0

如果你想相機膠捲ablbum而已,你可以嘗試這樣的事:

func getCameraRoll() -> AlbumModel { 
     var cameraRollAlbum : AlbumModel! 

     let cameraRoll = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil) 

     cameraRoll.enumerateObjects({ (object: AnyObject!, count: Int, stop: UnsafeMutablePointer) in 
     if object is PHAssetCollection { 
      let obj:PHAssetCollection = object as! PHAssetCollection 

      let fetchOptions = PHFetchOptions() 
      fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] 
      fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) 
      let assets = PHAsset.fetchAssets(in: obj, options: fetchOptions) 

      if assets.count > 0 { 
      let newAlbum = AlbumModel(name: obj.localizedTitle!, count: assets.count, collection:obj, assets: assets) 

      cameraRollAlbum = newAlbum 
      } 
     } 
     }) 
    return cameraRollAlbum 

    } 

請注意,您應該AlbumModel是我創建了一個模型,你可以改變它,用你自己的數據模型。

相關問題