I'm trying to save a UIImage to the camera roll.
Apple made the UIImageWriteToSavedPhotosAlbum
deprecated, therefore I'm avoiding using that (same for ALAssets
), which forces to use PhotoLibrary
.
This is the code I'm using:
definition:
var rollCollection : PHAssetCollection!;
Initialization:
let result = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: nil);
rollCollection = result.firstObject as? PHAssetCollection;
Code to save the picture:
if (rollCollection != nil){
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(
self.originalImg!);
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.rollCollection!);
let assetPlaceHolder = assetRequest.placeholderForCreatedAsset;
albumChangeRequest!.addAssets([assetPlaceHolder!])
}, completionHandler: { success, error in
dispatch_async(dispatch_get_main_queue(), {
print ("\(error!)");
if (!success){
self.presentViewController(self.alertCantSave!, animated: false, completion: nil);
}
else {
self.presentViewController(self.alertSaved!, animated: false, completion: nil);
}
});
})
}
else {
dispatch_async(dispatch_get_main_queue(), {
self.presentViewController(self.alertCantSave!, animated: false, completion: nil);
});
}
Every time I am trying to save an image I get the following error:
Error Domain=NSCocoaErrorDomain Code=-1 "(null)"
Any ideas? I couldn't find any explanation, and everywhere I looked for I found a code snippet similar to mine (including Apple's documentation: https://developer.apple.com/library/ios/documentation/Photos/Reference/PHPhotoLibrary_Class/)
Thanks.
I just found this question after looking for the exact same thing for a couple of hours.
Playing around a little bit I was able to come up with an answer that worked for me, so I'm sharing it here just in case any one else comes looking for something similar in the future.
// Make sure the image is not nil
guard let image = image else {
// No image here...
return
}
// Perform changes to the library
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
// You only need to create the request, there is no need to define the placeholder
// nor to add the asset because swift does not like it when you try to modify the camera roll.
PHAssetChangeRequest.creationRequestForAssetFromImage(image)
}, completionHandler: { success, error in
// Same as what you have...
})
Check out this answer if you want an example of how to save images to custom albums and to query images from a custom album. Save images with PHImageManager
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With