iOS10以上 Swift5.0 推送通知

我們之前發(fā)過關(guān)于推送的文章iOS 推送通知及通知擴(kuò)展,其中介紹了推送相關(guān)流程及代碼實(shí)現(xiàn),不過使用OC實(shí)現(xiàn)的,現(xiàn)在我們就來介紹一下在iOS10.0以上系統(tǒng)中,用Swift處理遠(yuǎn)程推送通知的相關(guān)流程及實(shí)現(xiàn)。

1. 遠(yuǎn)程推送的流程

蘋果官方提供的遠(yuǎn)程推送通知的傳遞示意圖如下:

遠(yuǎn)程推送通知的傳遞過程

各關(guān)鍵組件之間的交互細(xì)節(jié):

各關(guān)鍵組件之間的交互細(xì)節(jié)

不論實(shí)現(xiàn)的語言是OC該是Swift,遠(yuǎn)程推送流程都是一樣的,只是根據(jù)iOS版本的不同,注冊推送的方法、收到推送是的回調(diào)方法會(huì)有不同。

2. 實(shí)現(xiàn)遠(yuǎn)程推送功能的準(zhǔn)備工作

  • 在開發(fā)者賬號中,創(chuàng)建AppID,并為AppID開通推送權(quán)限;
  • 生成并下載安裝推送證書、描述文件;
  • APP端的工程設(shè)置界面,capabilities頁面下,將“Push Notifications”設(shè)置為ON。

3. 不同iOS版本間推送通知的區(qū)別

  • aps串的格式變化
// iOS10.0 之前: 
{"aps":{"alert":{"body": "This is a message"},"sound":"default","badge":1}}
//iOS 10 基礎(chǔ)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
}
  • 獲取推送設(shè)置
    iOS10.0 之前是不能獲取推送設(shè)置的,iOS 10 還可以實(shí)時(shí)獲取用戶當(dāng)前的推送的設(shè)置信息:
@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 }
}

//獲取設(shè)置
UNUserNotificationCenter.current().getNotificationSettings {
    settings in 
    print(settings.authorizationStatus) // .authorized | .denied | .notDetermined
    print(settings.badgeSetting) // .enabled | .disabled | .notSupported
}

2 UserNotifications

iOS10.0 及之后iOS加入了UserNotifications框架,Swift中的這個(gè)框架包括了以下庫:

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. 需要實(shí)現(xiàn)的代碼

  • 注冊遠(yuǎn)程推送
    要先導(dǎo)入U(xiǎn)serNotifications頭文件,注冊邏輯如下:
// 在AppDelegate的didFinishLaunchingWithOptions方法中注冊遠(yuǎn)程推送通知
// - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(nullable NSDictionary *)launchOptions NS_AVAILABLE_IOS(3_0);

// 注冊遠(yuǎn)程推送通知
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){
                    // 申請用戶權(quán)限被拒
                } else if (setting.authorizationStatus == .authorized){
                    // 用戶已授權(quán)(再次獲取dt)
                    DispatchQueue.main.async {
                        application.registerForRemoteNotifications()
                    }
                } else {
                    // 未知錯(cuò)誤
                }
            }
        }
    }
  • 處理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: "")
 // 上報(bào)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;

寫好代碼并設(shè)置好證書后,可以使用測試工具Pusher和真機(jī)測試一下...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容