Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent picking the same photo twice in UIImagePickerController

How do i prevent users from picking the same image twice in UIImagePickerContoroller to avoid duplication?

I tried doing it with the URLReference but its not working so I'm guessing its not the way.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    if let url = info[UIImagePickerControllerReferenceURL] as? NSURL{
        if photosURL.contains(url){
             Utilities.showMessage(message: "photo Uploaded already", sender: self, title: ErrorTitle.FRIENDS, onDismissAction: nil)
        } else {
            if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
                photos.append(pickedImage)
            }
        }
    }
    dismiss(animated: true, completion: nil)
}

thanks,

like image 403
Assaf Yehudai Avatar asked May 24 '17 09:05

Assaf Yehudai


2 Answers

You should also consider doing the picker.dismiss first and do the other logic with the image afterward. That way, you can prevent the user from tapping an image multiple times and invoking the delegate function several times.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    guard !picker.isBeingDismissed else {
        return
    }
    picker.dismiss(animated: true) {
        if let pickedImage = (info[UIImagePickerController.InfoKey(rawValue: UIImagePickerController.InfoKey.originalImage.rawValue)] as? UIImage) {
            // do stuff with the picked image
            print("Uesr picked an image \(pickedImage)")
        }
    }
}
like image 129
Yuchen Avatar answered Nov 17 '22 07:11

Yuchen


swift 4

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)

    if let capturedImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage {
        // do stuff
    }

    picker.delegate = nil
    picker.dismiss(animated: true, completion: nil)
}
like image 40
Roberto LL Avatar answered Nov 17 '22 06:11

Roberto LL