Невозможно получить уведомление VoIP с помощью PushKit

Я следую этой статье и M Penades answer создание демо VoIP Notification. Я могу зарегистрировать уведомление, используя didRegisterUserNotificationSettings, и могу получить токен voip от didUpdatePushCredentials.

Но когда я использую Хьюстон, имитирующий отправку уведомления на мое устройство, я могу получить сообщение 1 push notification sent successfully с консоли, но никаких действий или журналов на стороне устройства. Кажется, что didReceiveIncomingPushWithPayload никогда не вызывался.

P.S. Я использую Xcode 7.3, iPhone 6 (iOS 9.3) и iPad Mini (iOS 9.3) для разработки. Распространяется Ad Hoc ipa для установки.

Коды размещены здесь.

import UIKit
import PushKit


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
let voipRegistry = PKPushRegistry(queue: dispatch_get_main_queue())


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    //Enable all notification type. VoIP Notifications don't present a UI but we will use this to show local nofications later
    let notificationSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound] , categories: nil)

    //register the notification settings
    application.registerUserNotificationSettings(notificationSettings)

    //output what state the app is in. This will be used to see when the app is started in the background
    NSLog("app launched with state \(application.applicationState.stringValue)")
    return true
}

    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")
}

}

extension AppDelegate {

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {

    //register for voip notifications
    NSLog("didRegisterUserNotificationSettings called")
    voipRegistry.desiredPushTypes = Set([PKPushTypeVoIP])
    voipRegistry.delegate = self;
}
}

extension AppDelegate: PKPushRegistryDelegate {


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

    //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!) {

    NSLog("didReceiveIncomingPushWithPayload called")


    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 {
        NSLog("incoming notificaiton from background")

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

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

    else {
        NSLog("incoming notificaiton from frontend")


        dispatch_async(dispatch_get_main_queue(), { () -> Void in


            let alertController = UIAlertController(title: "Title", message: "This is UIAlertController default", preferredStyle: UIAlertControllerStyle.Alert)
            let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)

            UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

        })
    }

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

func pushRegistry(registry: PKPushRegistry!, didInvalidatePushTokenForType type: String!) {
    NSLog("didInvalidatePushTokenForType called")
    NSLog("token invalidated")
}
} 

extension UIApplicationState {

//help to output a string instead of an enum number
var stringValue : String {
    get {
        switch(self) {
        case .Active:
            return "Active"
        case .Inactive:
            return "Inactive"
        case .Background:
            return "Background"
        }
    }
}
}

Любая идея о том, как получить такое уведомление?


person Shongsu    schedule 18.04.2016    source источник
comment
У меня была такая же проблема, и когда я попытался отправить уведомление с помощью node-apn, я получил сообщение об ошибке, похоже, инструмент houston console line не отображает ошибки в некоторых случаях. Также убедитесь, что вы используете правильный идентификатор и сертификаты.   -  person ujell    schedule 18.04.2016
comment
Вы наконец получили уведомление на своем устройстве? Нужны ли мне какие-либо изменения в собственном быстром коде, который я разместил выше? Спасибо.   -  person Shongsu    schedule 19.04.2016
comment
В моем случае я пытался отправить уведомление с неправильным файлом .pem, так что да, это было исправлено. Также обратите внимание, что токены устройств различаются для разработки и распространения, что также может быть проблемой в вашем случае. Код выглядит нормально, если я ничего не пропустил.   -  person ujell    schedule 19.04.2016
comment
Спасибо! Вы спасли мою жизнь. Я изменил адрес сервера с gateway.sandbox.push.apple.com (для разработки) на gateway.push.apple.com (для производства, я думаю, для VoIP Push, это единственный вариант). Наконец-то я получил push-уведомление.   -  person Shongsu    schedule 20.04.2016
comment
Проверьте это: stackoverflow.com/questions/48581495/   -  person Chandresh    schedule 07.04.2018


Ответы (1)


Наконец-то я исправил эту проблему. Для быстрого исходного кода все в порядке, проблема в том, что я неправильно отправил push-запрос на сервер разработки Apple gateway.sandbox.push.apple.com, на самом деле мы должны отправить запрос на производственный сервер Apple gateway.push.apple.com.

Если вы следуете процедуре M Penades, обратите внимание, что вам необходимо изменить Simplepush, просто замените ssl://gateway.sandbox.push.apple.com:2195 на ssl://gateway.push.apple.com:2195 в строке 20 и повторите попытку.

Надеюсь, это сработает для вас.

person Shongsu    schedule 20.04.2016