How to handle push notification in swift?
Asked Answered
C

3

7

I have an ios app where i send push using apns. I need to handle push message and if it is correct show the message. How can i realize it in swift? This is my code:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions:
    [NSObject: AnyObject]?) -> Bool {
    registerForPushNotifications(application)
    return true
}

func registerForPushNotifications(application: UIApplication) {
    let notificationSettings = UIUserNotificationSettings(
        forTypes: [.Badge, .Sound, .Alert], categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    print("Device Token:", tokenString)
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    print("Failed to register:", error)
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {



}

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {

}

func applicationDidBecomeActive(application: UIApplication) {
    UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}

In what function i can handle push notification there?

Cognizant answered 8/7, 2016 at 11:23 Comment(5)
You can handle the notification in didReceiveRemoteNotification method. What problem are you facing?Errol
i send with push userid and i need to check user id,if it is correct userid i need to show push,if it is not i dont show pushCognizant
You can handle the push in the above-mentioned method and check for the parameters received in the dictionary.Errol
ok i check for the parameters, after how i can show or not show push?Cognizant
https://mcmap.net/q/328781/-how-to-set-up-push-notifications-in-swiftDoughnut
R
21

To handle push notifications when arrived in your iOS application is tricky part in order to take their full advantage.

When push notification arrives, your application can be in

Closed state – App is killed, Running state – App is in Foreground, Suspended state – App is in Background,

Handle push notification when arrived

Lets discuses one by one how to handle them in each state

Closed state:

When Application is closed (some other app is running or phone is locked), push notification arrived and you tapped on it to open the app. Control will be given to appDelegate’s method i.e. didFinishLaunchingWithOptions: Please note that when you normally launch the app by taping its icon from your phone. didFinishLaunchingWithOptions: called first with its launchOptions==nil. In case you launch the app by clicking received push notifications didFinishLaunchingWithOptions: called with its launchOptions!=nil. Here comes the point If you want to do something special when your application is launched upon clicking push notification you need to add code in your didFinishLaunchingWithOptions:

like this

if (launchOptions != nil)
{
   //do some thing special e.g. display particular ViewController or Set some notification badge value.
}

Running state

If your application is running (in foreground) and push notification received, nothing related to that notification will be displayed on screen – no alert, no message, no sound. Instead following method of appDelegate will be called

   func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}

You can implement this method according to your need that how you want to respond to the notification.

Suspended state

If your application is in background (phone is locked or some other app is running) and push notification recieved, notification will be displayed with sound and on clicking that notification app will be launched with following method of appDelegate is called

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}

Its the same that is called when notification received in Running state. Please note that you can always find if your app is awakened from background state in this method by using UIApplication’s applicationState property. In this case you can do something special when application is opened from background via push notification.

Ritz answered 8/7, 2016 at 11:24 Comment(6)
May you explain in detail,please?Cognizant
i have one more question?Cognizant
how can i realize this one: if user authorize i show push if is not i dont showCognizant
You should only register for push notification only after the user logs in.Errol
@Cognizant That you can manage it from backend when you send push notification to particular device token.Ritz
@Cognizant see the Rajan's commentRitz
E
1

As per your problem,

You cannot toggle the visibility of the notification once it has been received on the device.

This kind of feature/functionality is only possible on Android. As on receiving the notification, Android devs can decide whether to render the view or not.

So try to control it from the server side.

Errol answered 8/7, 2016 at 11:35 Comment(0)
D
1

I would like to give an example about handling remote push notifications.
All will be in AppDelegate.swift file;

First of all get your token after registration from this function to can send Remote Push Notifications (RPM) from your servers or provider:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    
    // Send device token that accepted to retrieve remote notifications to server
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    NSLog("APNs registration success, device token: \(token)")
}

Check remote notification info is exist in launch options inside didFinishLaunchWithOptions method to know did app launched by tapping notification alert like this:

// Check if there any user info about remote notifications in 'launchOptions'
        /// Get user your data from userInfo dictionary if you need
    if let userInfo = launchOptions?[.remoteNotification] as? [String: AnyObject],
          let exmplValue = userInfo["yourValue"] as? String {
        NSLog("[AppDelegate] - Info: App launched by tapping notification alert. We have new value: \(exmplValue)")
       /// Here you can change rootVC or storing some values to process it in your mainVC etc.
    }

Then implement didReceiveRemoteNotification function like in below to handle push notifications in both state active and inactive:

/// This function made for handling push notifications when app running (both states active or inactive)
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    
    /// Hide badge number if it exist
    application.applicationIconBadgeNumber = 0
    
    /// Get user your data from userInfo dictionary if you need
    guard let aps = userInfo["aps"] as? [String: Any],
          let alert = aps["alert"] as? [String: Any],
          let title = alert["title"] as? String,
          let body = alert["body"] as? String,
          let exampleValue = userInfo["example"] as? String else {
        NSLog("[AppDelegate] - Warning: user info missing aps or other data.")
        return
    }
    
   /// Check current application state
   if UIApplication.shared.applicationState == .active {
      // Your app in foreground, you can ask user to want to take action about what you want to do.
   } else {
      // Your app in background at most in inactive mode, user when taps on notification alert app will become active so you can do whatever you want directly
   }
}

Bonus:
Implement UNUserNotificationCenterDelegate in your AppDelegate.swift file then inside didFinishLaunchWithOptions confirm to delegate of notification center like this: UNUserNotificationCenter.current().delegate = self Finally override this function to adjusting badge, sound, alert of notification that will present.

    // Assign delegate to show LPN or RPN badge, alert, sound
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    /// I would like to notify user by sound only when app is active
    /// otherwise show notification (alert, badge, sound)
    if UIApplication.shared.applicationState == .active {
        completionHandler(.sound)
    } else {
        completionHandler([.alert, .badge, .sound])
    }
    
}

Please remember in these examples i don't implemented silent (background) notifications because of when i activate silent notifications my app handling all type of notifications inside below function and i cannot understand my app launched by tapping RPM or something else, briefly am not familiar with this case so if you need it you must add background modes capability and check Remote Notifications in your Targets -> Your App -> Signing& Capabilities, then implement this function to handle RPM:

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    <#code#>
}

Happy coding

Democratic answered 1/2, 2023 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.