On the surface I thought that this had to be a delegate issue, but after asking for the delegate the right one was returned.
I created an ImagePicker class to handle all the UIImagePickerController stuff. Every thing works until the delegate methods need to be called. After I pick a photo, the imagePicker dismisses, but the didFinishPickingMediaWithInfo method never gets called. Please help! Thanks :)
func selectPhoto() {
imagePicker.delegate = self //Delegate gets set here
let photoAsk = UIAlertController.init( //Ask user if they want to take picture or choose one
title: "Edit Profile Picture",
message: nil,
preferredStyle: .alert)
let cameraAction = UIAlertAction.init(
title: "Take Photo",
style: .default) { (UIAlertAction) in
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
self.imagePicker.sourceType = .camera
UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
} else {
print("Cannot access camera in simulator.")
return
}
}
let photoLibraryAction = UIAlertAction.init(
title: "Photo Library",
style: .default) { (UIAlertAction) in
self.imagePicker.sourceType = .photoLibrary
UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
print("UIImagePickerDelegate: \(self.imagePicker.delegate.debugDescription)") // <--THIS PRINTS OUT "AppName.ImagePicker: 0x145d7bdf0>", and the class name is ImagePicker
}
let cancelAction = UIAlertAction.init(
title: "Cancel",
style: .cancel) { (UIAlertAction) in return }
photoAsk.addAction(cameraAction)
photoAsk.addAction(photoLibraryAction)
photoAsk.addAction(cancelAction)
imagePicker.mediaTypes = [kUTTypeImage as String]
UIApplication.topViewController()?.present(photoAsk, animated: true, completion: nil)
}
}
This never gets called:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("Image picked.") //NEVER PRINTS
}
I had to copy the method names straight from the delegate. For some reason the auto-complete has the method headers wrong.
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
//save image
//display image
}
self.dismiss(animated: true, completion: nil)
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
UPDATE SWIFT 5:
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
//save image
//display image
}
self.dismiss(animated: true, completion: nil)
}
Details
Xcode 9.2, Swift 4
Xcode 10.2.1 (10E1001), Swift 5
Solution
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("\(info)")
if let image = info[.originalImage] as? UIImage {
imageView?.image = image
dismiss(animated: true, completion: nil)
}
}
}
Usage
let imagePickerController = UIImagePickerController()
imagePickerController.allowsEditing = false
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
Full sample
Do not forget to add the solution code here (look above)
import UIKit
class ViewController: UIViewController {
private weak var imageView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
let stackView = UIStackView(frame: .zero)
stackView.axis = .vertical
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(imageView)
imageView.widthAnchor.constraint(equalToConstant: 200).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 200).isActive = true
self.imageView = imageView
let button = UIButton(frame: .zero)
button.setTitle("Button", for: .normal)
button.setTitleColor(.blue, for: .normal)
button.addTarget(self, action: #selector(showImages), for: .touchUpInside)
stackView.addArrangedSubview(button)
}
#IBAction func showImages(_ sender: AnyObject) {
let imagePickerController = UIImagePickerController()
imagePickerController.allowsEditing = false
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
}
I found that the delegate code had to be within an active UIViewController.
I originally tried to have my code in a separate file, as as NSObject with the correct delegate protocols declared, like this:
class PhotoPicker: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
But that never called the delegate methods.
Taking the exact same code and placing it within the UIViewController I was calling it from made it work.
It looks like the best solution is to create a pop-up type view, and have its ViewController keep the code.
Yo have to make sure that UIImagePickerController was not released before delegate called.
I created an ImagePicker class to handle all the
UIImagePickerController stuff.
I created similar class, but
func onButtonDidTap(sender: UIButton) {
.....
let picker = VLImagePickerController()
picker.show(fromSender: sender, handler: { (image: UIImage?) -> (Void) in
if (image != nil) {
self.setImage(image!)
}
})
....
}
did not work for me.
'picker' was released before 'handler' could be called.
I created permanent reference, and it worked:
let picker = VLImagePickerController()
func onButtonDidTap(sender: UIButton) {
.....
//let picker = VLImagePickerController()
picker.show(fromSender: sender, handler: { (image: UIImage?) -> (Void) in
if (image != nil) {
self.setImage(image!)
}
})
....
}
I also faced this issue and solved it by using below solution. Set picker's delegate after present completion.
controller.present(picker, animated: true, completion: {
self.picker.delegate = self
})
Hope this will work for you!!
As per my experience, it is an issue of ARC.
If we define instance as locally then ARC will remove its reference
automatically once methods scope end. If you define globally then it
is kept in memory until the view controller is not deinitialized.
Short Answer:
Define UIImagePickerController instance globally.
Long Answer:
I have created once the common class of NSObject and delegates method of UIImagePickerController is not called.
After 5 hours of brainstorming, Finally, get the solution. It seems like an issue related to memory deallocation during the captured image from the camera.
public typealias CameraBlock = (UIImage?, Bool) -> Void
class HSCameraSingleton: NSObject {
var pickerController = UIImagePickerController()
private var completionBlock: CameraBlock!
var presentationController: UIViewController?
public init(presentationController: UIViewController) {
super.init()
self.presentationController = presentationController
}
public func present(completionBlock: #escaping CameraBlock) {
guard UIImagePickerController.isSourceTypeAvailable(.camera) else {
return
}
self.pickerController = UIImagePickerController()
self.pickerController.delegate = self
self.pickerController.allowsEditing = true
self.pickerController.sourceType = .camera
self.completionBlock = completionBlock
self.presentationController?.present(self.pickerController, animated: true, completion: nil)
}
}
extension HSCameraSingleton: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.completionBlock?(nil,false)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.originalImage] as? UIImage else {
self.completionBlock?(nil,false)
return
}
self.completionBlock?(image,true)
pickerController.dismiss(animated:true, completion: nil)
}
}
class AuthViewController: UIViewController{
lazy var overlay = HSCameraSingleton(presentationController:self)
#IBAction func actionLoginTap(_ sender: UIControl) {
overlay.present { (image, status) in
print(image,status)
}
}
}
swift 4.2
Add Delegate method according ViewController
UIImagePickerControllerDelegate,UINavigationControllerDelegate
//IBOutlet
#IBOutlet weak var ImagePhoto: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
//Button Action Take Photo
#IBAction func btnPhotoTap(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary // Or .camera as you require
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
//MARK:-imagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image1 = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
self.ImagePhoto.image = image1
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("Cancel")
self.dismiss(animated: true, completion: nil)
}
This code works, (although, it redisplays over and over because it displays the picker in viewWillAppear, this is just to keep code small). I would look at what is different from this. It could have to do with your top view controller? Why not just display the picker from a view controller rather than go to application's top view controller? Also, once you get the delegate callback, you need to dismiss the view controller.
import UIKit
import MobileCoreServices
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.delegate = self
}
override func viewDidAppear(_ animated: Bool) { // keeps reopening, do not this in your code.
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imagePicker.dismiss(animated: true, completion: nil)
}
}
I voted this one up because I was missing the UINavgationControllerDelegate declaration and this comment helped.
imagePickerController wasn't being called.
Something I found that helped me was making sure the delegate was set as public rather than private.
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
Related
I am having an issue while displaying camera captured image in an image view where delegates are set and being called "didFinishPickingMediaWithInfo".
I have two buttons for the user interaction (camera picture & from gallery), once I take picture from camera and then select any other image from gallery; the camera picture taken earlier is shown for a second. I tried searching a lot but no luck so far.
Can anyone please advise what am I missing. Following is the code for reference.
#IBAction func cameraButtonPressed(_ sender: UIButton) {
self.openCamera()
}
#IBAction func galleryButtonPressed(_ sender: UIButton) {
self.openGallary()
}
override func viewDidLoad() {
super.viewDidLoad()
initialLayout()
}
override func viewWillAppear(_ animated: Bool) {
self.lblPreview.isHidden = true
self.imageTake.isHidden = true
self.uploadButtonOutlet.isHidden = true
}
//
//MARK: - Internal Methods
func initialLayout() {
self.cameraButtonOutlet.layer.cornerRadius = 20
self.galleryButtonOutlet.layer.cornerRadius = 20
self.uploadButtonOutlet.layer.cornerRadius = 20
}
//MARK: - Open the camera
func openCamera(){
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera)){
imagePicker.sourceType = UIImagePickerController.SourceType.camera
//If you dont want to edit the photo then you can set allowsEditing to false
imagePicker.allowsEditing = true
imagePicker.delegate = self
imagePicker.cameraCaptureMode = .photo
imagePicker.cameraDevice = .rear
self.present(imagePicker, animated: true, completion: nil)
}
else{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
//MARK: - Choose image from camera roll
func openGallary(){
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
imagePicker.allowsEditing = true
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: nil)
}
extension UploadTimesheetViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage{
self.lblPreview.isHidden = false
self.imageTake.isHidden = false
self.uploadButtonOutlet.isHidden = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
self.imageTake.image = editedImage
self.imageTake.setNeedsLayout()
})
// self.imageTake.image = editedImage
}
//Dismiss the UIImagePicker after selection
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.isNavigationBarHidden = false
self.dismiss(animated: true, completion: nil)
}
}
Update your delegate method like this,
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var finalImage:UIImage?
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
finalImage = image
}else {
finalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}
self.lblPreview.isHidden = false
self.imageTake.isHidden = false
self.uploadButtonOutlet.isHidden = false
self.imageTake.image = finalImage
//Dismiss the UIImagePicker after selection
picker.dismiss(animated: true, completion: nil)
}
Sorry for the delayed response. Just updating the answer so if anyone is having the same issue should know what was the actual problem.
Once picker is dismissed a viewwillappear will be called where I have hid the image view and hence the reason it was not displaying it for the first time.
If I remove the code from viewwillappear and add that properties code to viewedload then all works fine.
The issue was once the picker is dismissed , viewillapear was called and that was creating the issue.
This question already has an answer here:
Picking two different images in the same view controller using imagePickerController in Swift
(1 answer)
Closed 3 years ago.
I am coding swift in Xcode and trying to create an Edit User Profile ViewController that has two UIImageViews, one UIImageView is for the profile photo and the other if for the cover photo. I am having a hard time changing images for the cover photo. When I go in my simulator and click on the change cover photo button and choose an image it changes the profile photo. When I click on the change profile photo button and choose an image it also changes the profile image as well but this action is correct. Does anyone know how to help me to where I can change images for these controllers and not have them be the same image? This is my code below.
import UIKit
class profilephotoViewController: UIViewController {
#IBOutlet weak var profileImagePhoto: UIImageView!
#IBOutlet weak var profileImageTapped: UIButton!
var imagePicker:UIImagePickerController!
#IBOutlet weak var coverImagePhoto: UIImageView!
#IBOutlet weak var coverImageTapped: UIButton!
var secondImagePicker:UIImagePickerController!
override func viewDidLoad() {
super.viewDidLoad()
let imageTap = UITapGestureRecognizer(target: self, action: #selector(openImagePicker))
profileImagePhoto.isUserInteractionEnabled = true
profileImagePhoto.addGestureRecognizer(imageTap)
profileImagePhoto.layer.cornerRadius = profileImagePhoto.bounds.height / 2
profileImagePhoto.clipsToBounds = true
profileImageTapped.addTarget(self, action: #selector(openImagePicker), for: .touchUpInside)
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
let coverTap = UITapGestureRecognizer(target: self, action: #selector(openSecondImagePicker))
coverImagePhoto.isUserInteractionEnabled = true
coverImagePhoto.addGestureRecognizer(coverTap)
coverImagePhoto.clipsToBounds = true
coverImageTapped.addTarget(self, action: #selector(openSecondImagePicker), for: .touchUpInside)
secondImagePicker = UIImagePickerController()
secondImagePicker.allowsEditing = true
secondImagePicker.sourceType = .photoLibrary
secondImagePicker.delegate = self
// Do any additional setup after loading the view.
}
#objc func openImagePicker(_ sender:Any) {
//Open Image Picker
self.present(imagePicker, animated: true, completion: nil)
}
#objc func openSecondImagePicker(_ sender:Any) {
//Open Second Image Picker
self.present(secondImagePicker, animated: true, completion: nil)
}
}
extension profilephotoViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.profileImagePhoto.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
func secondImagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
internal func secondImagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let secondPickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.coverImagePhoto.image = secondPickedImage
}
picker.dismiss(animated: true, completion: nil)
}
}
You can try
internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let secondPickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
if let picker == imagePicker {
self.profileImagePhoto.image = secondPickedImage
}
else {
self.coverImagePhoto.image = secondPickedImage
}
}
picker.dismiss(animated: true, completion: nil)
}
Using the code below it opens the camera but fails to call the picker delegate method. I'm getting no error messages.
import Foundation
import UIKit
import MobileCoreServices
class RecVidController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
RecVidController.startRecord(delegate: self, sourceType: .camera)
}
static func startRecord(delegate: UIViewController & UINavigationControllerDelegate & UIImagePickerControllerDelegate, sourceType: UIImagePickerController.SourceType) {
guard UIImagePickerController.isSourceTypeAvailable(sourceType) else { return }
let mediaUI = UIImagePickerController()
mediaUI.sourceType = sourceType
mediaUI.mediaTypes = [kUTTypeMovie as String]
mediaUI.allowsEditing = true
mediaUI.delegate = delegate
delegate.present(mediaUI, animated: true, completion: nil)
}
#objc func video(_ videoPath: String, didFinishSavingWithError error: Error?, contextInfo info: AnyObject) {
let title = (error == nil) ? "Success" : "Error"
let message = (error == nil) ? "Video was saved" : "Video failed to save"
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
}
// MARK: - UIImagePickerControllerDelegate
extension RecVidController: UIImagePickerControllerDelegate {
private func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true, completion: nil)
guard let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String,
mediaType == (kUTTypeMovie as String),
let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL,
UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(url.path)
else { return }
// Handle a movie capture
UISaveVideoAtPathToSavedPhotosAlbum(url.path, self, #selector(video(_:didFinishSavingWithError:contextInfo:)), nil)
}
}
// MARK: - UINavigationControllerDelegate
extension RecVidController: UINavigationControllerDelegate {
}
The problem is this declaration:
private func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
You have declared this method private, so Objective-C has no way of knowing that it exists. Thus, it can't call into it.
Basically, Cocoa looks to see whether this method is implemented, discovers that it isn't (because you've hidden it), and gives up. There's no visible penalty, because this delegate method is optional, and when it is not implemented, Cocoa dismisses the picker for you when the user is finished with it.
So just delete private and you should be good to go. This exposes the delegate method to Objective-C, and so it will be called.
(You do not have to say #objc to expose it to Objective-C, as you would if this were your own function, because you've declared we adopt UIImagePickerControllerDelegate, which is an Objective-C protocol.)
I had a similar issue when delegate methods were not called by program.
The imagePicker.delegate = self should be NOT in viewDidLoad() method but in method which opens gallery. Like this:
func openGallery()
{
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
self.present(imagePicker, animated: true, completion: nil)
}
when I am trying to implement all the uiimagepickerview methods in my app, my view controller (after choosing an image) shows nothing on it? It should have my textfields however they all 'disppeared'
Here's my code
#IBAction func registerUserProfileImageSelectButton(_ sender: UIButton) {
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
registerUserProfileImage.contentMode = .scaleAspectFit
registerUserProfileImage.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
I suspect it may be something to do in my dismiss method, but I am not too certain
Thanks for your help in advance!
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
The problem is you are trying to dismiss the current view controller, not the image picker controller. Please use:
imagePicker.dismiss(animated: true, completion: nil)
That should work!
this works for me perfectly you can try this code :
import UIKit
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
#IBOutlet weak var imagePickerImg: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func imagePicker(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self // you need to set a delegate to your image picker here
//to get selected ( edited ) portion
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print(info)
// let img = info[UIImagePickerControllerOriginalImage] as! UIImage
// if you keep editing true
let img = info[UIImagePickerControllerEditedImage] as! UIImage
imagePickerImg.image = img
dismiss(animated: true, completion: nil)
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
print("Cancel Press")
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I have a profile picture which also acts as a button, when the person clicks the picture the image selector shows up and they can choose the picture they want to use as their profile picture, but the imagePickerController is not being called, and the Parse db image file is not being called. Why is this happening, how can I fix it?
class ProfileView: UIViewController, UIImagePickerControllerDelegate {
func userchange(sender: AnyObject){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){
// imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
let user = PFUser.currentUser()
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageData = UIImageJPEGRepresentation(image, 0.05)
let imageFile = PFFile(name:"image.jpg", data:imageData!)
user!["ProPic"] = imageFile;
imageFile.save()
//NOTHING IS BEING PRINTED
print("called")
user!.saveInBackgroundWithBlock(nil)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
}
in swift 2.0 and onwards if you using any delegates for example UIImagePickerControllerDelegate , you need to compulsory implement the delegate methods , else dont use or dont add in your viewcontroller, this is the concept , now follow this
some example
Step-1
add UIImagePickerControllerDelegate, UINavigationControllerDelegate in your view Controller
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet var imageView: UIImageView!
let imagePicker = UIImagePickerController()
Step-2
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self // Its Manotary
}
Step-3
// Present the Image picker controller
#IBAction func loadImageButtonTapped(sender: UIButton) {
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
Step-4
// call the delegate method for pick the image
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.contentMode = .ScaleAspectFit
imageView.image = pickedImage
}
dismissViewControllerAnimated(true, completion: nil)
}
Step-5
// finally dismiss the Imagepicker controller
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}