我正在使用 PHPhotoLibrary 创建一个自定义文件夹并在其中添加图片。它工作正常,但我添加到自定义文件夹的图片也添加到“相机胶卷”文件夹中。我发现这个旧线程Add photos in custom album 也添加到默认相册“Camera Roll”中,有人说这是正常行为,但由于评论来自 3 年前,我想知道最新的 iOS版本有一种方法可以仅将图片添加到自定义文件夹中。我已经搜索了一些文档来确认这一点,但没有运气。
我正在使用的代码:
class TMPhotoAlbum {
static let albumName = "Custom Album"
static let sharedInstance = TMPhotoAlbum()
var assetCollection: PHAssetCollection!
init() {
func fetchAssetCollectionForAlbum() -> PHAssetCollection! {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", TMPhotoAlbum.albumName)
let collection = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
if (collection.firstObject != nil) {
return collection.firstObject as! PHAssetCollection
}
return nil
}
if let assetCollection = fetchAssetCollectionForAlbum() {
self.assetCollection = assetCollection
return
}
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(TMPhotoAlbum.albumName)
}) { success, _ in
if success {
self.assetCollection = fetchAssetCollectionForAlbum()
}
}
}
func saveImage(image: UIImage, completion: (Bool, NSError?) -> Void) {
if assetCollection == nil {
return // If there was an error upstream, skip the save.
}
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection)
albumChangeRequest?.addAssets([assetPlaceholder!])
}, completionHandler: completion )
}
}