推送
为什么用推送?
1.实时更新消息(无论app处于什么状态,推送通知都能到设备上,如果有必要,你的app会被启动)
2.foreground not required
3.power efficient
4.与客户互动的友好方式
推送类型\区别 | 定义 |
提醒通知 | 1.允许你传递可见提醒 2.你得app可以用自定义的方式与之交互 3.visible alert 4.display new information 5.can be interactive 6.foreground or background 7.customizable |
后台通知 | 允许app不在前台时,接收允许以便使内容保持最新。 |
5.推送通知步骤
1)注册远程通知
这将设备远程注册为苹果推送通知系统(APNs), 并返回设备令牌给设备,该令牌用于标示此设备为通知的对象。
var entity: UNAuthorizationOptions
if #available(iOS 12.0, *) {
entity = [.sound,.badge,.alert,.providesAppNotificationSettings]
} else {
entity = [.sound,.badge,.alert]
}
//授权
UNUserNotificationCenter.current().requestAuthorization(options: entity) { (isSuccess, error) in
if isSuccess {
print("requestAuthorization success")
}else {
print("requestAuthorization error : \(String(describing: error))")
}
}
// 注册远程通知
UIApplication.shared.registerForRemoteNotifications()
2)声明UNUserNotificationCenterDelegate代理对象(一般为AppDelegate)
UNUserNotificationCenter.current().delegate = self
- 一旦调用UIApplication.shared.registerForRemoteNotifications() 方法,会调用app的两种方法的其中一个,如果token注册失败,则调用failtoXXX方法,并输出为什么会失败,如果成功,则需要将令牌转发给后台服务器,这样就可以将通知推送到设备上。
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { /// Required - 注册 DeviceToken,将token转发给后台推送服务器 [LJAliYunPushManager.share registerDeviceTokenWith:deviceToken]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { //Optional NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error); }
- 将令牌作为数据对象传送给app上,为了能将其发送给服务器,需要将它转换为字符串。
/// 注册 DeviceToken @objc func registerDeviceToken(with deviceToken: Data) { //1.将数据分离到齐组件中,再将这些组件转换为十六进制字 let tokenComponents = deviceToken.map { (data) -> String in String(format: "%02.2hhx", data) } //2.将它们重新连接到一个字符串中 let deviceTokenString = tokenComponents.joined() //3.将该字符串追加到URLQuery,以制作出完成合格的端点, let queryItems = [URLQueryItem(name: "deviceToken", value: deviceTokenString)] var urlComps = URLComponents(string: "www.example.com/register")! guard let url = urlComps.url else { return } //4.然后执行URLSession let task = URLSession.shared.dataTask(with: url) { (data, response, error) in //handle data } task.resume() }
2.
3)接收通知,实现UNUserNotificationCenterDelegate方法