Dies wird Fotoalbum erstellen und in diesem Album speichern.
ich kam mit diesen Singletonklasse bis es zu handhaben:
import Photos
class CustomPhotoAlbum {
static let albumName = "Titanium"
static let sharedInstance = CustomPhotoAlbum()
var assetCollection: PHAssetCollection!
init() {
func fetchAssetCollectionForAlbum() -> PHAssetCollection! {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
let collection = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
if let firstObject: AnyObject = collection.firstObject {
return collection.firstObject as! PHAssetCollection
}
return nil
}
if let assetCollection = fetchAssetCollectionForAlbum() {
self.assetCollection = assetCollection
return
}
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomPhotoAlbum.albumName)
}) { success, _ in
if success {
self.assetCollection = fetchAssetCollectionForAlbum()
}
}
}
func saveImage(image: UIImage) {
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: nil)
}
}
Wenn Sie zuerst die Klasse instanziiert, wird das benutzerdefinierte Album erstellt werden, wenn es nicht bereits vorhanden ist. Sie können ein Bild wie folgt speichern:
CustomPhotoAlbum.sharedInstance.saveImage(image)
HINWEIS: Die CustomPhotoAlbum Klasse übernimmt die App hat bereits die Erlaubnis, die Foto-Bibliothek zugreifen. Der Umgang mit den Berechtigungen ist etwas außerhalb des Rahmens dieser Frage/Antwort. So stellen Sie sicher, dass PHPhotoLibrary.authorizationStatus() == .Authorize, bevor Sie es verwenden. Und wenn nötig Autorisierung anfordern.