-1

I have an alert in my iOS app, with two buttons on the alert. I'd like to call a function I have, called searchTheWeb() when the user selects that option:

alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil))
alert.addAction(UIAlertAction(title: "Search The Web!", style: UIAlertActionStyle.default, handler: nil))

func searchTheWeb(){
    let word =  self.userInfo.text! + self.faceResults.text!  + self.labelResults.text!
    if let encoded = word.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed), let url = URL(string: "https://www.google.com/#q=\(encoded)") {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url)
        }
    }
}

So in that addAction with the title Search The Web! How can I call that function?

Eoghan Casey
  • 190
  • 3
  • 17
  • That's what the `handler` parameter is for – vadian Apr 05 '18 at 16:46
  • @vadian I thought that myself so made a call to the function in the handle, but that just didn't work. Check out AdamPro's answer below, that works! – Eoghan Casey Apr 05 '18 at 16:49
  • It's worth it to read the [documentation](https://developer.apple.com/documentation/uikit/uialertaction/1620097-init) – vadian Apr 05 '18 at 16:53

2 Answers2

1

You just need to change how you declare your searchTheWeb action to the following:

let search = UIAlertAction(title: "Search The Web!", style: .default) { [weak self] _ in
    self?.searchTheWeb()
}
alert.addAction(search)
AdamPro13
  • 7,232
  • 2
  • 30
  • 28
1

Using alert handler

 alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil))

let search = UIAlertAction(title: "Search The Web!", style: UIAlertActionStyle.default, handler: { (action) -> Void in
    self.searchTheWeb()
})
alert.addAction(search)

func searchTheWeb(){
    let word =  self.userInfo.text! + self.faceResults.text!  + self.labelResults.text!
    if let encoded = word.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed), let url = URL(string: "https://www.google.com/#q=\(encoded)") {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url)
        }
    }
}
GIJOW
  • 2,307
  • 1
  • 17
  • 37