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
}
}
If you just want let the user choose image with UIImagePickerController use this code:
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet var imageView: UIImageView!
@IBOutlet var chooseBuuton: UIButton!
var imagePicker = UIImagePickerController()
@IBAction func btnClicked() {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
print("Button capture")
imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
self.dismiss(animated: true, completion: { () -> Void in
})
imageView.image = image
}
}
You can do like here
var avatarImageView = UIImageView()
var imagePicker = UIImagePickerController()
func takePhotoFromGallery() {
imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = true
present(imagePicker, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[.originalImage] as? UIImage {
avatarImageView.contentMode = .scaleAspectFill
avatarImageView.image = pickedImage
}
self.dismiss(animated: true)
}
Hope this was helpful
@IBAction func chooseProfilePicBtnClicked(sender: AnyObject) {
let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openCamera()
}
let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
{
UIAlertAction in
self.openGallary()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
{
UIAlertAction in
}
// Add the actions
picker.delegate = self
alert.addAction(cameraAction)
alert.addAction(gallaryAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
func openCamera(){
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
picker.sourceType = UIImagePickerControllerSourceType.Camera
self .presentViewController(picker, animated: true, completion: nil)
}else{
let alert = UIAlertView()
alert.title = "Warning"
alert.message = "You don't have camera"
alert.addButtonWithTitle("OK")
alert.show()
}
}
func openGallary(){
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(picker, animated: true, completion: nil)
}
//MARK:UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
picker .dismissViewControllerAnimated(true, completion: nil)
imageViewRef.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController){
print("picker cancel.")
}
Of course, above answers solve the main problem.
I faced a crash in Swift 3.0 while launching the photo album because Info.plist did not had these flags:
Privacy - Photo Library Usage Description -> NSPhotoLibraryUsageDescription
Privacy - Camera Usage Description -> NSCameraUsageDescription
[
Please add them if you face similar issue.
Thanks !
If you want to pick only normal image you can use below code,that check that the picked image is not panorama image.
let picker = UIImagePickerController()
func photoFromLibrary() {
self.picker.allowsEditing = true
self.picker.sourceType = .photoLibrary
//picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
self.present(self.picker, animated: true, completion: nil)
}
func shootPhoto() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
self.picker.allowsEditing = true
self.picker.sourceType = UIImagePickerControllerSourceType.camera
self.picker.cameraCaptureMode = .photo
self.picker.modalPresentationStyle = .fullScreen
self.present(self.picker,animated: true,completion: nil)
}
}
//Image picker delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let str = "\(info["UIImagePickerControllerOriginalImage"]!)"
let s = str.slice(from: "{", to: "}")
if let arr = s?.components(separatedBy: ","){
if arr.count >= 2 {
if Int(arr[0])! > 11000 {
picker.dismiss(animated:true, completion: nil)
self.makeToast("Invalid Image!!!")
return
}
}
}
}
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
self.UserImageView.image = image
}
picker.dismiss(animated:true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
picker.dismiss(animated: true, completion: nil)
}