環境:swift1.2, Xcode6.3
About
アルバム名を指定して画像を保存したいことがあったので作りました。
- アルバム名を指定して画像を保存することができます。
- 指定したアルバム名が存在しない場合は、アルバムを生成します。
- アルバム名は必ず1文字以上必要です。
- 保存が完了した時に以下のいずれかの結果を返すクロージャを呼び出せます。
// 保存に成功した時
PhotoAlbumUtilResult.SUCCESS
// 保存orアルバム生成orアルバムに追加が失敗した時
PhotoAlbumUtilResult.ERROR
// アプリ内で写真へのアクセス認証を一度も行っていないか、認証が許可されなかった時
PhotoAlbumUtilResult.DENIED
How to Use
Targets > General > Linked Frameworks and Libraries で以下の2つのライブラリを追加する。
※ Photos.framework を Optional で追加しないと、ios7で落ちるので注意
- AssetsLibrary.framework (Required)
- Photos.framework (Optional)
let image = UIImage()
let name = "アルバム名"
PhotoAlbumUtil.saveImageInAlbum(image, albumName: name, completion: { (result) in
switch result {
case .SUCCESS:
// 保存に成功した時
break
case .ERROR:
// 保存orアルバム生成orアルバムに追加が失敗した時
break
case .DENIED:
// アプリ内で写真へのアクセス認証を一度も行っていないか、認証が許可されなかった時
break
default:
break
}
})
Code
PhotoAlbumUtil.swift
// Must import AssetsLibrary.framework(Required), Photos.framework(Optional) from Targets > General > Linked Frameworks and Libraries
import Photos
import AssetsLibrary
enum PhotoAlbumUtilResult {
case SUCCESS, ERROR, DENIED
}
class PhotoAlbumUtil: NSObject {
class func isAuthorized() -> Bool {
if (UIDevice.currentDevice().systemVersion as NSString).floatValue < 8 {
return ALAssetsLibrary.authorizationStatus() == ALAuthorizationStatus.Authorized || ALAssetsLibrary.authorizationStatus() == ALAuthorizationStatus.NotDetermined
} else {
return PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.Authorized || PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.NotDetermined
}
}
class func saveImageInAlbum(image: UIImage, albumName: String, completion: ((result: PhotoAlbumUtilResult) -> ())?) {
if albumName.isEmpty {
completion?(result: .ERROR)
return
}
if (UIDevice.currentDevice().systemVersion as NSString).floatValue < 8 {
if !isAuthorized() {
completion?(result: .DENIED)
return
}
var found = false
let library = ALAssetsLibrary()
library.enumerateGroupsWithTypes(ALAssetsGroupAlbum, usingBlock: { (group: ALAssetsGroup!, stop: UnsafeMutablePointer<ObjCBool>) in
if group != nil {
if albumName == group.valueForProperty(ALAssetsGroupPropertyName) as! String {
found = true
library.writeImageToSavedPhotosAlbum(image.CGImage, orientation: ALAssetOrientation(rawValue: image.imageOrientation.rawValue)!, completionBlock: { (assetUrl: NSURL!, error: NSError!) in
library.assetForURL(assetUrl, resultBlock: { (asset: ALAsset!) in
group.addAsset(asset)
completion?(result: .SUCCESS)
}, failureBlock: { (error: NSError!) in
println(error.localizedDescription)
completion?(result: .ERROR)
})
})
}
} else {
if !found {
library.writeImageToSavedPhotosAlbum(image.CGImage, orientation: ALAssetOrientation(rawValue: image.imageOrientation.rawValue)!, completionBlock: { (assetUrl: NSURL!, error: NSError!) in
library.addAssetsGroupAlbumWithName(albumName, resultBlock: { (group: ALAssetsGroup!) in
library.assetForURL(assetUrl, resultBlock: { (asset: ALAsset!) in
group.addAsset(asset)
completion?(result: .SUCCESS)
}, failureBlock: { (error: NSError!) in
println(error.localizedDescription)
completion?(result: .ERROR)
})
}, failureBlock: { (error: NSError!) in
println(error.localizedDescription)
completion?(result: .ERROR)
})
})
}
}
}, failureBlock: { (error: NSError!) in
println(error.localizedDescription)
completion?(result: .ERROR)
})
} else {
if !isAuthorized() {
completion?(result: .DENIED)
return
}
var assetAlbum: PHAssetCollection?
let list = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.Any, options: nil)
list.enumerateObjectsUsingBlock{ (album, index, isStop) in
let assetCollection = album as! PHAssetCollection
if albumName == assetCollection.localizedTitle {
assetAlbum = assetCollection
isStop.memory = true
}
}
if let album = assetAlbum {
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let result = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
let assetPlaceholder = result.placeholderForCreatedAsset
let albumChangeRequset = PHAssetCollectionChangeRequest(forAssetCollection: album)
albumChangeRequset.addAssets([assetPlaceholder])
}, completionHandler: { (isSuccess: Bool, error: NSError!) in
if isSuccess {
completion?(result: .SUCCESS)
} else{
println(error.localizedDescription)
completion?(result: .ERROR)
}
})
} else {
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albumName)
}, completionHandler: { (isSuccess, error) in
self.saveImageInAlbum(image, albumName: albumName, completion: completion)
})
}
}
}
}