How can I save an image to the camera roll?

2019-01-07 03:33发布

问题:

I am new to Xcode (using 4.3) and am not sure how to save an image to the device's camera roll. All that I have done so far is set up an IBAction for the button to save the image. What library method or function can I use to save an image to the user's camera roll?

回答1:

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);
}


回答2:

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.0
import Photos

let snapshot: UIImage = someImage

PHPhotoLibrary.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>


回答3:

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];
}