I am writing my first iOS application (iPhone only) with Swift. The main application view should allow user to choose the image from the photo gallery.
I\'ve found
here is an easy way to do it:
but first you have to add ( Privacy - Photo Library Usage Description ) in the info.plist, and you should have a button and a UIImageView in your viewController.
then create an outlet of the UIImageView ( in this code the outlet is called myImage), and an action of the button ( I called the action importing in my code )
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet weak var myImage: UIImageView!
@IBAction func importing(_ sender: Any) {
let Picker = UIImagePickerController()
Picker.delegate = self
Picker.sourceType = .photoLibrary
self.present(Picker, animated: true, completion: nil)
Picker.allowsEditing = true
Picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
}
func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any])
{
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //1
myImage.contentMode = .scaleAspectFit //2
myImage.image = chosenImage //3
dismiss(animated:true, completion: nil) //4
}
}