WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

day 53 - Saving to the iOS photo library - how to pass data to selector?

Forums > 100 Days of Swift

Hi there, I do not understand how data are passed to a func with parameters when it is used as selector sign.

Example: if I'd like to add an argument "okMessage: String" to be printed on saving then adding at the very end of the func something like "print(okMessage)" (no matter usage, just for sake of understanding), then pass "hello, all done here" , how could pass that string?

the code from the lesson

  @IBAction func save(_ sender: Any) {
        guard let image = imageView.image else { return }
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingError:contentIinfo:)), nil)
    }
@objc func image(_ image: UIImage, didFinishSavingError error: Error?, contentIinfo: UnsafeRawPointer) {

        if let error = error {
            let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
            present(ac, animated: true, completion: nil)
        } else {
            let ac = UIAlertController(title: "Saved!r", message: "modified image saved", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
            present(ac, animated: true, completion: nil)
        }

    }

   

You don't. When you create a selector, you are passing in a signature of a function. If that function doesn't include a parameter for an extra String, you can't pass in an extra String. Most of the time, your selector will be called by the system and it expects the functions it calls to have particular signatures.

If you want your didFinishSavingError function to have extra info, you will need to do something else, like set a property in your class that you can read from within the function.

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.