我试图在Xcode 9.2中实现Pushkit,但无法获取设备 token

class AppDelegate: UIResponder, UIApplicationDelegate,PKPushRegistryDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
        UIApplication.shared.registerForRemoteNotifications()

        NSLog("app launched with state \(application.applicationState)")
        voipRegistration()
        return true
    }

    func voipRegistration() {
        // Create a push registry object
        let voipRegistry: PKPushRegistry = PKPushRegistry(queue: DispatchQueue.main)
        // Set the registry's delegate to self
        voipRegistry.delegate = self
        // Set the push type to VoIP
        voipRegistry.desiredPushTypes = Set([PKPushType.voIP])
    }

    /*
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //register for voip notifications
        let voipRegistry = PKPushRegistry(queue: DispatchQueue.main)
        voipRegistry.desiredPushTypes = Set([PKPushType.voIP])
        voipRegistry.delegate = self;
    }
    */

    func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
        //print out the VoIP token. We will use this to test the notification.
        NSLog("voip token: \(pushCredentials.token)")
    }

最佳答案

确保将其从字节转换为字符串类型

func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {

    //print out the VoIP token.
    let token = pushCredentials.token.map { String(format: "%02.2hhx", $0) }.joined()
    print("voip token: \(token)")

}

10-05 18:05