1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import UIKit class ImagePickerViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func changeImage(_ sender: Any) { let alertController = UIAlertController(title: "Choose Profile Picture" , message: "", preferredStyle: .actionSheet) let cameraButton = UIAlertAction(title: "Camera" , style: .default, handler: { (action) -> Void in self.openCamera() }) let galleryButton = UIAlertAction(title: "Gallery" , style: .default, handler: { (action) -> Void in self.openPhotoLibrary() }) let cancelButton = UIAlertAction(title: "Cancel" , style: .cancel, handler: { (action) -> Void in }) alertController.addAction(cameraButton) alertController.addAction(galleryButton) alertController.addAction(cancelButton) self.present(alertController, animated: true, completion: nil) } } extension ImagePickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { fileprivate func openCamera() { let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = UIImagePickerController.SourceType.camera self.present(myPickerController, animated: true, completion: nil) } fileprivate func openPhotoLibrary() { let myPickerController = UIImagePickerController() myPickerController.delegate = self; myPickerController.sourceType = UIImagePickerController.SourceType.photoLibrary self.present(myPickerController, animated: true, completion: nil) } // MARK: UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { // Dismiss the picker if the user canceled. dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // The info dictionary contains multiple representations of the image, and this uses the original. let selectedImage : UIImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage // Set image on ImageView imageView.image = selectedImage // Dismiss the picker. dismiss(animated: true, completion: nil) } } //Add these keys into Info.plist //make sure use valid description otherwise apple will reject your app //<key>NSCameraUsageDescription</key> //<string>Use camera to update your profile Pic</string> //<key>NSPhotoLibraryUsageDescription</key> //<string>lUse ibrary to update your profile Pic</string> |
warningComments are closed.