ios client study notes (eight): iOS client push notification

The push notification of the iOS client refers to sending notification messages to devices with installed applications through Apple's push notification service (APNs). These notifications can be displayed on the device's lock screen, notification center, and within apps to alert users of new messages or events that need to be addressed.

Push notifications usually include information such as title, body text, icons, etc., and can be customized with specific formatting and styles. Applications can use APNs to send messages to specified devices or device groups in order to provide users with useful information in a timely manner.

The following is a complete description of iOS client push notification:

1. Register APNs service

In order to use the APNs service, the application needs to register the APNs service first. This can be done by configuring the app's push notification settings in Xcode. At app launch, the device's token should be registered with APNs so that APNs can send notifications to the correct device.

2. Create notification content

The application needs to create notification content, including title, body, icon and other information. Notification content can be customized with specific formatting and styling to enhance the user experience.

3. Send notification

Apps can use APNs to send notifications to specified devices or groups of devices. A specific API or SDK can be used to send notifications in order to realize customized notification functions.

4. Processing notifications

When the device receives a notification, the application needs to process the notification and present it to the user. This can be achieved by customizing the application's notification handler. You can choose to display notifications on the device's lock screen, notification center, and within apps to alert users of new messages or events that need to be addressed.

Example:

The following is a complete code example for iOS client push notifications, including functions such as registering for APNs services, creating notification content, sending notifications, and processing notifications.

First, register the APNs service in the AppDelegate.swift file. At app launch, the device's token should be registered with APNs so that APNs can send notifications to the correct device. The specific code is as follows:

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Register for push notifications
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
        }
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("Device Token: \(token)")
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error.localizedDescription)")
    }

    // Handle notification when app is in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .badge, .sound])
    }

    // Handle notification when app is in background
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }

}

Next, when sending a notification, you need to create notification content, including title, body, icon and other information. Notification content can be customized with specific formatting and styling to enhance the user experience. The specific code is as follows:

import UIKit
import UserNotifications

func sendNotification() {
    let center = UNUserNotificationCenter.current()
    center.getNotificationSettings { (settings) in
        if settings.authorizationStatus == .authorized {
            let content = UNMutableNotificationContent()
            content.title = "New Message"
            content.body = "You have a new message from John Doe"
            content.sound = .default
            if let path = Bundle.main.path(forResource: "icon", ofType: "png") {
                let url = URL(fileURLWithPath: path)
                do {
                    let attachment = try UNNotificationAttachment(identifier: "icon", url: url, options: nil)
                    content.attachments = [attachment]
                } catch {
                    print("Failed to attach icon to notification: \(error.localizedDescription)")
                }
            }
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
            let request = UNNotificationRequest(identifier: "newMessage", content: content, trigger: trigger)
            center.add(request)
        }
    }
}

Finally, when handling notifications, you need to customize your application's notification handler to implement it. You can choose to display notifications on the device's lock screen, notification center, and within apps to alert users of new messages or events that need to be addressed. The specific code is as follows:

import UIKit
import UserNotifications

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Handle notification when app is in foreground
        UNUserNotificationCenter.current().delegate = self
    }

}

extension ViewController: UNUserNotificationCenterDelegate {

    // Handle notification when app is in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .badge, .sound])
    }

    // Handle notification when app is in background
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }

}

The above is a complete code example of iOS client push notification, including functions such as registering APNs service, creating notification content, sending notification and processing notification.
In short, iOS client push notification is a very useful function that can help applications provide users with useful information in a timely manner and improve user experience. In order to use this feature, the app needs to register with the APNs service, create notification content, send notifications, and handle notifications.

Guess you like

Origin blog.csdn.net/goodgoodstudy___/article/details/130307226