Swift - ImagePicker not executing delegate - ios

I just want to display an image taken with the iPhone camera in a ImageView. That was the first step of the project but it doesn't work...
Here is my code :
import UIKit
import MobileCoreServices
class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var scanButton: UIButton!
#IBOutlet weak var textfield: UITextField!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.imagePicker.modalPresentationStyle = UIModalPresentationStyle.currentContext
self.imagePicker.delegate = self
self.imagePicker.mediaTypes = [kUTTypeImage as String]
self.imagePicker.sourceType = .camera
self.imagePicker.allowsEditing = true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Actions
#IBAction func scanAction(_ sender: UIButton) {
print("----- scanAction -----");
self.present(self.imagePicker, animated: true, completion: nil)
}
//MARK: - UIImagePickerControllerDelegate
private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print("----- didFinishPickingMediaWithInfo -----");
var image:UIImage!;
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
image = pickedImage;
}
else {
image = info[UIImagePickerControllerOriginalImage] as! UIImage;
}
self.imageView.image = image;
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("----- imagePickerControllerDidCancel -----");
dismiss(animated: true, completion: nil)
}
}
I see the print of the action button but I never see the following one :
print("----- didFinishPickingMediaWithInfo -----");
I already have done imagePicker like this in the past so I don't understand why it doesn't work.
Can someone help me please?

The type of info is changed to [String : Any] in Swift 3 instead of [String : AnyObject] also you have not added _ as first parameter label, so change your method like this.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("----- imagePickerControllerDidCancel -----");
}

Related

Image not showing up in ImageView after using Image Picker

I am trying to write a simple app that will update the ImageView with a photo from my photos library. I can open the photos library and select a photo, but after I do that the default image in the ImageViewer does not show up. Any idea why?
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBOutlet weak var photoView: UIImageView!
#IBAction func testGesture(_ sender: UITapGestureRecognizer) {
let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
photoView.image = selectedImage
dismiss(animated: true, completion: nil)
}
}
You're not using the UIImagePickerControllerDelegate's didFinishPickingMediaWithInfo method. Remove the private and modify the didFinishPickingMediaWithInfo method to the UIImagePickerControllerDelegate method syntax and you're good to go.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
photoView.image = selectedImage
print(selectedImage)
dismiss(animated: true, completion: nil)
}

How do you display an image in a UIImageView that was selected using UIImagePickerController?

I'm very new to Xcode and Swift, and I was trying to display an image in a UIImageView that was selected using UIImagePickerController. I linked the UIImageView using an #IBOutlet and I put some if statements at the bottom to allow for editing of the selected picture, but I got stuck when an error popped up in my code. I'm pretty sure that the problem has something to do with how I am referencing the UIImageView, but I don't know how to do it in a different way. I just got this account to ask this question, so forgive me for the way I made this post.
Here is the code:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func openPhotosButton(_ sender: UIButton) {
showImagePickerController()
}
#IBOutlet weak var characterView: UIImageView!
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func showImagePickerController() {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
imagePickerController.sourceType = .photoLibrary
present(imagePickerController, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as UIImage {
characterView.image = editedImage
}
else if let originalImage = info[UIImagePickerController.InfoKey.originalImage] as UIImage {
characterView.image = originalImage
}
dismiss(animated: true)
}
}
Picture from Xcode:
change your method to this one
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
characterView.image = editedImage
}
else if let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
characterView.image = originalImage
}
dismiss(animated: true)
}

imagePickerController - didFinishPickingMediaWithInfo does not get called after picking media

