Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 10 push notifications - how does willPresentNotification and didReceiveNotificationResponse work?

Currently I have my app set up to receive push notifications in ios 9 where it works perfectly but with iOS 10 I'm not receiving them. I've looked over various responses on stackoverflow and came across this:

Push Notifications not being received on iOS 10, but working on iOS 9 and before

which appears to work for the poster. I'm not entirely sure what code I'm supposed to add under the willPresentNotification and didReceiveNotificationResponse sections. If anyone has any examples of how these sections work it will be appreciated. This is my relevant code for handling push notifications so far:

import UserNotifications
import Whisper

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

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

  registerForPushNotifications(application)
}

 //MARK: Push Notification Settings
  func registerForPushNotifications(application: UIApplication) {

    //check to see if phone is updated to iOS 10
    if #available(iOS 10.0, *){
      UNUserNotificationCenter.currentNotificationCenter().delegate = self
      UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: {(granted, error) in
        if (granted)
        {
          UIApplication.sharedApplication().registerForRemoteNotifications()
        }
        else{
          print("registering for push notifications unsuccessful")
        }
      })
    }

    else{ //If user is not on iOS 10 use the old methods we've been using
      let notificationSettings = UIUserNotificationSettings(
        forTypes: [.Badge, .Sound, .Alert], categories: nil)
      application.registerUserNotificationSettings(notificationSettings)

    }

  }

  //Notification handling for iOS 10
  @available(iOS 10.0, *)
  func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
    //Handle the notification - NOT SURE WHAT GOES HERE

  }

  @available(iOS 10.0, *)
  func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
    //Handle the notification -NOT SURE WHAT GOES HERE
  }


  //This is called if user selects to receive push notifications
  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]])
    }

    //save device token to keychain
    self.deviceToken = tokenString
    userInfo.sharedInstance.savePushNotDeviceToken(tokenString)
    NSUserDefaultsManager.sharedManager.pushNotifications = true

    //register device token to api
    registerPushNotificationDevice(tokenString)

    print("Device Token:", tokenString)
  }


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

    //save push notifications state
    NSUserDefaultsManager.sharedManager.pushNotifications = false

  }


  //In- App push notifications
  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    if application.applicationState == .Active {

      let navigationController = self.window!.rootViewController as! UINavigationController

      let alert = [String: String]()
      let title = ""
      let body = ""

      // Default printout of userInfo
      print("All of userInfo:\n\( userInfo)\n")

      if let aps = userInfo["aps"] as? NSDictionary {
        if let alert = aps["alert"] as? NSDictionary {
          if let title = alert["title"] as? NSString {
            if let body = alert["body"] as? NSString {

              let announcement = Announcement(title: title as String, subtitle: body as String, image: UIImage(named: "Image"))
                show(shout: announcement, to: navigationController)

            }
          }
        }
      }
    }
  }



}
like image 625
SwiftyJD Avatar asked Sep 26 '16 19:09

SwiftyJD


People also ask

How do iPhone push notifications work?

An iOS push notification is a message that pops up on an Apple device such as an iPhone. Before receiving push notifications from an app, iOS device users must explicitly give permission. Once a user opts-in, mobile app publishers can send push notifications to the users' mobile devices.

How does a push Notifcation work?

A push notification is a message that pops up on a mobile device, such as a sports score, an invitation to a flash sale or a coupon for downloading. App publishers can send them at any time, since users don't have to be in the app or using their devices to receive them.

What is the difference between push notifications and notifications?

The main difference between push notification and notification is that the latter are created internally from an application on the device that wants to show user some information, a reminder, some news or updates, and so on.

Will iOS awake my app when I receive silent push notification?

Silent remote notifications can wake your app from a “Suspended” or “Not Running” state to update content or run certain tasks without notifying your users.


1 Answers

For remote and local notification in iOS 10 we have UserNotifications.framework. To handle notification there are two delegate methods of UNUserNotificationCenterDelegate available in UserNotifications.framework. You need to do the same code you are doing in didReceiveRemoteNotification method to get userInfo.

This two methods are available to handle userInfo according to your app requirements.

//UNUserNotificationCenterDelegate delegate methods to get userInfo

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {

        //Called when a notification is delivered to a foreground app.

        let userInfo = notification.request.content.userInfo as? NSDictionary
        print("\(userInfo)")

     }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        // Called to let your app know which action was selected by the user for a given notification.
        let userInfo = response.notification.request.content.userInfo as? NSDictionary
        print("\(userInfo)")
    }
like image 76
Ashish Shah Avatar answered Sep 21 '22 00:09

Ashish Shah