import UIKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let notificationHandler = NotificationHandler() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //请求通知权限 UNUserNotificationCenter.current() .requestAuthorization(options: [.alert, .sound, .badge]) { (accepted, error) in if !accepted { print("用户不允许消息通知。") } } //向APNs请求token UIApplication.shared.registerForRemoteNotifications() return true } //token请求回调 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { //打印出获取到的token字符串 print("Get Push token: \(deviceToken.hexString)") } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } } //对Data类型进行扩展 extension Data { //将Data转换为String var hexString: String { return withUnsafeBytes {(bytes: UnsafePointer<UInt8>) -> String in let buffer = UnsafeBufferPointer(start: bytes, count: count) return buffer.map {String(format: "%02hhx", $0)}.reduce("", { $0 + $1 }) } } }
{ "aps":{ "alert":{ "title":"hangge.com", "subtitle":"航歌", "body":"做最好的开发者知识平台" }, "sound":"default", "badge":1 } }