SwiftyJD SwiftyJD - 3 months ago 7x
Swift Question

How to send a push notification after a button is tapped?

I currently have an iOS App that is already set up to receive push notifications. What I'm trying to do is, after a user presses the 'Join' button, I want to send them a "Welcome" push notification. Any clue on how to do this?


It's pretty easy.


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: nil))
    return true

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    print("Local notification received (tapped, or while app in foreground): \(notification)")

Then in your action:

@IBAction func welcomeMe(sender: AnyObject) {
    let notification = UILocalNotification()
    notification.alertBody = "Welcome to the app!" // text that will be displayed in the notification

    notification.fireDate = NSDate(timeIntervalSinceNow: 2)
    notification.soundName = UILocalNotificationDefaultSoundName

    notification.userInfo = ["title": "Title", "UUID": "12345"]         

Now if the app is in the background, you see an Push notification. If it's in the foreground then your didReceiveLocalNotification fires instead. Tapping on the notification launches your app to the foreground and fires didReceiveLocalNotification also.