스트리밍은 대부분의 브라우저와
Developer 앱에서 사용할 수 있습니다.
-
푸시 알림 입문서
중요한 이벤트와 업데이트에 대한 푸시 알림을 통해 사용자가 앱을 최대한 활용할 수 있도록 돕고, 백그라운드에서 최신 데이터를 제공하여 앱을 열면 데이터를 바로 확인할 수 있도록 하세요. 알림을 사용하여 사용자에게 관련성 높은 정보를 시의적절하게 알리는 방법을 알아보세요. 경고 알림 및 백그라운드 알림의 차이점과 앱에 이러한 알림을 적용하는 방법을 알아보고, 작업에 적합한 API를 사용하여 실수를 방지하세요.
리소스
관련 비디오
WWDC23
-
다운로드
Hello and welcome to WWDC.
Hi. My name is Elliot Garner, and in this video, I'm going to be discussing push notifications. Let's begin with an overview of push notifications, what they are and why you might use them. Then, I will be discussing how you can add them to your application.
Push notifications allow applications to be engaging and interactive. They provide you the ability to deliver updates to your application in real time.
This allows for a more dynamic experience when it comes to updating your application. So, what exactly are the advantages to adding push notifications to your application? First, they do not require your application to be in the foreground.
Push notifications are delivered to your application regardless of the app state and, if necessary, your application will be launched.
Push notifications are power-efficient and are a great way to engage with your customers. There are two types of push notifications: Alert notifications and background notifications. Alert notifications allow you to deliver visible alerts that can be interacted with in ways that your app can customize.
Background notifications allow your application to receive runtime while it is not in the foreground in order to keep your content up-to-date. Now, let's talk about alert pushes first.
Alert pushes allow you to deliver a visible alert to give an update about your application. This alert should be used to inform about new information that can be interacted with. This alert does not require your application to be running and will be displayed regardless of app state. And, most importantly, it's entirely customizable. How the alert looks, and its interact-ability, is up to you.
Let's look at how you would begin setting up your application for alert notifications. The first thing you need to do is register for remote notifications.
This will register the device for Apple Push Notification system, or APNs, and will return a device token to your application.
This token is used to identify the device and lets you target it for notifications.
Next, you will need to declare your AppDelegate a UNUserNotificationCenterDelegate. Once you have done that, you will assign your AppDelegate as a delegate of the Notification Center. This will let your application be notified when your alert gets opened. Once you have called registerForRemoteNotifications, you will receive a callback on one of these two methods. If you failed to get a token for the device, didFailToRegisterFor RemoteNotificationsWithError will be called with the error describing why registration failed.
If you succeeded in getting a token, you need to send that token to your back end push server so you can deliver notifications to this device. Let's take a look at an example of that. The device token is delivered to your application as a data object. So, in order to send it to your server, it needs to be converted into a string.
You can do that by separating the data into its components, converting those components into a hexadecimal string, and then joining them back together into a single string.
You then append that string to your URLQuery to make your fully qualified endpoint.
Then, you perform a URLSession to send that token to your server to register it in your database.
Lastly, before the device can receive any notifications, you need to ask for permissions for your application to display alerts. Calling requestAuthorization results in a prompt being displayed asking if your application can display alerts.
The result of that decision will be passed to the completionHandler and is set in device settings. Any successive calls to this method will return the status in device settings and will not result in a prompt. As you can see, this function is asking for permissions to display an alert, play a sound, and present a badge on the application icon.
Only request authorization in response to an action when there is context. You are much more likely to get permissions with this context. Before discussing how to handle a notification payload, let's look at an example payload.
Let's say that you're building an application for a restaurant that wants to be able to alert users whenever there is a new special.
As you can see, this alert is telling us that the Avocado Bacon Burger is now on sale.
Let's step through this payload piece by piece to make sure that it's understood. First is the aps dictionary. This aps dictionary tells the device how to render the notification. Inside of the aps dictionary is the alert dictionary. This tells the system what text to use for the notification.
Inside of that are the title and body fields. The title field is a short string describing the purpose of the notification. This needs to be short and easy to understand.
The body field is the full descriptive text of the alert message. Next is the sound field. This field is optional and should be included when you want the device to play a sound when the alert is received. If you wanna use the default sound, simply use default like this. However, you can also provide custom sounds for your application. Next is the badge field. This is an optional field which is used to modify the badge of your app icon.
This is an absolute value which will be displayed on the app icon.
This value can be modified programmatically, so once the alert has been opened, set this value to zero when handling the notification.
Outside of the aps field, you have any custom data that you might wanna provide alongside the notification. Here, it's telling the application what the special is for today, and how much it costs.
Now that we know what our payload looks like, let's examine how to handle receiving a notification.
This method is the UNUser NotificationCenterDelegate method that is called whenever your notification is opened. This method has a completionHandler that must be called before returning from the function. The payload that was delivered to the application can be extracted from the userInfo property of the notification's content. Once you have the payload, parse the data from the dictionary representation of the JSON.
If the data isn't there as is expected, call the completionHandler before returning. This lets the system know that you have finished handling the opening of the notification. Once you have the data, you can perform any updates necessary to your application.
You should be opening the part of your application relevant to the alert. In the example of the restaurant, when the alert is tapped, the item is added to the cart and the cart is displayed.
Once you're done, call the completionHandler to tell the system that you finished. And that's it. That's all that you need to do to set up your application to handle and receive alert notifications.
Now that we've examined implementing alert pushes, let's discuss background pushes and how you can use them in your application. Background pushes are similar to alert pushes but there are some crucial differences that are important to remember.
Background notifications allow your application to fetch data from the background upon receiving push notifications.
These should be used to keep your application up-to-date even if the application isn't running. The system will launch your application and give you necessary runtime in order to perform your background update. However, there are some limitations. The system limits applications to so many background operations a day, and background updates will not be performed if the device is under certain constraints. For example, if the device is in a low battery state.
So, what do you need to do in order to set up your application to register for and handle receiving background pushes? Like with alert pushes, you need to register your application for remote notifications in order to obtain a device token for your application.
However, unlike alert pushes, you do not need to make your application a UNUserNotificationCenterDelegate or assign it to the UNUserNotificationCenter. That's because the UNUserNotificationCenterDelegate is only used when handling alert notifications. And since background notifications are all that's being implemented here, it's unnecessary.
Because registerForRemoteNotifications was called, you still need to handle receiving a device token, and you still need to send that device to your push server for your own registration. This is exactly the same as what needs to be done for alert notifications. Now, let's examine the payload for a background notification. As you can see, background notification payloads are much more simple than alert notifications. The only field required for background notifications is the content-available field inside of the aps dictionary.
This field tells the system that this is a background notification and that your application should be launched to perform your updates. Just like alert notifications, the outside of the aps dictionary can be used for custom data. Now, let's look at how you would handle a background push.
When the device receives any remote notification, didReceiveRemoteNotification is called.
Use this method to handle your background notification.
This function also has a completionHandler. However, unlike the completionHandler when handling alert notifications, this completionHandler has one parameter.
This parameter is an enum which tells the system whether your background update failed... received no data... or received new data.
This allows the system to be smart about when to launch your application in the future.
So, in the case of the restaurant application, background notifications are being used to fetch the menu every day in order to make sure its content is up-to-date.
If the URL for the current version of the menu fails to be made, call the completionHandler and tell it the background update failed.
Once the URL is created, a URLSession needs to be created in order to fetch the data for today's menu.
If no data was received, call the completionHandler and tell it that the background update finished successfully with no data.
Otherwise, now that the updated menu has been fetched, the application can use that data to update its contents. And once that has been finished, the completionHandler can be called to tell the system that the background update has succeeded and retrieved new data.
And that's all it takes to get your application to handle background notifications.
Now that you know what push notifications are, how they can be used, and how to implement them, it should be no problem to add them to your application.
All that you need to do is enable push notifications in the developer portal and follow these steps to add push notifications to your application.
Download the sample app. It has all of the codes shown in this video. Look through it, and use it as a jumping-off point for adding notifications to your apps. Once you have done these things, you are well on your way to creating an enriched experience for your applications. Thank you.
-
-
2:02 - Registering for notifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.registerForRemoteNotifications() UNUserNotificationCenter.current().delegate = self return true }
-
2:36 - UIApplicationDelegate callbacks
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { // The token is not currently available. print("Remote notification is unavailable: \(error.localizedDescription)") } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // Forward the token to your provider, using a custom method. self.forwardTokenToServer(token: deviceToken) }
-
3:05 - Forward token to server
func forwardTokenToServer(token: Data) { let tokenComponents = token.map { data in String(format: "%02.2hhx", data) } let deviceTokenString = tokenComponents.joined() let queryItems = [URLQueryItem(name: "deviceToken", value: deviceTokenString)] var urlComps = URLComponents(string: "www.example.com/register")! urlComps.queryItems = queryItems guard let url = urlComps.url else { return } let task = URLSession.shared.dataTask(with: url) { data, response, error in // Handle data } task.resume() }
-
3:47 - Request authorization
@IBAction func subscribeToNotifications(_ sender: Any) { let userNotificationCenter = UNUserNotificationCenter.current() userNotificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in print("Permission granted: \(granted)") } }
-
4:43 - Payload JSON
{ "aps" : { "alert" : { "title" : "Check out our new special!", "body" : "Avocado Bacon Burger on sale" }, "sound" : "default", "badge" : 1, }, "special" : "avocado_bacon_burger", "price" : "9.99" }
-
6:11 - didReceive response
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo guard let specialName = userInfo["special"] as? String, let specialPriceString = userInfo["price"] as? String, let specialPrice = Float(specialPriceString) else { // Always call the completion handler when done. completionHandler() return } let item = Item(name: specialName, price: specialPrice) addItemToCart(item) showCartViewController() completionHandler() }
-
8:16 - Register for remote notifications (Background)
class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.registerForRemoteNotifications() return true }
-
9:05 - Background Notification Payload
{ "aps" : { "content-available" : 1 }, "myCustomKey" : "myCustomData" }
-
9:33 - didReceiveRemoteNotification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { guard let url = URL(string: "www.example.com/todays-menu") else { completionHandler(.failed) return } let task = URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data else { completionHandler(.noData) return } updateMenu(withData: data) completionHandler(.newData) } }
-
-
찾고 계신 콘텐츠가 있나요? 위에 주제를 입력하고 원하는 내용을 바로 검색해 보세요.
쿼리를 제출하는 중에 오류가 발생했습니다. 인터넷 연결을 확인하고 다시 시도해 주세요.