converted app from swift 3 to swift 4.2.
my app had a upload your profile image feature that is not working anymore and I am trying to figure out why. For now What I see is that
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo
didFinishPickingMediaWithInfo Is not being called after media was chosen
Here is my views full code:
import UIKit
class CameraMenuViewController: BaseViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var UserID:Int = 0
#IBOutlet weak var myImageView: UIImageView!
var callback : ((UIImage) -> ())?
#IBOutlet weak var btn_end: UIButton!
#IBOutlet weak var from_camera: UIBarButtonItem!
#IBOutlet weak var from_gallery: UIBarButtonItem!
#IBAction func btn_end_pressed(_ sender: UIButton) {
//
//self.openViewControllerBasedOnIdentifier("Home")
//let data = UIImagePNGRepresentation(myImageView) as NSData?
let image = myImageView.image!.pngData() as NSData?
//if let data = UIImagePNGRepresentation(myImageView) {
print("callback data")
let userDetails:Dictionary = (UserDefaults.standard.value(forKey: "myUserDetails") as? [String:Any])!
let UserID:Int = userDetails["UserID"] as! Int
print("UserID")
print(UserID)
print("is_selfie from callback")
//save profile image as NewUserID
UserDefaults.standard.set(image, forKey: String(UserID))
UserDefaults.standard.synchronize()
self.view.removeFromSuperview()
//}
}
#IBAction func btn_closer(_ sender: UIButton) {
//self.view.removeFromSuperview()
}
#IBAction func photofromLibrary(_ sender: UIBarButtonItem) {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
picker.modalPresentationStyle = .popover
present(picker, animated: true, completion: nil)
picker.popoverPresentationController?.barButtonItem = sender
}
#IBAction func shootPhoto(_ sender: UIBarButtonItem) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
print("photo shoot")
//UserDefaults.standard.set("selfie", forKey: "is_selfie")
UserDefaults.standard.set(true, forKey: "is_selfie")
UserDefaults.standard.synchronize()
DispatchQueue.main.async {
self.picker.allowsEditing = false
self.picker.sourceType = UIImagePickerController.SourceType.camera
self.picker.cameraCaptureMode = .photo
self.picker.modalPresentationStyle = .fullScreen
self.present(self.picker,animated: true,completion: nil)
}
} else {
noCamera()
}
}
let picker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
picker.delegate = self
DispatchQueue.global(qos: .userInitiated).async
{
self.present(self.picker, animated: true, completion: nil)
}
let language = UserDefaults.standard.object(forKey: "myLanguage") as! String
if(language=="arabic"){
//from_camera.setTitle("كاميرا",for: .normal)
//from_gallery.text.setTitle("الصور",for: .normal)
btn_end.setTitle("إنهاء",for: .normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Delegates
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
let chosenImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as! UIImage //2
myImageView.contentMode = .scaleAspectFit //3
myImageView.image = chosenImage //4
myImageView.layer.borderWidth = 1
myImageView.layer.masksToBounds = false
myImageView.layer.borderColor = UIColor.black.cgColor
myImageView.layer.cornerRadius = myImageView.frame.height/4
myImageView.clipsToBounds = true
callback?(chosenImage)
dismiss(animated:true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func noCamera(){
let alertVC = UIAlertController(
title: "No Camera",
message: "Sorry, this device has no camera",
preferredStyle: .alert)
let okAction = UIAlertAction(
title: "OK",
style:.default,
handler: nil)
alertVC.addAction(okAction)
present(
alertVC,
animated: true,
completion: nil)
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
Please help me understand why didFinishPickingMediaWithInfo isn't getting called anymore
It appears as though the function declaration changed between Swift 3 and 4.2. This mustn't have been updated for you by the Swift Migrator Tool. One trick I do when this happens, to check what the correct function declaration is, is to use multiline comment syntax to comment out your current function (didFinishPickingMediaWithInfo in your case). Then you can start typing the function out again, and use Xcode autocomplete to ensure you have it correct. You can then copy the contents of the function you commented out to this new and correct function declaration.
Or - you could just look it up the documentation! According to the documentation on imagePickerController, the function should be declared as:
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
If you replace your function declaration with the above, it should get called again.
As Craig said you need to change delegate function declaration and also afterwards you need to update the following:
let chosenImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
These two changes combined should solve your issue.
i think the name off the function is update
this is my code in My app And work greate
extension FCViewController: UIImagePickerControllerDelegate
{
internal func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
{
if let photo = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}
// Any Code Here ...

How do I use the updated UIImagePickerControllerDelegate iOS 12 API?

How do I use the updated UIImagePickerControllerDelegate API since it changed to [UIIMagePickerController.InfoKey : Any]? This part has been updated. I also searched here and I could not find an answer.
import UIKit
class adicionarNovoItemVc: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var textFieldNome: UITextField!
let imagePicker = UIImagePickerController()
#IBOutlet weak var namePreview: UILabel!
#IBOutlet weak var imagePreview: UIImageView!
let picker = UIImagePickerController()
#IBAction func botaoAdcFoto(_ sender: UIButton) {
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
???
}
}
Update:
After updating the didFinishPickingMediaWithInfo delegate to :
private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[.originalImage] as! UIImage? {
self.imagePreview.image = image
self.picker.dismiss(animated: true, completion: nil)
}
}
I now get:
Cannot downcast from 'Slice>' to a more optional type 'UIImage?'
It's not really much different. In iOS 12, lots of the old constants names have been refactored.
Instead of the old key UIImagePickerControllerOriginalImage you now use UIImagePickerController.InfoKey.originalImage:
Something like:
let image = info[UIImagePickerControllerOriginalImage]
now becomes:
let image = info[.originalImage]
See the related documentation for UIImagePickerController.InfoKey.
Update:
You made several mistakes in your attempted didFinishPickingMediaWithInfo. You need:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
self.imagePreview.image = image
}
self.picker.dismiss(animated: true, completion: nil)
}
You need to set the mediaTypes of the picker using the availableMediaTypes class func of UIImagePickerController and retrieve the actual image from the info parameter.
#IBAction func botaoAdcFoto(_ sender: UIButton) {
picker.allowsEditing = true
picker.delegate = self
picker.sourceType = .photoLibrary
if let mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary) {
picker.mediaTypes = mediaTypes
}
present(picker, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as! UIImage? {
self. imagePreview.setImage(image, for: .normal)
self.picker.dismiss(animated: true, completion: nil)
}
}

