How to save picture to iPhone photo library?
You can use this function:
UIImageWriteToSavedPhotosAlbum(UIImage *image,
id completionTarget,
SEL completionSelector,
void *contextInfo);
You only need completionTarget, completionSelector and contextInfo if you want to be notified when the UIImage
is done saving, otherwise you can pass in nil
.
See the official documentation for UIImageWriteToSavedPhotosAlbum()
.
Take a photo and save to photo library in Swift
Use below code for an image taken from Photo Gallery and save inside photo library.
Code Support for Swift 3.1 & 4.0 version:
First, we have to do the setup for Permissions inside Project's .plist file:-
1) Camera
<key>NSCameraUsageDescription</key>
<string>This app will use camera.</string>
2) Photo Library
<key>NSPhotoLibraryUsageDescription</key>
<string>You can select photos to attach to reports.</string>
3) Save to Photo Library
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Please allow access to save photo in your photo library</string>
We need to open .pilst file as a Source code type then add permissions inside -
After That
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var imageTake: UIImageView!
var imagePicker: UIImagePickerController!
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - Take image
@IBAction func takePhoto(_ sender: UIButton) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}
//MARK: - Saving Image here
@IBAction func save(_ sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(imageTake.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
//MARK: - Add image to Library
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
//MARK: - Done image capture here
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imagePicker.dismiss(animated: true, completion: nil)
imageTake.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
}
Swift 4.2 Code update -
class ViewController: UIViewController, UINavigationControllerDelegate {
@IBOutlet weak var imageTake: UIImageView!
var imagePicker: UIImagePickerController!
enum ImageSource {
case photoLibrary
case camera
}
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - Take image
@IBAction func takePhoto(_ sender: UIButton) {
guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
selectImageFrom(.photoLibrary)
return
}
selectImageFrom(.camera)
}
func selectImageFrom(_ source: ImageSource){
imagePicker = UIImagePickerController()
imagePicker.delegate = self
switch source {
case .camera:
imagePicker.sourceType = .camera
case .photoLibrary:
imagePicker.sourceType = .photoLibrary
}
present(imagePicker, animated: true, completion: nil)
}
//MARK: - Saving Image here
@IBAction func save(_ sender: AnyObject) {
guard let selectedImage = imageTake.image else {
print("Image not found!")
return
}
UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
//MARK: - Add image to Library
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
showAlertWith(title: "Save error", message: error.localizedDescription)
} else {
showAlertWith(title: "Saved!", message: "Your image has been saved to your photos.")
}
}
func showAlertWith(title: String, message: String){
let ac = UIAlertController(title: title, message: message, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
extension ViewController: UIImagePickerControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
imagePicker.dismiss(animated: true, completion: nil)
guard let selectedImage = info[.originalImage] as? UIImage else {
print("Image not found!")
return
}
imageTake.image = selectedImage
}
}
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);
}
Save a photo to a folder in photo library
First you need to create a folder:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library addAssetsGroupAlbumWithName:folderName
resultBlock:^(ALAssetsGroup *group)
{
NSLog(@"Added folder:%@", folderName);
}
failureBlock:^(NSError *error)
{
NSLog(@"Error adding folder");
}];
Then, find the folder:
__block ALAssetsGroup* folder;
[library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:folderName])
{
folder = group;
}
}
failureBlock:^(NSError* error)
{
// Error handling.
}];
And add your photo to it.
Save the Image to Asset Library, and put it into the album:
[library writeImageToSavedPhotosAlbum:yourImage
metadata:[info objectForKey:UIImagePickerControllerMediaMetadata]
completionBlock:^(NSURL* assetURL, NSError* error)
{
if (error.code == 0)
{
// Get the asset
[library assetForURL:assetURL
resultBlock:^(ALAsset *asset)
{
// Assign the photo to the album
[folder addAsset:asset];
}
failureBlock:^(NSError* error)
{
// Error handling.
}];
}
else
{
// Error handling.
}
}];
Related Topics
Opening the Settings App from Another App
How to Input Currency Format on a Text Field (From Right to Left) Using Swift
How to Find Current Visible Viewcontroller in Ios
How to Add Pagecontrol Inside Uicollectionview Image Scrolling
How to Determine the Current Iphone/Device Model
Best Way to Check If Object Is Out of Bounds in Array
How to Size a Uitextview to Its Content
What Happens When Testflight App Expire
Iphone 6 and 6 Plus Media Queries
Vertically Align Text to Top Within a Uilabel
Transport Security Has Blocked a Cleartext Http
How to Set Up a Simple Delegate to Communicate Between Two View Controllers
Loading/Downloading Image from Url on Swift
Scrolling Issue on Position Fixed Element on Ios
Iphone/Ipad: How to Make Uitextfield Readonly (But Not Disabled)