ios注銷所有通知
by Payal Gupta
通過Payal Gupta
您一直想了解的有關iOS中通知的所有信息 (Everything you’ve always wanted to know about notifications in iOS)
漂亮的小警報..? (Pretty Little Alerts..?)
Notifications are a way to inform users when new data becomes available for their apps, even when the app is not running in the foreground.
通知是一種在新數據可用于其應用程序時通知用戶的方法,即使該應用程序未在前臺運行。
For example, a messaging app might let the user know when a new message has arrived, and a calendar app might inform the user of an upcoming appointment.
例如,消息收發應用程序可能會在新消息到達時通知用戶,而日歷應用程序可能會通知用戶即將到來的約會。
With the release of iOS-10, Apple introduced brand new frameworks to support notifications, be it local or remote. This release was focused on customized notifications.
隨著iOS-10的發布, Apple引入了全新的框架來支持本地或遠程通知。 此版本的重點是自定義通知 。
Without wasting any time, let’s just quickly jump in to the details.
不浪費任何時間,讓我們快速進入細節。
通知類型 (Types of notifications)
We can broadly classify notifications into two categories:
我們可以將通知大致分為兩類:
Local notifications — the app configures the notification details locally and passes those details to the system. The system then handles the delivery of the notification when the app is not in the foreground.
本地通知 -應用程序在本地配置通知詳細信息,并將這些詳細信息傳遞給系統。 然后,當應用程序不在前臺時,系統處理通知的傳遞。
Remote notifications — you use one of your company’s servers to push data to user devices via the Apple Push Notification service (APNs).
遠程通知 -您使用公司的一臺服務器通過Apple推送通知服務(APN)將數據推送到用戶設備。
Further down in the article, we’ll see how we can get ahold of both notification types. Let’s first start with an introduction to this new notification framework that we can use for our cause.
在本文的后續部分,我們將看到如何獲取兩種通知類型。 首先讓我們開始介紹可以用于我們的事業的這個新的通知框架。
iOS-10的通知新功能是什么? (What’s new in iOS-10 for notifications?)
With the release of iOS-10, Apple introduced two new frameworks to handle notifications:
隨著iOS-10的發布,Apple引入了兩個新的框架來處理通知:
User Notifications Framework — manages both local and remote notifications.
用戶通知框架 -管理本地和遠程通知。
User Notifications UI Framework — customizes the appearance of the system’s notification interface.
用戶通知UI框架 —自定義系統通知界面的外觀。
We’ll be using these two frameworks and some platform-specific APIs to configure our notifications.
我們將使用這兩個框架和一些特定于平臺的API來配置我們的通知。
Along with the frameworks, the Notification service app extension was also introduced that allows you to modify the content of remote notifications before they are delivered.
除框架外, Notification service應用程序擴展 還引入了,使您可以在傳遞遠程通知之前對其進行修改。
Apple also allows customizing your notification’s UI though the Notification content extension.
Apple還允許通過Notification content extension來自定義通知的UI 。
Is it too much to remember? Yup...surely it is. But, don't worry. We’ll see everything step-by-step along with the relevant code. Just take it easy. ?
要記住的東西太多了嗎? 是的,肯定是。 但是,不用擔心。 我們將逐步查看所有內容以及相關代碼。 放輕松點。 ?
首先,配置它! (First things first — configure it!)
請求授權 (Request Authorization)
To get our app to notify the user of anything, we need to know whether the person using it actually wants that in the first place. Mayby they don’t like their phone ringing and displaying alerts all the time ? or maybe they actually want the updates, but not that irritating sound…naahhh!??
為了使我們的應用程序能夠通知用戶任何事情,我們首先需要知道使用該應用程序的人是否真的想要它。 也許他們不喜歡手機一直響和顯示警報嗎? 也許他們實際上是想要更新,但不是那種令人討厭的聲音……naahhh!??
So, first of all we need to get permission from the user we’re going to notify. And that’s pretty simple — just two lines of code and we’re done:
因此,首先,我們需要獲得要通知的用戶的許可。 這很簡單-只需兩行代碼,我們就完成了:
You need to write that code in AppDelegate’s
method — application:didFinishLaunchingWithOptions:
before returning from it.
您需要先從AppDelegate's
方法中編寫該代碼— application:didFinishLaunchingWithOptions:
然后再從中返回。
Please note: Because the system saves the user’s response, calls to requestAuthorization(options:completionHandler:)
method during subsequent launches do not prompt the user again.
請注意:由于系統保存了用戶的響應,因此在后續啟動期間對requestAuthorization(options:completionHandler:)
方法的調用不會再次提示用戶。
添加類別和操作-可操作的通知 (Adding Categories and Actions — Actionable Notifications)
The user notifications framework supports adding categories and actions to the notifications.
用戶通知框架支持向通知添加類別和操作。
Categories — Define the types of notifications that the app supports and communicate to the system how we want a notification to be presented.
類別 -定義應用程序支持的通知類型,并向系統傳達我們希望如何顯示通知的方式。
Actions — Each category can have up to four actions associated with it. Actions are basically custom buttons, that on tap dismiss the notification interface and forward the selected action to the app for immediate handling.
動作 -每個類別最多可以有四個關聯的動作。 動作基本上是自定義按鈕,點擊該按鈕可關閉通知界面,并將選定的動作轉發到應用程序以立即進行處理。
Okayyy! And what does that mean..??? Some code might help you understand better:
好吧! 那是什么意思.. ??? 一些代碼可以幫助您更好地理解:
In the above code, we simply created a category named INVITATION with four different actions — remindLater, accept, decline, and comment.
在上面的代碼中,我們僅創建了一個名為INVITATION的類別。 有四個不同的動作- remindLater, 接受 , 拒絕和 評論 。
The categories and actions are uniquely identified by their identifiers. Whenever a notification with a category is delivered, the system presents the notification along with all the actions associated with that category once the user expands it. This is what it will look like: ?
類別和動作由其標識符唯一標識。 每當傳遞帶有類別的通知時,一旦用戶展開該類別,系統就會顯示該通知以及與該類別關聯的所有動作。 它將是這樣的:
Define all the categories and actions just below where you configured notifications in application:didFinishLaunchingWithOptions:
method.
在您在application:didFinishLaunchingWithOptions:
方法中配置通知的位置下面,定義所有類別和操作。
Include the category identifier (eg. INVITATION) when scheduling your notification whether locally or remotely. We’ll see how to do that in the next section.
在本地或遠程安排通知時,請包括類別標識符(例如INVITATION)。 我們將在下一節中看到如何做。
安排本地通知 (Scheduling local notifications)
Now that we’re done with configuring our notifications, let’s see how to actually schedule one from within the app.
現在我們已經完成了配置通知的操作,讓我們看看如何在app中實際安排一個通知。
Scheduling a local notification requires just three simple steps:
安排本地通知僅需三個簡單步驟:
- Prepare the content 準備內容
- Add a trigger — when the notification should be fired 添加觸發器-何時觸發通知
- Schedule it for delivery 安排交貨
Let’s get on with the code quickly, so we don’t get confused with everything happening here. LOL ?
讓我們快速開始編寫代碼,這樣我們就不會對這里發生的一切感到困惑。 大聲笑 ?
In the above code, along with the other content, we have also provided a categoryIdentifier
to support actionable notifications. In case we don’t do that, the system will adopt it’s default behavior.
在上面的代碼以及其他內容中,我們還提供了categoryIdentifier
來支持可操作的通知。 如果我們不這樣做,系統將采用其默認行為。
That’s it. That’s all that’s needed. And yes it definitely works...hehehe.? Give it a try before moving on any further. You can download the sample from here.
而已。 這就是所需要的。 是的,它絕對有效...呵呵。 在繼續之前嘗試一下。 您可以從此處下載示例。
Please note: Apps behave differently in background and foreground states whenever a notification is delivered.
請注意 :每當收到通知時,應用在后臺和前臺狀態下的行為都會有所不同。
App not running / App in Background — the system displays local notifications directly to the user. We don’t get any callback in the app for that.
應用程序未運行/應用程序在后臺 -系統直接向用戶顯示本地通知。 我們沒有為此在應用程序中獲得任何回調。
App in Foreground — the system gives the app the opportunity to handle the notification internally. The system silences notifications for foreground apps by default.
前景中的應用程序-系統為應用程序提供了內部處理通知的機會。 默認情況下,系統使前臺應用程序的通知靜音 。
When the app is in foreground while the notification is delivered, we get the callback in UNUserNotificationCenterDelegate's
method — userNotificationCenter(_:willPresent:withCompletionHandler:)
where you can decide whether to handle the notification silently or alert the user about it.
當通知發送時應用程序處于前臺時,我們將在UNUserNotificationCenterDelegate 's
方法中獲取回調userNotificationCenter(_:willPresent:withCompletionHandler:)
,您可以在其中決定是靜默處理通知還是向用戶發出警報。
Don’t forget to conform AppDelegate
to UNUserNotificationCenterDelegate
protocol and setting it as the delegate of UNUserNotificationCenter
shared object in application:didFinishLaunchingWithOptions:
.
不要忘記使AppDelegate
符合UNUserNotificationCenterDelegate
協議,并將其設置為application:didFinishLaunchingWithOptions:
的UNUserNotificationCenter
共享對象的委托。
let center = UNUserNotificationCenter.current()
center.delegate = self
We’re done with local notifications for now. Let’s move on to how we can schedule a notification from outside our app. Before that, let’s have a look at how to respond to the custom actions.
目前,我們已完成本地通知。 讓我們繼續介紹如何從應用程序外部安排通知。 在此之前,讓我們看一下如何響應自定義操作。
響應用戶操作 (Responding to User Actions)
Configuring notifications? ? Scheduling notifications? ?
正在配置通知? ?安排通知? ?
What about tapping a notification or any custom action in the notification? Where will it lead? In both the cases, the system notifies the app of the user’s choice.
點擊通知或通知中的任何自定義操作怎么辦? 它會引向何方? 在這兩種情況下,系統都會向應用程序通知用戶的選擇。
Whenever the user performs any action in the notification, the response is sent to UNUserNotificationCenterDelegate's
method — userNotificationCenter(_:didReceive:withCompletionHandler:)
, where we can provide handling specific to each action.
每當用戶在通知中執行任何操作時,響應就會發送到UNUserNotificationCenterDelegate's
方法— userNotificationCenter(_:didReceive:withCompletionHandler:)
,在該方法中,我們可以為每個操作提供特定的處理。
Please note: if the app is not running when a response is received, the system launches the app in the background to process the response.
請注意:如果收到響應后應用未運行,則系統會在后臺啟動該應用以處理響應。
遠程通知 (Remote notifications)
Push notification or remote notifications, no matter what we call them, are one of the most frequently used with lots and lots of use-cases.
推送通知或遠程通知,無論我們如何稱呼它們,都是在很多用例中使用最頻繁的通知之一。
Be it social media or calendar or any of the utilities apps, we can see them almost everywhere. From news apps notifying us of the latest content, to Medium itself alerting us of the latest published articles.
無論是社交媒體,日歷還是任何實用程序應用程序,我們幾乎都可以在任何地方看到它們。 從通知我們最新內容的新聞應用程序到Medium提醒我們最新發布的文章。
Ever wonder how do they even do that? Local Notifications ?? It could be…it does the same thing — right? Maybe we can do some more configuration in the local one itself and get that working?
有沒有想過他們怎么做到這一點? 本地通知?? 可能是…做同樣的事情-對嗎? 也許我們可以在本地本身中做一些更多的配置并使它正常工作?
But Medium, for example, don’t have access to the app on our personal device, so how could it schedule any notifications? Exactly! It can’t. This is something different and something more than just the local ones.
但是,例如,Medium無法訪問我們個人設備上的應用程序,那么它將如何安排任何通知? 究竟! 不可以 這是不同的東西,而不僅僅是本地的東西。
Ok, how about we send the notification from some point and show it at some other point — will this answer our question? Yup, it surely will. But how to do that? Remote Notifications it is.
好的,我們如何從某個點發送通知并在其他點顯示通知,這將回答我們的問題嗎? 是的,肯定會。 但是該怎么做呢? 它是遠程通知 。
This is exactly what they do. This is the feature that has solved THE BIG PROBLEM of “Keeping up-to-date”.
這正是他們所做的。 此功能解決了“保持最新”的大問題。
術語 (Terminology)
APNs — the centerpiece of the remote notifications feature. It is a cloud service that allows approved third-party apps installed on Apple devices to send push notifications from a remote server to users over a secure connection.
APN —遠程通知功能的核心。 它是一項云服務,它允許安裝在Apple設備上的經過批準的第三方應用程序通過安全連接從遠程服務器向用戶發送推送通知。
Device Token — An app-specific token that is globally unique and identifies one app-device combination. It enables communication between the Provider, APNs, and the Device.
設備令牌-一種特定于應用程序的令牌,在全球范圍內是唯一的,可標識一個應用程序-設備組合。 它使提供者,APN和設備之間能夠進行通信。
Provider — Server that actually sends the remote notification including the device token and other information to APNs.
提供程序—實際將遠程通知(包括設備令牌和其他信息)發送到APN的服務器。
Important note: Never cache device tokens in your app. Instead, get them from the system when you need them.
重要說明 : 切勿在您的應用中緩存設備令牌。 而是在需要時從系統中獲取它們。
APNs issues a new device token to your app when certain events happen. The device token is guaranteed to be different, for example, when a user restores a device from a backup, when the user installs your app on a new device, and when the user reinstalls the operating system.
當某些事件發生時,APN會向您的應用發布新的設備令牌。 保證設備令牌是不同的,例如,當用戶從備份中還原設備時,當用戶在新設備上安裝您的應用程序以及當用戶重新安裝操作系統時。
When you attempt to fetch a device token but it has not changed, the fetch method returns quickly.
當您嘗試獲取設備令牌但未更改時,fetch方法將快速返回。
Please note: The ability of APNs to deliver remote notifications to a non-running app requires the app to have been launched at least once.
請注意: APNs能夠向未運行的應用程序傳遞遠程通知的功能要求該應用程序至少已啟動一次。
實際運作方式 (How it actually works)
Below is a small and quick explanation of how all the above technologies work together in sync to complete the remote notifications workflow.
以下是有關上述所有技術如何協同工作以完成遠程通知工作流程的簡短概述。
App registers with APNs
應用程式 向APN注冊
APNs sends device token to Device with then sends it to App
APNs將設備令牌發送到設備 ,然后將其發送到App
App sends this device token to Provider
應用將此設備令牌發送給提供商
Provider sends notifications with that device token to APNs which then sends it to Device which then sends it to the App.
提供商將帶有該設備令牌的通知發送到APNs ,然后將其發送到設備 ,然后再發送到App 。
If a notification for your app arrives with the device powered on but with the app not running, the system can still display the notification. If the device is powered off when APNs sends a notification, APNs holds on to the notification and tries again later.
如果在設備開機但未運行應用程序的情況下收到有關您應用程序的通知,則系統仍可以顯示該通知。 如果在APN發送通知時關閉了設備的電源,則APN會保留該通知并稍后再試。
在應用程序中處理 (Handle it in the app)
Now that we are aware of what remote notifications are and what things are needed to make them work, let’s now move on to how we can make our app support them. Because nothing happens on its own ?. We need to make some configurations for them to work.
既然我們知道了什么是遠程通知,需要哪些東西才能使它們正常工作,現在讓我們繼續介紹如何使我們的應用程序支持它們。 因為什么都沒有發生? 我們需要進行一些配置以使其正常工作。
To be able to handle remote notifications, our app must:
為了能夠處理遠程通知,我們的應用程序必須:
Enable remote notifications in capabilities — just one-click and you are done with this step. In the Capabilities tab of our Xcode project, enable the Push Notifications option. Ensure that Push Notifications is added to the App ID that we are using for the project.
啟用功能中的遠程通知 -只需單擊一下即可完成此步驟。 在我們的Xcode項目的“ 功能”選項卡中,啟用“ 推送通知”選項。 確保將推送通知添加到我們用于項目的應用程序ID中。
2. Register with Apple Push Notification service (APNs) and receive an app-specific device token
2. 向Apple Push Notification Service(APN)注冊并接收特定于應用程序的設備令牌
Requesting to register with APNs is quick and easy. Just add the below code in UIApplicationDelegate’s
method— application:didFinishLaunchingWithOptions:
before returning from it.
申請向APN注冊很容易。 只需在UIApplicationDelegate's
方法中添加以下代碼( application:didFinishLaunchingWithOptions:
然后再從中返回即可。
UIApplication.shared.registerForRemoteNotifications()
Now there are two possibilities: either we get registered successfully or the process fails.
現在有兩種可能性:要么我們成功注冊,要么過程失敗。
On successful registration, APNs sends an app-specific device token to the device inUIApplicationDelegate’s
method— application:didRegisterForRemoteNotificationsWithDeviceToken:
.
成功注冊后,APNs使用UIApplicationDelegate's
方法application:didRegisterForRemoteNotificationsWithDeviceToken:
向該設備發送特定于應用程序的設備令牌。
In case of faliure, we receive a callback in UIApplicationDelegate’s
method—application:didFailToRegisterForRemoteNotificationsWithError:
.
如果出現故障,我們會在UIApplicationDelegate's
方法中收到一個回調application:didFailToRegisterForRemoteNotificationsWithError:
3. Send the device token to notification provider server
3.將設備令牌發送到通知提供者服務器
As of now, we’ve received the device token from APNs. Now, we need to send this token to our provider, which will use it while pushing any notifications to our device.
到目前為止,我們已經從APNs收到了設備令牌。 現在,我們需要將此令牌發送給我們的提供商,該提供商將在將任何通知推送到我們的設備時使用它。
Since we don’t have a provider, for now we can use Easy APNs Provider for testing our push notifications. Further down, we’ll see how exactly we can make use of this tool.
由于我們沒有提供者,因此現在我們可以使用Easy APNs Provider來測試我們的推送通知。 再往下看,我們將看到如何精確地使用此工具。
For now, just download and install it on your Mac.
現在,只需下載并將其安裝在Mac上即可。
4. Implement support for handling incoming remote notifications
4.實施對處理傳入的遠程通知的支持
We have our device token, and our provider also knows about it. Next, the Provider will send the notification including this token and other information in it, and we’ll get it on our device.
我們有我們的設備令牌,我們的提供商也知道這一點。 接下來,提供商將發送包含此令牌和其他信息的通知,我們將在設備上獲取該通知。
Now what? What will happen when it arrives? How will it appear on the device? What will happen when we tap on it? What about all the actions that we configured earlier? Can we get them here?
怎么辦? 當它到達時會發生什么? 它將如何出現在設備上? 當我們點擊它會發生什么? 那么我們之前配置的所有操作呢? 我們可以把它們送到這里嗎?
Too many question ???Well, don’t worry. We’ll have answers to all of them one-by-one.
太多的問題???好,不用擔心。 我們將一一解答所有問題。
What will happen when it arrives? We’ll get a callback in UIApplicationDelegate’s
method— application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
. It tells the app that a remote notification has arrived that indicates there is data to be fetched.
當它到達時會發生什么? 我們將在UIApplicationDelegate's
方法中獲得一個回調— application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
。 它告訴應用程序遠程通知已到達,該通知指示有數據要提取。
How will it appear on the device? It will appear with the default notification interface. If the notification’s payload is configured with category, it will appear as the actionable notification with all the actions attached to that category. We’ll discuss the payload in next section.
它將如何出現在設備上? 它將與默認的通知界面一起出現。 如果通知的有效負載配置為category ,它將顯示為可操作的通知,其中所有操作都附加到該類別。 我們將在下一節中討論有效負載。
What will happen when we tap on it? Same as local notifications. UNUserNotificationCenterDelegate's
method — userNotificationCenter(_:didReceive:withCompletionHandler:)
is called with the response object.
當我們點擊它會發生什么? 與本地通知相同。 UNUserNotificationCenterDelegate's
方法— userNotificationCenter(_:didReceive:withCompletionHandler:)
與響應對象一起調用。
在提供者上處理 (Handle it on the Provider)
We have covered most of the things we need to integrate push notifications into our app. Although we know how to handle them in the app, we are still short of handling them on the provider.
我們已經介紹了將推送通知集成到我們的應用程序中所需的大部分內容。 盡管我們知道如何在應用程序中處理它們,但仍然缺少在提供程序上處理它們的方法。
We have the provider. It knows what device token to use, but that alone won’t pop up a notification on our device with some title and other details. Neither will it make any of the actions appear.
我們有提供者。 它知道要使用的設備令牌,但僅此一個,就不會在我們的設備上彈出帶有標題和其他詳細信息的通知。 也不會使任何動作出現。
So, pushing notifications from the provider requires the following items:
因此,推送來自提供商的通知需要以下各項:
A device token
設備令牌
APNs certificate — we can obtain it from the developer account
APNs證書 -我們可以從開發者帳戶中獲取
Payload — any custom data that you want to send to your app, and includes information about how the system should notify the user. It’s simply a JSON dictionary with some key value pairs. The below illustration might help you understand it better.
有效負載 -您要發送到應用程序的任何自定義數據,包括有關系統應如何通知用戶的信息。 它只是一個帶有一些鍵值對的JSON字典 。 下圖可能幫助您更好地理解它。
Let’s see what’s all in that JSON dictionary:
讓我們看看JSON字典中的全部內容:
aps dictionary — the most important one. Contains Apple-defined keys and is used to determine how the system that is receiving the notification should alert the user.
APS 字典 -最重要的一個。 包含Apple定義的鍵 ,用于確定接收通知的系統應如何警告用戶。
alert dictionary — it is more of a self-explanatory item. Provides the content of the notification.
警報 字典 -它更多是一個不言自明的項目。 提供通知的內容。
category — for actionable notifications. All the actions attached to that category will be available in the notifications.
類別 -用于可操作的通知。 通知中將提供該類別所附的所有操作。
content-available — To support a background update notification, set this key to 1.
內容可用 —要支持后臺更新通知,請將此鍵設置為1。
mutable-content — To enable a notification’s modification through Notification Service App Extension, set it to 1.
可變內容 —要通過Notification Service App Extension啟用通知的修改,請將其設置為1。
Here you can read more about customizing the payload as per your requirements. This is a reference to the keys that we can add in the aps dictionary
在這里,您可以閱讀有關根據需要自定義有效負載的更多信息。 這是對我們可以在aps字典中添加的鍵的引用
通知服務應用程序擴展 (Notification Service App Extension)
At this point, we know what remote notifications are, how they work, what all we need to get them working — pretty much everything! Since we just got them working perfectly??.
至此,我們知道了哪些遠程通知 是什么,它們如何工作,我們需要什么來使它們工作-幾乎所有東西! 因為我們只是讓它們完美地工作??。
Now the question is, what if we want to modify some content in the notification received from the provider, before presenting it on the device? What if the notification contains some image link that we need to download before delivering it to the user? Can we do that with what we already know? We don’t have access to the provider…so how will we?
現在的問題是,如果我們要在從提供商那里收到的通知中修改某些內容,然后再將其顯示在設備上怎么辦? 如果通知中包含一些我們需要先下載的圖像鏈接,該怎么辦? 我們可以用我們已經知道的做嗎? 我們沒有訪問提供者的權限……那我們將如何?
We can’t actually. We can’t change what we get, but we can definitely change what we present.
我們實際上不能。 我們無法改變我們得到的,但是我們絕對可以改變我們所呈現的。
That’s what Notification Service App Extension is all about— modifying the content of remote notifications before delivery. It is as simple as it looks. No fancy code, nothing. It’s really very simple.
這就是Notification Service App Extension的全部目的-在交付前修改遠程通知的內容。 它看起來很簡單。 沒有花哨的代碼,什么都沒有。 這真的非常簡單。
向項目添加Notification Service Extension (Adding Notification Service Extension to the project)
Extensions in an xcode project are added as a target. Select File — New — Target — Notification Service Extension.
xcode項目中的擴展被添加為目標。 選擇文件 - 新建 - 目標 - 通知服務擴展。
先決條件 (Prerequisites)
Before we begin to modify the content, there are some restrictions on when the content is allowed to be modified.
在我們開始修改內容之前,對何時允許修改內容有一些限制。
Content can be modified only if:
僅在以下情況下才能修改內容:
- The remote notification is configured to display an alert. 遠程通知配置為顯示警報。
The remote notification’s aps dictionary includes the mutable-content key with the value set to 1.
遠程通知的aps詞典包含可變內容鍵,其值設置為1。
We cannot modify silent notifications or those that only play a sound or badge the app’s icon.
我們無法修改靜默通知或僅播放聲音或標記應用程序圖標的靜默通知。
So, to support any modifications in the notifications’ content, these conditions must be fulfilled.
因此,為了支持對通知內容的任何修改,必須滿足這些條件。
修改內容 (Modifying the content)
The default notification service extension target provided by Xcode contains a subclass of the UNNotificationServiceExtension
class for us to modify.
Xcode提供的默認通知服務擴展目標包含UNNotificationServiceExtension
類的子類,供我們修改。
It contains two methods:
它包含兩種方法:
didReceive(_:withContentHandler:)
— make any needed changes to the notification and notify the system when you’re done. This method has a limited amount of time (about 30 secs) to perform its task and execute the provided completion block.didReceive(_:withContentHandler:)
—對通知進行任何必要的更改,并在完成后通知系統。 該方法執行任務并執行提供的完成塊的時間有限(約30秒)。serviceExtensionTimeWillExpire()
— Tells us that the extension is about to be terminated. Give us one last chance to submit our changes. If we don’t update the notification content before time expires, the system displays the original content.serviceExtensionTimeWillExpire()
—告訴我們該擴展即將終止。 給我們最后一次提交更改的機會。 如果我們在時間到期之前不更新通知內容,則系統將顯示原始內容。
Let’s look at an example. We’ll change the body in payload in Code Snippet 7 to “Address: Sea Shells Apartments, Mumbai”.
讓我們來看一個例子。 我們將代碼片段7中有效負載中的主體更改為“ Address:孟買Sea Shells Apartments, ”。
All the default implementation of both the methods is provided by the extension itself. We just have to make the changes we want, like in Line 8 in the above code snippet. Just a single line of code for now. Similarly, you can modify other fields as per your requirements.
擴展本身提供了這兩種方法的所有默認實現。 我們只需要進行所需的更改,就像上面的代碼片段中的第8行一樣。 現在只需一行代碼。 同樣,您可以根據需要修改其他字段。
通知內容擴展 (Notification Content Extension)
Having an eye-catching UI is always better than a simple default UI. Adding some colors and some pretty fonts is never a bad idea. We’re going to do the same with our notifications to make them look Wow!?
擁有醒目的UI總是比簡單的默認UI更好。 添加一些顏色和一些漂亮的字體絕不是一個壞主意。 我們將對通知進行同樣的處理,以使它們看起來哇!?
And and and…Apple is here to our rescue again. Notification content extension it is. This presents a custom interface for a delivered local or remote notification.
而且還有…… 蘋果再次在這里為我們解救。 通知內容擴展名是。 這提供了本地交付的自定義界面 要么 遠程通知。
向項目添加通知內容擴展 (Adding Notification Content Extension to the project)
I think we already know how to do that. Don’t we? We’re going to the same what we did for adding Notification Service Extension. Select File — New — Target — Notification Content Extension.
我認為我們已經知道該怎么做。 不是嗎 我們將進行與添加Notification Service Extension相同的操作 。 選擇文件 - 新建 - 目標 - 通知內容擴展。
向擴展的Info.plist添加一些鍵 (Adding some keys to extension’s Info.plist)
To support custom UI for local and remote notifications, we need to make some changes in the Info.plist file of content extension.
為了支持本地和遠程通知的自定義UI,我們需要在內容擴展的Info.plist文件中進行一些更改。
UNNotificationExtensionCategory (reqd.) — A string or an array of strings. Each string contains the identifier of a category declared by the app. Category, I must say, is really really important for notifications. Custom UI will only appear for the notifications lying in the specified categories.
UNNotificationExtensionCategory(必填) —一個字符串或字符串數??組。 每個字符串都包含應用程序聲明的類別的標識符。 我必須說, 類別對于通知確實非常重要。 自定義用戶界面僅會顯示在指定類別中的通知。
UNNotificationExtensionInitialContentSizeRatio (reqd.) — A floating-point number that represents the initial size of the view controller’s view expressed as a ratio of its height to its width. It’s the view controller that we’ll use for making custom UI. We’ll discuss that in the upcoming section.
UNNotificationExtensionInitialContentSizeRatio(reqd。) —一個浮點數,它表示視圖控制器視圖的初始大小,以其高度與寬度之比表示。 這是我們將用于制作自定義UI的視圖控制器。 我們將在接下來的部分中進行討論。
UNNotificationExtensionDefaultContentHidden — if true: show only custom content. If false: show custom+default content.
UNNotificationExtensionDefaultContentHidden —如果為true :僅顯示自定義內容。 如果為 false :顯示自定義+默認內容。
UNNotificationExtensionOverridesDefaultTitle —if true: set the notification’s title to the title of the view controller. If false: notification’s title is set to app’s name.
UNNotificationExtensionOverridesDefaultTitle —如果為true :將通知的標題設置為視圖控制器的標題。 如果為false :通知的標題設置為應用程序的名稱。
Here is an illustration that can help us understand the above keys better.
這是一個插圖,可以幫助我們更好地理解上述鍵。
In the above illustration, the keys in Info.plist are configured as:
在上圖中, Info.plist中的鍵配置為:
UNNotificationExtensionCategory — INVITATION
UNNotificationExtensionCategory —邀請
UNNotificationExtensionInitialContentSizeRatio — 1
UNNotificationExtensionInitialContentSizeRatio — 1
UNNotificationExtensionDefaultContentHidden — false
UNNotificationExtensionDefaultContentHidden —假
UNNotificationExtensionOverridesDefaultTitle — false
UNNotificationExtensionOverridesDefaultTitle — false
創建自定義UI (Creating the custom UI)
Notification content extension provides us with a UIViewController
that conforms to UNNotificationContentExtension
protocol. This controller presents the interface of the notification. The Storyboard
file in the extension contains a single ViewController that we can use to create whatever UI we want the notification to present.
通知內容擴展為我們提供了一個符合UNNotificationContentExtension
協議的UIViewController
。 該控制器顯示通知的界面。 擴展中的Storyboard
文件包含一個ViewController,我們可以使用它創建我們想要通知呈現的任何UI。
Once we create the UI, we need to connect the elements in the NotificationViewController
in order to fill in the details. Whenever a notification arrives with an expected category, we receive a callback in UNNotificationContentExtension’s
method — didReceive(_:)
. This is the place where we can add details to our customized UI.
創建UI后,我們需要在NotificationViewController
中連接元素以填寫詳細信息。 每當有預期類別的通知到達時,我們都會在UNNotificationContentExtension's
方法UNNotificationContentExtension's
didReceive(_:)
收到回調。 在這里,我們可以向自定義UI添加詳細信息。
We’re almost done with our notification’s custom UI. Just 1 more thing. Since the custom UI is attached to the notifications’ category, that may have some actions attached to it. And…you got that right! ?We’ll get our actions automatically without any custom handling. Brilliant!?
通知的自定義UI幾乎完成了。 再多1件。 由于自定義用戶界面已附加到通知的類別中, 可能會附加一些動作。 而且...你說對了! ?我們將自動采取行動,而無需任何自定義處理。 輝煌!?
Content + Beautiful UI + Custom Actions — Everything done. What more can we ask for? Apple, you are great!?
內容+漂亮的用戶界面+自定義操作 -一切都完成了。 我們還能要求什么? 蘋果,你很棒!?
One last point: we can add handling to the custom actions in the extension, too. The system calls didReceive(_:completionHandler:)
method to respond to any selected actions. If our view controller doesn’t implement that method, the system delivers the selected action to your app for handling.
最后一點:我們也可以在擴展程序的自定義操作中添加處理。 系統調用didReceive(_:completionHandler:)
方法來響應任何選定的動作。 如果我們的視圖控制器未實現該方法,則系統會將選定的操作傳遞給您的應用以進行處理。
If implemented, we need to handle all the possible actions in this method. One thing that is important here is the completion
closure.
如果實施,我們需要處理此方法中所有可能的操作。 這里重要的一件事是completion
關閉。
completion
: The block to execute when you are finished performing the action. You must call this block at some point during your implementation. The block has no return value.
completion
:完成動作后要執行的塊。 在實現過程中的某個時候,您必須調用此塊。 該塊沒有返回值。
The closure accepts a single parameter dismiss
of type UNNotificationContentExtensionResponseOption
. We provide the following options:
閉包接受類型為UNNotificationContentExtensionResponseOption
的單個參數dismiss
。 我們提供以下選項:
doNotDismiss
— Don’t dismiss the notification interface.doNotDismiss
—不關閉通知界面。dismiss
— Dismiss the notification interface.dismiss
—關閉通知界面。dismissAndForwardAction--
Dismiss the notification interface and forward the notification to the app.dismissAndForwardAction--
關閉通知界面并將通知轉發到應用程序。
That sums up our notifications. Too much to remember? Practise makes Progress ?. Try making your own notifications now!
總結了我們的通知。 記不清了嗎? 實踐取得進步 ? 立即嘗試制作自己的通知!
樣例項目 (Sample Project)
You can download the sample project from here.
您可以從此處下載示例項目。
And the sample project for Notification Content Extension can be found here.
可以在這里找到Notification Content Extension的示例項目。
進一步閱讀 (Further reading)
Don’t forget to read my other articles:
不要忘記閱讀我的其他文章:
Everything about Codable in Swift 4
Swift 4中有關Codable的一切
Color it with GRADIENTS — iOS
使用GRADIENTS為它著色— iOS
Coding for iOS 11: How to drag & drop into collections & tables
iOS 11編碼:如何拖放到集合和表格中
All you need to know about Today Extensions (Widget) in iOS 10
您需要了解的有關iOS 10中的Today Extensions(Widget)的所有信息
UICollectionViewCell selection made easy..!!
UICollectionViewCell選擇變得簡單.. !!
Feel free to leave comments in case you have any questions.
如有任何疑問,請隨時發表評論。
翻譯自: https://www.freecodecamp.org/news/ios-10-notifications-inshorts-all-in-one-ad727e03983a/
ios注銷所有通知