swift4.2 打印devicetoken

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        
        if #available(iOS 10, *){
            iOS8Later()
            return true
        }
        
        if #available(iOS 8, *){
            iOS10Later()
            return true
        }
        early()

        return true
    }
    
    
    ///请求完成后会调用把获取的deviceToken返回给我们
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        testStringToData()
        
        //deviceToken = 32 bytes
        print("deviceToken = \(deviceToken)")
        
        //FIXME:打印推送64位token
        print(deviceToken.map { String(format: "%02.2hhx", arguments: [$0]) }.joined() , "推送 deviceToken" )
    }
    

    func testStringToData(){
        let testStr = "莎莎哈"
        let testData = testStr.data(using: String.Encoding.utf8)
        let newTestStr = String(data: testData ?? Data(), encoding: String.Encoding.utf8)
        print("======", testStr, testData,  newTestStr)
    }

    
}

extension AppDelegate{
    
    func early(){
        let type = UIRemoteNotificationType.alert.rawValue | UIRemoteNotificationType.badge.rawValue | UIRemoteNotificationType.sound.rawValue
        UIApplication.shared.registerForRemoteNotifications(matching: UIRemoteNotificationType(rawValue: type))
    }
    
    func iOS8Later(){
        let type = UIUserNotificationType.badge.rawValue | UIUserNotificationType.alert.rawValue | UIUserNotificationType.sound.rawValue
        //请求授权
        let set = UIUserNotificationSettings(types: UIUserNotificationType(rawValue: type), categories: nil)
        
        UIApplication.shared.registerUserNotificationSettings(set)
        
        //需要通过设备UUID 和APP bundle ID 发送请求,获取deviceToken
        UIApplication.shared.registerForRemoteNotifications()
    }
    
    func iOS10Later(){
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: UNAuthorizationOptions.alert) { (isSucceseed: Bool, error:Error?) in
                
                if isSucceseed == true{
                    print( "成功")
                }else{
                    print( "失败")
                    print("error = \(error)")
                }
            }
            UIApplication.shared.registerForRemoteNotifications()
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate{
    
}

  

Swift3.1的DeviceToken打印的是32Bytes
https://www.jianshu.com/p/fed585eef7c1

猜你喜欢

转载自www.cnblogs.com/qingzZ/p/10304720.html