我們之前發(fā)過關于推送的文章iOS 推送通知及通知擴展蔚出,其中介紹了推送相關流程及代碼實現(xiàn)命浴,不過使用OC實現(xiàn)的沸版,現(xiàn)在我們就來介紹一下在iOS10.0以上系統(tǒng)中卓起,用Swift處理遠程推送通知的相關流程及實現(xiàn)。
1. 遠程推送的流程
蘋果官方提供的遠程推送通知的傳遞示意圖如下:
各關鍵組件之間的交互細節(jié):
不論實現(xiàn)的語言是OC該是Swift盾饮,遠程推送流程都是一樣的采桃,只是根據(jù)iOS版本的不同,注冊推送的方法丘损、收到推送是的回調方法會有不同普办。
2. 實現(xiàn)遠程推送功能的準備工作
- 在開發(fā)者賬號中,創(chuàng)建AppID徘钥,并為AppID開通推送權限衔蹲;
- 生成并下載安裝推送證書、描述文件吏饿;
- APP端的工程設置界面踪危,capabilities頁面下,將“Push Notifications”設置為ON猪落。
3. 不同iOS版本間推送通知的區(qū)別
- aps串的格式變化
// iOS10.0 之前:
{"aps":{"alert":{"body": "This is a message"},"sound":"default","badge":1}}
//iOS 10 基礎Payload:
{"aps":{"alert":{"title":"I am title","subtitle":"I am subtitle","body":"I am body"},"sound":"default","badge":1}}
- 注冊通知
iOS10.0 之前
//iOS8以下
[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
//iOS8 - iOS10
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge categories:nil]];
iOS10.0 及以后
// OC
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions options = UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert;
[center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) {
}
// Swift
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]{ granted, error in
}
- 獲取推送設置
iOS10.0 之前是不能獲取推送設置的贞远,iOS 10 還可以實時獲取用戶當前的推送的設置信息:
@available(iOS 10.0, *)
open class UNNotificationSettings : NSObject, NSCopying, NSSecureCoding {
open var authorizationStatus: UNAuthorizationStatus { get }
open var soundSetting: UNNotificationSetting { get }
open var badgeSetting: UNNotificationSetting { get }
open var alertSetting: UNNotificationSetting { get }
open var notificationCenterSetting: UNNotificationSetting { get }
open var lockScreenSetting: UNNotificationSetting { get }
open var carPlaySetting: UNNotificationSetting { get }
open var alertStyle: UNAlertStyle { get }
}
//獲取設置
UNUserNotificationCenter.current().getNotificationSettings {
settings in
print(settings.authorizationStatus) // .authorized | .denied | .notDetermined
print(settings.badgeSetting) // .enabled | .disabled | .notSupported
}
2 UserNotifications
iOS10.0 及之后iOS加入了UserNotifications框架,Swift中的這個框架包括了以下庫:
import UserNotifications.NSString_UserNotifications
import UserNotifications.UNError
import UserNotifications.UNNotification
import UserNotifications.UNNotificationAction
import UserNotifications.UNNotificationAttachment
import UserNotifications.UNNotificationCategory
import UserNotifications.UNNotificationContent
import UserNotifications.UNNotificationRequest
import UserNotifications.UNNotificationResponse
import UserNotifications.UNNotificationServiceExtension
import UserNotifications.UNNotificationSettings
import UserNotifications.UNNotificationSound
import UserNotifications.UNNotificationTrigger
import UserNotifications.UNUserNotificationCenter
3. 需要實現(xiàn)的代碼
- 注冊遠程推送
要先導入UserNotifications頭文件笨忌,注冊邏輯如下:
// 在AppDelegate的didFinishLaunchingWithOptions方法中注冊遠程推送通知
// - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions NS_AVAILABLE_IOS(3_0);
// 注冊遠程推送通知
func registerNotifications(_ application: UIApplication) {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.getNotificationSettings { (setting) in
if setting.authorizationStatus == .notDetermined {
center.requestAuthorization(options: [.badge,.sound,.alert]) { (result, error) in
if(result){
if !(error != nil){
// 注冊成功
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
} else{
//用戶不允許推送
}
}
} else if (setting.authorizationStatus == .denied){
// 申請用戶權限被拒
} else if (setting.authorizationStatus == .authorized){
// 用戶已授權(再次獲取dt)
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
} else {
// 未知錯誤
}
}
}
}
- 處理deviceToken:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let dtDataStr = NSData.init(data: deviceToken)
let dtStr = dtDataStr.description.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "").replacingOccurrences(of: " ", with: "")
// 上報deviceToken
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// 彈窗提示
}
- 處理接收到的推送信息:
// UNUserNotificationCenterDelegate
// The method will be called on the delegate only if the application is in the foreground.
// If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented.
// The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list.
// This decision should be based on whether the information in the notification is otherwise visible to the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __OSX_AVAILABLE(10.14);
// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction.
// The delegate must be set before the application returns from application:didFinishLaunchingWithOptions:.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __OSX_AVAILABLE(10.14) __TVOS_PROHIBITED;
// The method will be called on the delegate when the application is launched in response to the user's request to view in-app notification settings.
// Add UNAuthorizationOptionProvidesAppNotificationSettings as an option in requestAuthorizationWithOptions:completionHandler: to add a button to inline notification settings view and the notification settings view in Settings.
// The notification will be nil when opened from Settings.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(nullable UNNotification *)notification __IOS_AVAILABLE(12.0) __OSX_AVAILABLE(10.14) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
寫好代碼并設置好證書后蓝仲,可以使用測試工具Pusher和真機測試一下...