Three images using image picker

I am building an app that allows user to add three pictures to threeUIImageViews
I added three buttons, for instance, when a user clicks on button one he should be able to add an image toUIImageView 1
but the image did not come to theUIImageView and I did not find any solution
sample of code:
#IBAction func imageOneBtn(sender: AnyObject) {
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
picker.delegate = self
picker.allowsEditing = false
self.presentViewController(picker, animated: true, completion: nil)
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
imageViewOne.image = selectedImage
imageViewOne.contentMode = UIViewContentMode.ScaleAspectFit
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
Thank you in advance
The code seems to be correct.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
Try removing the exclamation mark (!).
Try using imageViewOne.contentMode = .ScaleAspectFit
Also try using var instead of let selectedImage
In general Try this code
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var selectedImage = info[UIImagePickerControllerOriginalImage] as UIImage
imageViewOne.contentMode = .ScaleAspectFit
imageViewOne.image = selectedImage
dismissViewControllerAnimated(true, completion: nil)
}
I have solved my problem, and this is the answer for anyone who may want to use it
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var oneImg: UIImageView!
#IBOutlet weak var twoImg: UIImageView!
#IBOutlet weak var threeImg: UIImageView!
var num=0;
func config() {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
imagePickerController.sourceType = .PhotoLibrary
presentViewController(imagePickerController, animated: true, completion: nil)
}
#IBAction func oneBtn(sender: AnyObject) {
num = 1
config()
}
#IBAction func twoBtn(sender: AnyObject) {
num = 2
config()
}
#IBAction func threeBtn(sender: AnyObject) {
num = 3
config()
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage;
if num == 1 { // switch can be used here
oneImg.image = selectedImage;
} else if (num == 2) {
twoImg.image = selectedImage
} else if (num == 3) {
threeImg.image = selectedImage
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
}

Resources