import UIKit import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//注册通知权限
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
//如果用户允许了通知权限,就注册推送通知服务
UIApplication.shared.registerForRemoteNotifications()
}
else {
print("用户拒绝了通知权限")
}
}
UNUserNotificationCenter.current().delegate = self
return true
}
//注册推送通知服务成功后,APNS 会调用此方法
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.reduce("", { $0 + String(format: "%02X", $1) })
print("设备注册成功,Device Token:\(tokenString)")
}
//注册推送通知服务失败后,APNS 会调用此方法
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("设备注册失败,Error:\(error.localizedDescription)")
}
//处理通知
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print("didReceive response:\(userInfo)")
completionHandler()
}
//处理在前台收到的通知
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
print("willPresent notification:\(userInfo)")
completionHandler([.alert, .sound, .badge])
}
}