Swift iOS 13,使用移动网络时未获得 APNS 设备令牌 (4g/3g)

Anj*_*der 5 apple-push-notifications devicetoken ios swift

我试图获得 APNS 推送令牌。

func configPushNotifications(_ application: UIApplication) {
    application.registerForRemoteNotifications()
}
Run Code Online (Sandbox Code Playgroud)

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

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) 
Run Code Online (Sandbox Code Playgroud)

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

Mau*_*iya 3

请验证代码,如下所示

首先导入本地通知

import UserNotifications
Run Code Online (Sandbox Code Playgroud)

然后创建一个方法

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()
}
Run Code Online (Sandbox Code Playgroud)

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

self.settingPushNotification()
Run Code Online (Sandbox Code Playgroud)

您需要添加委托方法

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)")
}
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

  • “UserNotifications”请求已按原样完成。正如我所说,旧版 iOS 版本通常可以正常工作。仅当我连接到移动互联网 (4g/3g) 时,才会在更新的 **iOS 13.1.2 和 13.1.3** 中出现问题。如果我没有在“签名和功能”中添加远程通知,那么旧版 iOS 也不应该正常工作。 (2认同)