首页 > 解决方案 > Swift iOS 13,使用移动网络时未获取 APNS 设备令牌(4g/3g)

问题描述

我试图获取 APNS 推送令牌。

func configPushNotifications(_ application: UIApplication) {
    application.registerForRemoteNotifications()
}

但是如果我使用的是 My Phone Sim Internet (4g/3g),我没有从 AppDelegate 收到任何令牌。

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) 

但如果我使用 Wifi,它工作正常。我检查了iOS 13.1.213.1.3。两者都有同样的问题。但较低的版本喜欢iOS 12 or 11工作正常。是苹果虫吗?或者我必须为移动网络请求具有不同配置的令牌?

标签: iosswiftapple-push-notificationsdevicetoken

解决方案


请验证代码,如下所示

首先导入本地通知

import UserNotifications

然后创建一个方法

func settingPushNotification() {
    
    let app = UIApplication.shared
    
    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        app.registerUserNotificationSettings(settings)
    }
    
    app.registerForRemoteNotifications()
}

您可以以这种方式appdelegate或以viewcontroller这种方式调用此方法。

self.settingPushNotification()

您需要添加委托方法

func application(
    _ application: UIApplication,
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
    ) {
    let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
    let token = tokenParts.joined()
    
    if !token.isEmpty {
        
        let userDefaults = UserDefaults.standard
        userDefaults.set(token, forKey: Strings.DeviceToken.rawValue)

    }
    

    print("Device Token: \(token)")
}

func application(
    _ application: UIApplication,
    didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)")
}

确保您在签名和功能中添加了推送通知。

在此处输入图像描述

这样您就可以获得 APNS 设备令牌。


推荐阅读