Swift iOS 13, Not getting APNS Device token while using Mobile Network (4g/3g)

Viewed 5196

I was trying to get APNS push token.

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

But I didn't received any Token from AppDelegate if I am using My Phone Sim Internet (4g/3g).

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

But if i use Wifi, it's working fine. I checked iOS 13.1.2 and 13.1.3. Both have the same problem. But lower versions like iOS 12 or 11 working fine. Is it apple bug? or I have to request token with different config for Mobile network?

1 Answers

Please verify code as looks like this

first import local notification

import UserNotifications

then create a method

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

you can call this method either in appdelegate or in viewcontroller this way.

self.settingPushNotification()

you need to add delegate methods

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

Make sure you added push notification in signing and capabilities.

enter image description here

This way you can get APNS Device token.

Related