引入库
import UserNotifications
首先注册 注册方法 放置到这里
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {}
注册方法
//MARK: 注册推送
func registerNotifications(_ application: UIApplication) {
//-- 注册推送
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self as UNUserNotificationCenterDelegate
center.getNotificationSettings { (setting) in
if setting.authorizationStatus == .notDetermined{
// 未注册
center.requestAuthorization(options: [.badge,.sound,.alert]) { (result, error) in
print("显示内容:\(result) error:\(String(describing: error))")
if(result){
if !(error != nil){
print("注册成功了!")
application.registerForRemoteNotifications()
}
} else{
print("用户不允许推送")
}
}
} else if (setting.authorizationStatus == .denied){
//用户已经拒绝推送通知
//-- 弹出页面提示用户去显示
}else if (setting.authorizationStatus == .authorized){
//已注册 已授权 --注册同志获取 token
self.registerForRemoteNotifications()
}else{
}
}
}
}
// 注册通知,获取deviceToken
func registerForRemoteNotifications() {
// 请求授权时异步进行的,这里需要在主线程进行通知的注册
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
成功与失败的回调
// 成功的回调
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
//TODO: 注册远程通知, 将deviceToken传递过去
let deviceStr = deviceToken.map { String(format: "%02hhx", $0) }.joined()
print(deviceStr)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
}
//失败的回调
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
//TODO: 注册失败后的结果, 可以在这里记录失败结果, 以后再伺机弹框给用户打开通知
}
delegate
extension AppDelegate:UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
}
}
简单明了复制即可
网友评论