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
For Swift 3:
First, you need to add the following key in info.plist:
NSPhotoLibraryUsageDescription
This app requires access to the photo library.
Your View controller needs to conform to the following protocols:
UIImagePickerControllerDelegate, UINavigationControllerDelegate:
class ImagePickerViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {}
You need to declare the UIImage you will be useing to bind the returned/selected image:
@IBOutlet weak var myImageView: UIImageView!
@IBoutlet weak var upLoadImageBtn:UIImage!
let imagePicker = UIImagePickerController()
Set the pickerImage delegate to be your ViewController:
imagePicker.delegate = self
For the upload button, you will need to link to the following image in order to fire the action and display the image picker:
@IBAction func upLoadImageBtnPressed(_ sender: AnyObject) {
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
/*
The sourceType property wants a value of the enum named UIImagePickerControllerSourceType, which gives 3 options:
UIImagePickerControllerSourceType.PhotoLibrary
UIImagePickerControllerSourceType.Camera
UIImagePickerControllerSourceType.SavedPhotosAlbum
*/
present(imagePicker, animated: true, completion: nil)
}
Your View controller needs to implement the delegate methods for the image picker delegates:
// MARK: - ImagePicker Delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
myImageView.contentMode = .scaleAspectFit
myImageView.image = pickedImage
}
/*
Swift Dictionary named “info”.
We have to unpack it from there with a key asking for what media information we want.
We just want the image, so that is what we ask for. For reference, the available options are:
UIImagePickerControllerMediaType
UIImagePickerControllerOriginalImage
UIImagePickerControllerEditedImage
UIImagePickerControllerCropRect
UIImagePickerControllerMediaURL
UIImagePickerControllerReferenceURL
UIImagePickerControllerMediaMetadata
*/
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion:nil)
}