iOS10以上 Swift5.0 推送通知

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

1. 遠程推送的流程

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

遠程推送通知的傳遞過程

各關鍵組件之間的交互細節(jié):

各關鍵組件之間的交互細節(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和真機測試一下...

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市官疲,隨后出現(xiàn)的幾起案子袱结,更是在濱河造成了極大的恐慌,老刑警劉巖途凫,帶你破解...
    沈念sama閱讀 216,997評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件垢夹,死亡現(xiàn)場離奇詭異,居然都是意外死亡维费,警方通過查閱死者的電腦和手機果元,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來犀盟,“玉大人而晒,你說我怎么就攤上這事≡某耄” “怎么了倡怎?”我有些...
    開封第一講書人閱讀 163,359評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我监署,道長颤专,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,309評論 1 292
  • 正文 為了忘掉前任钠乏,我火速辦了婚禮血公,結果婚禮上,老公的妹妹穿的比我還像新娘缓熟。我一直安慰自己,他們只是感情好摔笤,可當我...
    茶點故事閱讀 67,346評論 6 390
  • 文/花漫 我一把揭開白布够滑。 她就那樣靜靜地躺著,像睡著了一般吕世。 火紅的嫁衣襯著肌膚如雪彰触。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,258評論 1 300
  • 那天命辖,我揣著相機與錄音况毅,去河邊找鬼。 笑死尔艇,一個胖子當著我的面吹牛尔许,可吹牛的內容都是我干的。 我是一名探鬼主播终娃,決...
    沈念sama閱讀 40,122評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼味廊,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了棠耕?” 一聲冷哼從身側響起余佛,我...
    開封第一講書人閱讀 38,970評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎窍荧,沒想到半個月后辉巡,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 45,403評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡蕊退,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,596評論 3 334
  • 正文 我和宋清朗相戀三年郊楣,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片咕痛。...
    茶點故事閱讀 39,769評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡痢甘,死狀恐怖,靈堂內的尸體忽然破棺而出茉贡,到底是詐尸還是另有隱情塞栅,我是刑警寧澤,帶...
    沈念sama閱讀 35,464評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站放椰,受9級特大地震影響作烟,放射性物質發(fā)生泄漏。R本人自食惡果不足惜砾医,卻給世界環(huán)境...
    茶點故事閱讀 41,075評論 3 327
  • 文/蒙蒙 一拿撩、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧如蚜,春花似錦压恒、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,705評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽牍陌。三九已至,卻和暖如春伦吠,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背魂拦。 一陣腳步聲響...
    開封第一講書人閱讀 32,848評論 1 269
  • 我被黑心中介騙來泰國打工毛仪, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人芯勘。 一個月前我還...
    沈念sama閱讀 47,831評論 2 370
  • 正文 我出身青樓箱靴,卻偏偏與公主長得像,于是被迫代替她去往敵國和親荷愕。 傳聞我的和親對象是個殘疾皇子刨晴,可洞房花燭夜當晚...
    茶點故事閱讀 44,678評論 2 354

推薦閱讀更多精彩內容