UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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)
        }

    }

2      

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.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.