Choosing Photo with UIImagePickerController
First of all, in the file ViewController.swift
, image view, label and button clicked function are defined.
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// ...
}
@IBAction func selectBtnTapped(_ sender: Any) {
// ...
}
Before implementing the selectBtnTapped
method, you need to declare UIImagePickerControllerDelegate
and UINavigationControllerDelegate
next to UIViewController
to use Picker View.
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
...
It's ready to implement picker view now.
@IBAction func selectBtnTapped(_ sender: Any) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = .photoLibrary
self.present(picker, animated: true, completion: nil)
}
And thaen, implement the didFinishPickingMediaWithInfo
function to complete the photo selection.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imageView.image = info[UIImagePickerControllerEditedImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
Finally, in the Info.plist
file we create a row named "Privacy - Photo Library Usage Description". In section "Value" you can write the message you want.