How can I save an image to the camera roll?
You use the UIImageWriteToSavedPhotosAlbum()
function.
//Let's say the image you want to save is in a UIImage called "imageToBeSaved"UIImageWriteToSavedPhotosAlbum(imageToBeSaved, nil, nil, nil);
Edit:
//ViewController.m- (IBAction)onClickSavePhoto:(id)sender{ UIImageWriteToSavedPhotosAlbum(imageToBeSaved, nil, nil, nil);}
Here's an answer for iOS8+ using the Photos framework.
Objective-C:
#import <Photos/Photos.h>UIImage *snapshot = self.myImageView.image;[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:snapshot]; changeRequest.creationDate = [NSDate date];} completionHandler:^(BOOL success, NSError *error) { if (success) { NSLog(@"successfully saved"); } else { NSLog(@"error saving to photos: %@", error); }}];
Swift:
// Swift 4.0import Photoslet snapshot: UIImage = someImagePHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAsset(from: snapshot)}, completionHandler: { success, error in if success { // Saved successfully! } else if let error = error { // Save photo failed with error } else { // Save photo failed with no error }})
Here's a link to the Apple documentation.
Don't forget to add the appropriate key/value to your info.plist to request permission to access the photo library:
<key>NSCameraUsageDescription</key><string>Enable camera access to take photos.</string><key>NSPhotoLibraryUsageDescription</key><string>Enable photo library access to select a photo from your library.</string><key>NSPhotoLibraryAddUsageDescription</key><string>Enable photo library access to save images to your photo library directly from the app.</string>
For reference, you can save videos in a similar manner:
UISaveVideoAtPathToSavedPhotosAlbum(videoPath, nil, nil, nil);
You might want to save a video to upload to Instagram, for example:
// Save video to camera roll; we can share to Instagram from there.-(void)didTapShareToInstagram:(id)sender { UISaveVideoAtPathToSavedPhotosAlbum(self.videoPath, self, @selector(video:didFinishSavingWithError:contextInfo:), (void*)CFBridgingRetain(@{@"caption" : caption}));}- (void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfoPtr { NSDictionary *contextInfo = CFBridgingRelease(contextInfoPtr); NSString *caption = contextInfo[@"caption"]; NSString *escapedString = [videoPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]; // urlencodedString NSString *escapedCaption = [caption stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]; // urlencodedString NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@", escapedString, escapedCaption]]; [[UIApplication sharedApplication] openURL:instagramURL];}