Image picker (UIImagePickerController)
UIImagePickerController allows to pick image or video from photo library on device.
App must have the permission to access the photo library. So you need add following keys with description to the app info.plist.
- NSCameraUsageDescription - allows to use camera
- NSPhotoLibraryUsageDescription - allows to use photo library
There are three types of image source:
- .camera
- .photoLibrary
- .savedPhotosAlbum
Use the key .editedImage in the picker delegate if imagePicker.allowsEditing is set to true, or .originalImage in otherwise.
image picker example
class MyController: UIVIewController {
private lazy var photoImageView: UIImageView = {
let v = UIImageView()
// v.contentMode = .scaleAspectFit
v.layer.cornerRadius = 4
return v
}()
func selectImage() {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.mediaTypes = ["public.image", "public.movie"]
imagePicker.sourceType = .camera
present(imagePicker, animated: true) {
print("imagePicker presented")
}
}
func setupLayout {
// ...
}
// ...
}
// MARK: - UIImagePickerControllerDelegate
extension MyController: UIImagePickerControllerDelegate {
func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.editedImage] as? UIImage else { return }
photoImageView.image = image
for constrain in photoImageView.constraints where
constrain.identifier == "photoImageViewHeight"
{ constrain.constant = 158 }
photoImageView.layoutIfNeeded()
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}