Painted painted levels: fostered fostered fostered
Tags: “iOS” “Swift” “Push” author: Dac_1033 Review: QiShare team
We previously sent an article about push iOS push notification and notification extension, which introduced push related process and code implementation, but using OC to achieve, now we will introduce in iOS10.0 above the system, with Swift to deal with remote push notification related process and implementation.
1. Remote push process
The official apple remote push notification delivery diagram is as follows:
Interaction details between key components:
Whether the language is OC or Swift, the remote push process is the same, but according to the different iOS version, the method of registering push and the callback method of receiving push will be different.
2. Make preparations for the remote push function
- In the developer account, create AppID and grant push permission to AppID;
- Generate, download and install push certificate and description file;
- ON the Capabilities screen, set “Push Notifications” to ON.
3. Differences between push notifications in different iOS versions
- Aps string format changes
// before iOS10.0 :{" aps":{"alert":{"body": "This is a message"},"sound":"default","badge":1}} {"aps":{"alert":{"title":"I am title","subtitle":"I am subtitle","body":"I am body"},"sound":"default","badge":1}}Copy the code
- registration
IOS10.0 before
/ / below iOS8 [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound]; //iOS8 - iOS10 [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge categories:nil]];Copy the code
IOS10.0 and later
// 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
}
Copy the code
- Get Push Settings
Before iOS10.0, you can’t get push Settings. IOS 10 can also get push Settings in real time:
@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}} / / get set UNUserNotificationCenter. Current () getNotificationSettings {Settings in print(settings.authorizationStatus) // .authorized | .denied | .notDetermined print(settings.badgeSetting) // .enabled | .disabled | .notSupported }Copy the code
2 UserNotifications
The UserNotifications framework was added to iOS10.0 and later, and the framework in Swift includes the following libraries:
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
Copy the code
3. Code to be implemented
- Sign up for remote push
To import the UserNotifications header, register the following logic:
/ / the AppDelegate didFinishLaunchingWithOptions method of remote push notification/registration / - (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) {/ / registered successfully DispatchQueue. Main. Async {application. RegisterForRemoteNotifications ()}}} else {/ / users are not allowed to push}}} the else If (setting. AuthorizationStatus = =. Denied) {/ / application user permissions rejected} else if (setting. AuthorizationStatus = =. Authorized) {/ / Authorized users (again for dt) DispatchQueue. Main. Async {application. RegisterForRemoteNotifications ()}} else {/ / unknown error}}}}Copy the code
- Processing 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) {
// 弹窗提示
}
Copy the code
- Processing received push messages:
// 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 __TVOS_AVAILABLE options)) completionHandler __IOS_AVAILABLE (10.0) (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 __WATCHOS_AVAILABLE (10.0) (3.0) __TVOS_PROHIBITED __OSX_AVAILABLE (10.14); // 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 __OSX_AVAILABLE (12.0) (10.14) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;Copy the code
Once you’ve written your code and set up your certificate, you can use the test tool Pusher and the real machine to test it…
Recommended articles:
IOS UI state saving and recovery (3) iOS UI state saving and recovery (2) iOS UI state saving and recovery (1) Swift operator Common method of accurate timing in iOS Dart Foundation (1) Dart Foundation (2) Dart Foundation (3) Dart Foundation (4) Strange dance weekly