Save image to photo library using photo framework
All you need to do is trigger a creation request. As the error says, you can access the change request only inside the performChanges
block.
So to save the image you would do something like this:
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:[info valueForKey:UIImagePickerControllerOriginalImage]];
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
NSLog(@"Success");
}
else {
NSLog(@"write error : %@",error);
}
}];
In case you need to do something with the placeholder of the newly created asset, you can access it inside the same performChanges
block:
PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:[info valueForKey:UIImagePickerControllerOriginalImage]];
PHObjectPlaceholder *assetPlaceholder = changeRequest.placeholderForCreatedAsset;
In Swift 3 I do this to save the video to the library.
if mediaType.isEqual(to: (kUTTypeMovie as NSString) as String) {
if let videoURL = info[UIImagePickerControllerMediaURL] as? URL {
PHPhotoLibrary.shared().performChanges({
_ = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
}, completionHandler: { (success, error) in
if success {
print("ok")
let videoData = NSData(contentsOf: videoURL)
// use videoData here if needed...
if let posterImage = self.firstFrame(videoURL: videoURL) {
self.imageView.image = posterImage
}
picker.dismiss(animated: true) { () -> Void in
}
} else {
print(error?.localizedDescription)
}
})
}
}