iOS10以上 Swift5.0 推送通知

我们之前发过关于推送的文章iOS 推送通知及通知扩展,其中介绍了推送相关流程及代码实现,不过使用OC实现的,现在我们就来介绍一下在iOS10.0以上系统中,用Swift处理远程推送通知的相关流程及实现。

1. 远程推送的流程

苹果官方提供的远程推送通知的传递示意图如下:

远程推送通知的传递过程

各关键组件之间的交互细节:

各关键组件之间的交互细节

不论实现的语言是OC该是Swift,远程推送流程都是一样的,只是根据iOS版本的不同,注册推送的方法、收到推送是的回调方法会有不同。

2. 实现远程推送功能的准备工作

  • 在开发者账号中,创建AppID,并为AppID开通推送权限;
  • 生成并下载安装推送证书、描述文件;
  • APP端的工程设置界面,capabilities页面下,将“Push Notifications”设置为ON。

3. 不同iOS版本间推送通知的区别

  • 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. 需要实现的代码

  • 注册远程推送
    要先导入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和真机测试一下...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,444评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,421评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,036评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,363评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,460评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,502评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,511评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,280评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,736评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,014评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,190评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,848评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,531评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,159评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,411评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,067评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,078评论 2 352

推荐阅读更多精彩内容