2014-09-22 133 views
42

如何在iOS8中獲取所有相冊(包括相機膠捲(現在稱爲時刻))的列表?iOS 8照片框架:獲取iOS8所有相冊的列表

在iOS 7中,我使用ALAssetGroup枚舉塊,但不包括iOS時刻,它似乎與iOS7中的Camera Roll等效。

void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) 
    { 
     if (group == nil) {// We're done enumerating 
      return; 
     } 

     [group setAssetsFilter:[ALAssetsFilter allAssets]]; 
     if ([[sGroupPropertyName lowercaseString] isEqualToString:@"camera roll"] && nType == ALAssetsGroupSavedPhotos) { 
      [_assetGroups insertObject:group atIndex:0]; 
     } else { 
      [_assetGroups addObject:group]; 
     } 
    }; 

    // Group Enumerator Failure Block 
    void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) { 
     SMELog(@"Enumeration occured %@", [error description]); 
    }; 

    // Enumerate Albums 
    [_library enumerateGroupsWithTypes:kSupportedALAlbumsMask 
          usingBlock:assetGroupEnumerator 
          failureBlock:assetGroupEnumberatorFailure]; 
    }]; 

回答

117

使用PhotosFramework有點不同,你可以達到相同的結果,但你只需要在零件中完成。

1)獲取的所有照片(矩在iOS8上,或前相機膠捲)

PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil]; 

可選,如果你想命令他們通過創建日期,你只需要添加PHFetchOptions像這樣:

PHFetchOptions *allPhotosOptions = [PHFetchOptions new]; 
allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]]; 

PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions]; 

現在,如果你願意,你可以從PHFetchResult對象得到資產:

[allPhotosResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) { 
    NSLog(@"asset %@", asset); 
}]; 

2)獲取所有用戶的相冊(帶額外的排序,例如,只顯示相冊,有至少一張照片)

PHFetchOptions *userAlbumsOptions = [PHFetchOptions new]; 
userAlbumsOptions.predicate = [NSPredicate predicateWithFormat:@"estimatedAssetCount > 0"]; 

PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:userAlbumsOptions]; 

[userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) { 
     NSLog(@"album title %@", collection.localizedTitle); 
}]; 

對於從PHFetchResult *userAlbums返回各PHAssetCollection,你可以像這樣取PHAssets(你甚至可以限制結果只包括照片資產):

PHFetchOptions *onlyImagesOptions = [PHFetchOptions new]; 
onlyImagesOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage]; 
PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:onlyImagesOptions]; 

3)獲取智能相冊

PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil]; 
[smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) { 
     NSLog(@"album title %@", collection.localizedTitle); 
}]; 

一件事帶有S要注意如果estimatedAssetCount無法確定,則collection.estimatedAssetCount可返回NSNotFound。正如標題所示,這是估計的。如果你想確保你有進行抓取,並得到像計數資產的數目:

PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil]; 

多項資產= assetsFetchResult.count

蘋果有一個示例項目,你想要做什麼:

https://developer.apple.com/library/content/samplecode/UsingPhotosFramework/ExampleappusingPhotosframework.zip(必須是已註冊的開發人員訪問此)

+1

嘿@拉迪斯拉夫,很好的答案。但你怎麼知道使用'creationDate'作爲sortDescriptor,照片屬性是否記錄在任何地方? – snowbound 2015-07-15 03:35:24

+3

蘋果公司在此有一個非常好的文檔 - https://developer.apple.com/library/prerelease/ios/documentation/Photos/Reference/PHFetchOptions_Class/index。請看一下sortDescriptors,你會看到: 「構建帶有你想要獲取的照片實體屬性的排序描述符,如表1所列。」#://apple_ref/doc/uid/TP40014396-CH1-SW5 「例如,以下代碼按照創建日期進行排序,以查找照片庫中最舊的資源。「 表1具有可用於PHAsset,PHAssetCollection,PHCollectionList,PHCollection的所有屬性... – Ladislav 2015-07-17 17:59:04

+0

