2014-09-26 37 views
17

在iOS 8的Photos.framework中,我試圖將UIImage保存到用戶的照片庫中,這與您可以在Safari中長按圖像並選擇「保存圖像」的方式非常相似。在iOS 7中,這可以通過調用ALAssetLibrary的writeImageToSavedPhotosAlbum:metadata:completionBlock來完成。哪個PHAssetCollection用於保存圖像?

對於iOS 8,我們需要選擇一個資產集合來添加一個PHAsset,但我無法弄清楚哪個PHAssetCollection最接近保存到用戶的「相機膠捲」(即使沒有一個,真的,在iOS 8)

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ 
    PHAssetChangeRequest *newAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image]; 
    newAssetRequest.creationDate = time; 
    newAssetRequest.location = location; 

    PHObjectPlaceholder *placeholderAsset = newAssetRequest.placeholderForCreatedAsset; 

    PHAssetCollectionChangeRequest *addAssetRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:WHICH_ASSET_COLLECTION]; 
    addAssetRequest addAssets:@[placeholderAsset]; 

} completionHandler:^(BOOL success, NSError *error) { 
    NSLog(@"Success: %d", success); 
}]; 

我試着訪問「最近添加」的智能相冊,但它不允許添加新的內容。

回答

29

您不需要搞亂PHAssetCollection。剛剛加入:

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ 
     PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:<#your photo here#>]; 
    } completionHandler:^(BOOL success, NSError *error) { 
     if (success) { 
      <#your completion code here#> 
     } 
     else { 
      <#figure out what went wrong#> 
     } 
    }]; 
+0

在完成處理程序中,您如何獲得新資產? – 2014-12-29 04:34:40

+1

根據文檔,您可以使用@property(nonatomic,strong,readonly)PHObjectPlaceholder * placeholderForCreatedAsset',如果您需要引用由同一個變更塊中的變更請求創建的資產,請使用此屬性。以下代碼在包含在照片庫更改區塊中時創建資產,然後將其添加到集合中:「 有關佔位符的更多信息,我建議您閱讀[文檔](https://developer.apple.com /library/prerelease/ios/documentation/Photos/Reference/PHObjectPlaceholder_Class/index.html)。 – 2014-12-29 15:41:18

+0

我已經嘗試過佔位符對象。該示例將佔位符對象添加到相冊更改請求中,但是仍在維護一組資源。將佔位符對象添加到數組不起作用。 – 2014-12-29 15:51:30

6

其實在8.1相機膠捲回來了。這是智能相冊,其子類型爲SmartAlbumUserLibrary。

+0

順便說一句,你已經很好地理解了佔位符是什麼。 – matt 2014-11-13 18:00:22

+0

我想如果他嘗試將它添加到該'ALAssetCollection',它仍然是隻讀的,無法添加。只要在我的回答中添加它就可以做到他想要的。 – 2014-11-13 18:07:59

+0

@SushiGrassJacob相機膠捲是可寫的。 – matt 2014-11-13 19:01:31