【问题标题】:IOS Swift Pushkit: didUpdatePushCredentials not calledIOS Swift Pushkit:没有调用 didUpdatePushCredentials
【发布时间】:2016-08-27 16:01:46
【问题描述】:

我正在尝试使用 Twilio Client iOS SDK 开发 VoIP 应用程序。我的应用程序不在后台时收到来电。对于后台模式,我尝试按照 Apple 的建议使用 PushKit Framework。但是我的应用程序没有注册PushKit。方法didUpdatePushCredentials 没有被调用。

这是我的应用委托和设置:

import UIKit
import PushKit;

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var voipRegistry: PKPushRegistry!;

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.


        if  UIApplication.instancesRespondToSelector(#selector(UIApplication.registerUserNotificationSettings(_:))) {
            application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil))
        }

        let preferences = NSUserDefaults.standardUserDefaults()
        let usrIdKey = "usrId"
        let tokenKey = "token"
        if preferences.objectForKey(usrIdKey) == nil  || preferences.objectForKey(tokenKey) == nil{
            //  Doesn't exist
        } else {

            self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
            var nav1 = UINavigationController()
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let viewControllerObj = storyboard.instantiateViewControllerWithIdentifier("NumberScreenViewController") as? NumberScreenViewController
            nav1.viewControllers = [viewControllerObj!]
            self.window!.rootViewController = nav1
            self.window?.makeKeyAndVisible()
        }

        phone.login{
            device in
        }

        var state:String
        switch application.applicationState {
        case .Active:
            state = "Active"
        case .Background:
            state = "Background"
        case .Inactive:
            state = "Active"
        }

        NSLog("App launched with state \(state)")

        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state informationO to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        //output to see when we terminate the app
        NSLog("app terminated")
    }

    func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
         NSLog("Registering for VOIP notifications.")
        //register for voip notifications
        voipRegistry = PKPushRegistry(queue: dispatch_get_main_queue())
        voipRegistry.desiredPushTypes = Set([PKPushTypeVoIP])
        voipRegistry.delegate = self;
    }


    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification)
    {
        if ( application.applicationState == UIApplicationState.Active)
        {
            print("Active")
            // App is foreground and notification is recieved,
            // Show a alert.
        }
        else if( application.applicationState == UIApplicationState.Background)
        {
            print("Background")
            // App is in background and notification is received,
            // You can fetch required data here don't do anything with UI.
            self.redirectToPage(notification.userInfo)
        }
        else if( application.applicationState == UIApplicationState.Inactive)
        {
            print("Inactive")
            // App came in foreground by used clicking on notification,
            // Use userinfo for redirecting to specific view controller.
            self.redirectToPage(notification.userInfo)
        }
    }

    func redirectToPage(userInfo:[NSObject : AnyObject]!)
    {
        var viewControllerToBrRedirectedTo:DialScreenViewController  = DialScreenViewController(nibName: "DialScreenViewController", bundle: nil)
        if userInfo != nil
        {
            if let pageType = userInfo["TYPE"]
            {
                if pageType as! String == "Page1"
                {
//                    viewControllerToBrRedirectedTo = UIViewController() // creater specific view controller
                }
            }
        }

            if self.window != nil && self.window?.rootViewController != nil
            {
                let rootVC = self.window?.rootViewController!
                if rootVC is UINavigationController
                {
                    (rootVC as! UINavigationController).pushViewController(viewControllerToBrRedirectedTo, animated: true)
                }
                else
                {
                    rootVC?.presentViewController(viewControllerToBrRedirectedTo, animated: true, completion: { () -> Void in

                    })
                }
            }
    }
}

extension AppDelegate: PKPushRegistryDelegate {

    func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) {

        //print out the VoIP token. We will use this to test the nofications.
        NSLog("voip token: \(credentials.token)")
    }

    func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) {
        let payloadDict = payload.dictionaryPayload["aps"] as? Dictionary<String, String>
        let message = payloadDict?["alert"]

        //present a local notifcation to visually see when we are recieving a VoIP Notification
        if UIApplication.sharedApplication().applicationState == UIApplicationState.Background {

            let localNotification = UILocalNotification();
            localNotification.alertBody = message
            localNotification.applicationIconBadgeNumber = 1;
            localNotification.soundName = UILocalNotificationDefaultSoundName;

            UIApplication.sharedApplication().presentLocalNotificationNow(localNotification);
        }

        else {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                let alert = UIAlertView(title: "VoIP Notification", message: message, delegate: nil, cancelButtonTitle: "Ok");
                alert.show()
            })
        }

        NSLog("incoming voip notfication: \(payload.dictionaryPayload)")
    }

    func pushRegistry(registry: PKPushRegistry!, didInvalidatePushTokenForType type: String!) {

        NSLog("token invalidated")
    }
}

【问题讨论】:

    标签: ios swift twilio voip pushkit


    【解决方案1】:

    我也有同样的问题。不过重启手机后就恢复了。

    【讨论】:

      【解决方案2】:

      通过https://www.raywenderlich.com/123862/push-notifications-tutorial

      Download

      import UIKit
      import PushKit
      
      
      class AppDelegate: UIResponder, UIApplicationDelegate,PKPushRegistryDelegate{
      
      
      
      func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
      
      
          let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
          application.registerForRemoteNotificationTypes(types)
      
          self. PushKitRegistration()
      
          return true
      }
      
      
      
      //MARK: - PushKitRegistration
      
      func PushKitRegistration()
      {
      
          let mainQueue = dispatch_get_main_queue()
          // Create a push registry object
          if #available(iOS 8.0, *) {
      
              let voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue)
      
              // Set the registry's delegate to self
      
              voipRegistry.delegate = self
      
              // Set the push type to VoIP
      
              voipRegistry.desiredPushTypes = [PKPushTypeVoIP]
      
          } else {
              // Fallback on earlier versions
          }
      
      
      }
      
      
      @available(iOS 8.0, *)
      func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) {
          // Register VoIP push token (a property of PKPushCredentials) with server
      
          let hexString : String = UnsafeBufferPointer<UInt8>(start: UnsafePointer(credentials.token.bytes),
              count: credentials.token.length).map { String(format: "%02x", $0) }.joinWithSeparator("")
      
          print(hexString)
      
      
      }
      
      
      @available(iOS 8.0, *)
      func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) {
          // Process the received push
      
      
      }
      
      }
      

      Life cycle of app - when app is in terminated and push kit payload comes

      【讨论】:

      • 请不要发帖identical answers。在这种情况下,最好将问题标记为重复。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      相关资源
      最近更新 更多