謝謝。正是我在找什麼! – snowbound 2015-07-20 06:38:13

16

這是一個簡單的@拉吉斯拉夫的高超接受的答案翻譯成斯威夫特:

// *** 1 *** 
// Get all photos (Moments in iOS8, or Camera Roll before) 
// Optionally if you want them ordered as by creation date, you just add PHFetchOptions like so: 
let allPhotosOptions = PHFetchOptions() 
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] 

let allPhotosResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: allPhotosOptions) 

// Now if you want you can get assets from the PHFetchResult object: 
allPhotosResult.enumerateObjectsUsingBlock({ print("Asset \($0.0)") }) 

// *** 2 *** 
// Get all user albums (with additional sort for example to only show albums with at least one photo) 
let userAlbumsOptions = PHFetchOptions() 
userAlbumsOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0") 

let userAlbums = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.Any, options: userAlbumsOptions) 

userAlbums.enumerateObjectsUsingBlock({ 
    if let collection = $0.0 as? PHAssetCollection { 
     print("album title: \(collection.localizedTitle)") 
     //For each PHAssetCollection that is returned from userAlbums: PHFetchResult you can fetch PHAssets like so (you can even limit results to include only photo assets): 
     let onlyImagesOptions = PHFetchOptions() 
     onlyImagesOptions.predicate = NSPredicate(format: "mediaType = %i", PHAssetMediaType.Image.rawValue) 
     if let result = PHAsset.fetchKeyAssetsInAssetCollection(collection, options: onlyImagesOptions) { 
      print("Images count: \(result.count)") 
     } 
    } 
}) 

// *** 3 *** 
// Get smart albums 

let smartAlbums = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .AlbumRegular, options: nil) // Here you can specify Photostream, etc. as PHAssetCollectionSubtype.xxx 
smartAlbums.enumerateObjectsUsingBlock({ 
    if let assetCollection = $0.0 as? PHAssetCollection { 
     print("album title: \(assetCollection.localizedTitle)") 
     // One thing to note with Smart Albums is that collection.estimatedAssetCount can return NSNotFound if estimatedAssetCount cannot be determined. As title suggest this is estimated. If you want to be sure of number of assets you have to perform fetch and get the count like: 

     let assetsFetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil) 
     let numberOfAssets = assetsFetchResult.count 
     let estimatedCount = (assetCollection.estimatedAssetCount == NSNotFound) ? -1 : assetCollection.estimatedAssetCount 
     print("Assets count: \(numberOfAssets), estimate: \(estimatedCount)") 
    } 
}) 
+0

非常感謝! – 2017-08-19 07:26:48

+0

嗨@Grimxn,我知道嗎,只能在照片庫中獲取最後導入的照片。根據創建日期排序,我們也可以獲取所有圖像。但我的要求只是取回最後導入的照片。因爲我們使用外置攝像頭拍攝照片並複製到IPAD。那麼,如何在應用程序結束時獲取「上次導入照片」? – lakshmanbob 2017-09-04 08:59:26

+0

我目前沒有處理這個問題,但我想你需要枚舉資產集合https:// developer.apple.com/documentation/photos/phassetcollection#1656287'並檢查他們的'assetCollectionType's。 .. – Grimxn 2017-09-04 12:23:35

0

試試這個代碼...

self.imageArray = [[NSArray中的alloc] INIT];

PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init]; 
requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact; 
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat; 
requestOptions.synchronous = true; 
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil]; 

NSLog(@"%d",(int)result.count); 

    PHImageManager *manager = [PHImageManager defaultManager]; 
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:countValue]; 

    // assets contains PHAsset objects. 

    __block UIImage *ima; 
    for (PHAsset *asset in result) { 
     // Do something with the asset 

     [manager requestImageForAsset:asset 
          targetSize:PHImageManagerMaximumSize 
          contentMode:PHImageContentModeDefault 
           options:requestOptions 
         resultHandler:^void(UIImage *image, NSDictionary *info) { 
          ima = image; 

          [images addObject:ima]; 

         }]; 




    self.imageArray = [images copy]; 
相關問題