How to Use Image Picker in iOS: Swift Guide for Beginners

Опубликовано: 03 Октябрь 2024
на канале: Divyesh Gondaliya
7,197
35

In this tutorial you are going to learn the basics on how to deal with UIImagePickerController to add photos from the users Photo Library into your app.

Facebook Page :-   / iosinfoandknowledge  

Collectionview inside ScrollView :-    • Collectionview inside Scrollview  
Dynamic height TableView in a Scroll View :-    • Dynamic height TableView in a Scroll ...  

My Social Media link is below
-------------
instagram :-   / gdivyesh40  
facebook :- https://www.facebook.com/profile.php?...


Note: This tutorial has been updated (08/01/2018) to use Xcode 9.2, iOS 11.2, and Swift 4.

Delegate:- UIImagePickerControllerDelegate, UINavigationControllerDelegate

let imagePicker = UIImagePickerController()

//in did load
imagePicker.delegate = self


///Button Tap
let alert = UIAlertController(title: "Racecap", message: "Please Select an Option", preferredStyle: .actionSheet)

alert.addAction(UIAlertAction(title: "Choose from photos", style: .default , handler:{ (UIAlertAction)in
self.imagePicker = UIImagePickerController()
self.imagePicker.delegate = self
self.imagePicker.sourceType = .photoLibrary
self.imagePicker.allowsEditing = false
self.present(self.imagePicker, animated: true, completion: nil)
}))

alert.addAction(UIAlertAction(title: "Take a picture", style: .default , handler:{ (UIAlertAction)in
self.imagePicker = UIImagePickerController()
self.imagePicker.delegate = self
self.imagePicker.sourceType = .camera
self.imagePicker.allowsEditing = false
self.present(self.imagePicker, animated: true, completion: nil)
}))

alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
}))

self.present(alert, animated: true, completion: {
print("completion block")
})



// UIImagePickerControllerDelegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imgview.image = image
} else{
print("Something went wrong")
}
dismiss(animated: true, completion: nil)
}