Get the push notification token - iOS 10, Swift 3

后端 未结 9 825
深忆病人
深忆病人 2020-12-25 14:07

How to get the device token from new xCode 8, Swift 3 in iOS 10?

Here is the code to register notification:

<
相关标签:
9条回答
  • 2020-12-25 14:59

    Working Code for getting push notification token - iOS 11 or greater, Swift 4

    Request user permission

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
        let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert,UIUserNotificationType.badge, UIUserNotificationType.sound]
        let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
    
        application.registerUserNotificationSettings(pushNotificationSettings)
        application.registerForRemoteNotifications()
    
        return true        
    }
    

    Getting device token

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print(token) 
    }
    

    In case of error

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    
        print("i am not available in simulator \(error)")
    }
    
    0 讨论(0)
  • 2020-12-25 15:02
    var pushToken = String(format: "%@", deviceToken as CVarArg)
    pushToken = pushToken.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
    pushToken = pushToken.replacingOccurrences(of: " ", with: "")
    
    0 讨论(0)
  • 2020-12-25 15:04

    Swift 3 example taken from raywenderlich.com.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }  
        let token = tokenParts.joined()
        print(token)
    }
    
    0 讨论(0)
提交回复
热议问题