引入庫
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("顯示內(nèi)容:\(result) error:\(String(describing: error))")
if(result){
if !(error != nil){
print("注冊成功了场躯!")
application.registerForRemoteNotifications()
}
} else{
print("用戶不允許推送")
}
}
} else if (setting.authorizationStatus == .denied){
//用戶已經(jīng)拒絕推送通知
//-- 彈出頁面提示用戶去顯示
}else if (setting.authorizationStatus == .authorized){
//已注冊 已授權(quán) --注冊同志獲取 token
self.registerForRemoteNotifications()
}else{
}
}
}
}
// 注冊通知牲芋,獲取deviceToken
func registerForRemoteNotifications() {
// 請求授權(quán)時異步進行的闸餐,這里需要在主線程進行通知的注冊
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
成功與失敗的回調(diào)
// 成功的回調(diào)
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) {
}
//失敗的回調(diào)
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
//TODO: 注冊失敗后的結(jié)果, 可以在這里記錄失敗結(jié)果, 以后再伺機彈框給用戶打開通知
}
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) {
}
}
簡單明了復制即可
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者