Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow the user to pick a photo from his camera roll or photo library?

Tags:

ios

iphone

camera

I'm making a little photo editing app for fun. Users must select a photo from their camera roll which will then be imported for modification.

How does this generally work? I have seen many apps allowing this with a standard controller that looks always the same.

Is it also possible to access this library directly or to customize the appearance of that controller?

Where should I start looking?

like image 722
Proud Member Avatar asked May 24 '11 12:05

Proud Member


1 Answers

The easiest way to do this is by using the UIImagePickerController in a simple alertView.

For example, you want someone to tap on their profile picture and be able to set a new image from either their camera or their photo library.

enter image description here

@IBAction func btnProfilePicTap(sender: AnyObject) {
    let picker = UIImagePickerController()
    picker.delegate = self
    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {
        action in
        picker.sourceType = .camera
        self.present(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: {
        action in
        picker.sourceType = .photoLibrary
        self.present(picker, animated: true, completion: nil)
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

Then simply add the delegate and you're done.

extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
        //use image here!
        dismiss(animated: true, completion: nil)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}

Sorry, this example is in swift but I hope it still helps.

EDIT: Updated for Swift 5.

like image 54
William T. Avatar answered Oct 16 '22 00:10

William T.