[图片上传失败...(image-89a956-1563784038464)]
参照 pro648的 UserNotifications框架详解
https://github.com/pro648/BasicDemos-iOS/tree/master/UserNotifications
1.申请通知权限和通知方式
1.请求可以收取通知
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound, .carPlay]) { (granted, error) in
guard granted else { return }
// Register for push notification.
UIApplication.shared.registerForRemoteNotifications()
}
2.获取到Token,将token保存到自己的服务器。然后服务器可以使用次token,推送消息到手机
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Receive device token
let token = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}.joined()
// Forward token to server.
// Enable remote notification features.
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Fail to register for remote notifications. error:\(error)")
// Disable remote notification features.
}
2.管理通知,使用UNUserNotificationCenterDelegate
1.包含两个主要方法,程序在后台时,收到通知后,用户点击通知会调用
// Use this method to process the user's response to a notification.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
print("Default Action")
} else if (response.actionIdentifier == UNNotificationDismissActionIdentifier){
print("Dismiss action")
}else if (response.notification.request.content.categoryIdentifier == "calendarCategory") {
handleCalendarCategory(response: response)
}
UIApplication.shared.applicationIconBadgeNumber = 0
completionHandler()
}
private func handleCalendarCategory(response: UNNotificationResponse) {
if response.actionIdentifier == "markAsCompleted" {
} else if response.actionIdentifier == "remindMeIn1Minute" {
// 1 Minute
let newDate = Date(timeInterval: 60, since: Date())
scheduleNotification(at: newDate)
} else if response.actionIdentifier == "remindMeIn1Minute" {
// 5 Minutes
let newDate = Date(timeInterval: 60*5, since: Date())
scheduleNotification(at: newDate)
}
}
2.前台收到通知时,如果不进行相关处理,用户看不到通知。可以通过下面方法显示通知
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping(UNNotificationPresentationOptions) -> Void) { let identifier = notification.request.identifier
let options: UNNotificationPresentationOptions
if identifier == "calendar" {
options = []
} else {
options = [.alert, .sound]
}
completionHandler(options)
}