CHutch
CHutch

Reputation: 1

Two actions from one button in Swift

I am trying to activate an iOS Notification Center timer and simultaneously send a user to a web URL (in actuality a survey). I can't figure out how to get the two actions from a single button. Here is the code I have that currently uses two separate buttons:

@IBAction func timer(_ sender: Any)
{
    let content = UNMutableNotificationContent()
    content.title = "Reminder"
    content.subtitle = "Click This Notice"
    content.body = "Please Repeat Daily"
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: true)
    let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

@IBAction func survey(_ sender: Any) {
    if let url = NSURL(string: "https://yahoo.com"){ UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)}
}

Any help is much appreciated as I am a less than basic programmer.

Upvotes: 0

Views: 3261

Answers (2)

ctrl freak
ctrl freak

Reputation: 12395

This is what your button target may look like:

button.addTarget(self, action: #selector(timer(_:)), for: .touchUpInside)

Just call the second method from inside the first method:

@objc func timer(_ sender: Any) {
    print("timer")
    survey(sender)
}
@objc func survey(_ sender: Any) {
    print("survey")
}

Just pass the button as the argument for the second method's parameter.

Upvotes: 0

Martin Muldoon
Martin Muldoon

Reputation: 3436

From the Storyboard you can simply cntrl drag from your button to your View Controller. Select action and name action1.. or whatever.

Do this a second time for action2

Implement your two actions and you are done. When you click the button, both actions will be called.

Upvotes: 1

Related Questions