iOS 10推送通知 - willPresentNotification和didReceiveNotificationResponse如何工作?

时间:2016-09-26 19:44:13

标签: ios swift push-notification apple-push-notifications ios10

目前我已将我的应用程序设置为在ios 9中接收推送通知,其中它完美运行但是在iOS 10中我没有收到它们。我查看了stackoverflow上的各种响应,并发现了这个:

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

似乎适用于海报。我不完全确定我应该在willPresentNotification和didReceiveNotificationResponse部分添加什么代码。如果有人有任何关于这些部分如何工作的例子,将不胜感激。这是我到目前为止处理推送通知的相关代码:

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)

            }
          }
        }
      }
    }
  }



}

1 个答案:

答案 0 :(得分:23)

对于iOS 10中的远程和本地通知,我们有UserNotifications.framework。要处理通知,UserNotifications.framework中有两种 UNUserNotificationCenterDelegate 的委托方法。您需要执行与 didReceiveRemoteNotification 方法相同的代码来获取userInfo。

这两种方法可用于根据您的应用程序要求处理userInfo。

class Led { 
  public:
    void snowled()
    {
      LinuxGPIO gpio23(23);
      gpio23.SetDirection(true);
      bool on = true;
      for (;;)
      {
          printf("Switching %s the LED...\n", on ? "on" : "off");
          gpio23.SetValue(on);
          on = !on;
          sleep(1);
      }
    }
};



extern "C" {
    Led* Led_new(){ return new Led(); }
    void Led_snowled(Led* led){ led->snowled(); }
}