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:

安排本地通知仅需三个简单步骤:

  1. Prepare the content准备内容
  2. Add a trigger — when the notification should be fired添加触发器-何时触发通知
  3. 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.

请注意 :每当收到通知时,应用在后台和前台状态下的行为都会有所不同。

  1. 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.

    应用程序未运行/应用程序在后台 -系统直接向用户显示本地通知。 我们没有为此在应用程序中获得任何回调。

  2. 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.

以下是有关上述所有技术如何协同工作以完成远程通知工作流程的简短概述。

  1. Appregisters with APNs

    应用程式APN注册

  2. APNs sends device token to Device with then sends it to App

    APNs将设备令牌发送到设备 ,然后将其发送到App

  3. App sends this device token to Provider

    应用将此设备令牌发送给提供商

  4. 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:

为了能够处理远程通知,我们的应用程序必须:

  1. 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:

因此,推送来自提供商的通知需要以下各项:

  1. A device token

    设备令牌

  2. APNs certificate we can obtain it from the developer account

    APNs证书 -我们可以从开发者帐户中获取

  3. 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字典中的全部内容:

  1. 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定义的键 ,用于确定接收通知的系统应如何警告用户。

  2. alert dictionary — it is more of a self-explanatory item. Provides the content of the notification.

    警报 字典 -它更多是一个不言自明的项目。 提供通知的内容。

  3. category — for actionable notifications. All the actions attached to that category will be available in the notifications.

    类别 -用于可操作的通知。 通知中将提供该类别所附的所有操作。

  4. content-available To support a background update notification, set this key to 1.

    内容可用 要支持后台更新通知,请将此键设置为1。

  5. 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 FileNewTargetNotification 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:

它包含两种方法:

  1. 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秒)。

  2. 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 FileNewTargetNotification 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文件中进行一些更改。

  1. 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(必填) 一个字符串或字符串数​​组。 每个字符串都包含应用程序声明的类别的标识符。 我必须说, 类别对于通知确实非常重要。 自定义用户界面仅会显示在指定类别中的通知。

  2. 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的视图控制器。 我们将在接下来的部分中进行讨论。

  3. UNNotificationExtensionDefaultContentHidden — if true: show only custom content. If false: show custom+default content.

    UNNotificationExtensionDefaultContentHidden —如果为true :仅显示自定义内容。 如果为 false :显示自定义+默认内容。

  4. 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中的键配置为:

  1. UNNotificationExtensionCategory INVITATION

    UNNotificationExtensionCategory 邀请

  2. UNNotificationExtensionInitialContentSizeRatio 1

    UNNotificationExtensionInitialContentSizeRatio 1

  3. UNNotificationExtensionDefaultContentHidden false

    UNNotificationExtensionDefaultContentHidden

  4. 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 。 我们提供以下选项:

  1. doNotDismiss — Don’t dismiss the notification interface.

    doNotDismiss —不关闭通知界面。

  2. dismiss — Dismiss the notification interface.

    dismiss —关闭通知界面。

  3. 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:

不要忘记阅读我的其他文章:

  1. Everything about Codable in Swift 4

    Swift 4中有关Codable的一切

  2. Color it with GRADIENTS — iOS

    使用GRADIENTS为它着色— iOS

  3. Coding for iOS 11: How to drag & drop into collections & tables

    iOS 11编码:如何拖放到集合和表格中

  4. All you need to know about Today Extensions (Widget) in iOS 10

    您需要了解的有关iOS 10中的Today Extensions(Widget)的所有信息

  5. 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注销所有通知

ios注销所有通知_您一直想了解的有关iOS中通知的所有信息相关推荐

  1. ios 蓝牙命令发送_实战恢复cisco 2950交换机的IOS

    本来想用两台思科交换机做实验的,可是通过console口进入其中一台交换机后却发现这个台交换机的IOS文件丢失了.本来正常进入交换机后应该是首先进入到用户模式的,而且提示符应该是">& ...

  2. ios 查看同文件名_实战恢复cisco 2950交换机的IOS

    本来想用两台思科交换机做实验的,可是通过console口进入其中一台交换机后却发现这个台交换机的IOS文件丢失了.本来正常进入交换机后应该是首先进入到用户模式的,而且提示符应该是">& ...

  3. ios设计登录功能_亲爱的产品设计师,这是iOS 14的新功能

    ios设计登录功能 On June 22, 2020 Apple previewed iOS 14 for the first time. As always there are quite some ...

  4. ios 自动缩小字体_小字体紫筑B丸85%中粗体文件+deb双版本

    今天带来的是有字由心雨公众号的一款收费字体『紫筑B丸』,我把5字重里面的中粗体提取出来单独缩小至85%后做成了单字重,同时把英文也改变成和中文对应的大小粗度后,整体感觉非常的舒服,也一直是我自用最久的 ...

  5. ios 自动打包命令_通过命令行xcodebuild编译打包iOS应用

    点击上方"软件测试精品"关注我们 为什么要自动化打包? iOS编译打包需要签名,测试包又需要连接不同后台服务器,开发人员就需要不断地打开Xcode编译打包成ipa,然后上传到ftp ...

  6. python电话通知_教你如何使用Python向手机发送通知

    你曾想尝试在服务器端或电脑上向手机发送通知吗? 你曾烦恼过企业邮箱的防骚扰机制吗? 现在,我们可以用一种简单轻松的方法来代替企业邮箱了! 进行以下的实验,你需要做好以下准备 1)注册并在手机上下载IF ...

  7. 注销slack账号_如何从您的Slack帐户中注销所有设备

    注销slack账号 If you're worried someone has access to your Slack account, or you want to make sure old d ...

  8. ios 检测是否联网_具透 | 你可能不知道,iOS 10 有一个中国「特供」的联网权限功能...

    9 月底,苹果正式在北京成立了苹果中国研发中心.近几年,我们也在每年更新的 iOS 系统中不断看到,苹果对中国市场的关照.从早前的九宫格输入法,到最近的骚扰电话拦截,都照顾了国内用户的需求. 在 iO ...

  9. ios 自定义拍照页面_无需解锁也能使用的iOS实用小组件

    侧滑惊喜 无需解锁也能使用的iOS小组件 iOS锁定后还可以使用很多小功能,今天我们就分享一下侧滑显示的小组件 Dragonstar·2020  侧滑 显示小组件  我们一直希望苹果能够将小组件直接添 ...

最新文章

  1. 精通mysql_《深入精通Mysql(五)》实战:Mysql实现主从复制
  2. Python3 异步编程之进程与线程-1
  3. ShareEntryActivity java.lang.ClassNotFoundException | Android类找不到问题
  4. Photoshop剪切板故障修复
  5. UVa11389 The Bus Driver Problem(贪心)
  6. Elasticsearch 使用copy_to组合字段进行查询
  7. 使用 udev 进行动态内核设备管理(转自suse文档)
  8. java中文件处理之图片_在Java 7中处理文件
  9. VS Code 关于SFTP上传文件到多服务器的配置
  10. thread_ThreadPoolExecutor
  11. 华为Mate 40系列或首发屏下摄像头:全球首个量产级别方案
  12. 苹果新机发布在即 供应链齐泼冷水:卖不了7000万台
  13. element提交图片限制一张_element-ui上传图片限制图片比例
  14. Windows vCenter 6.5升级 VUM的安装
  15. LeetCode 6罗马数字转整数
  16. 高等代数——大学高等代数课程创新教材(丘维声)——3.3笔记+习题
  17. 蛋壳梦破:CEO被限制消费,资金链碎了一地
  18. 利用大数据打造智慧港航运
  19. excel 表格怎么让内容回车换行?
  20. MOOS-ivp 多社区 系列停更

热门文章

  1. NOIP2000提高组复赛C 单词接龙
  2. ECharts 点击非图表区域的点击事件不触发问题
  3. linux安装日志切割程序
  4. Windows半透明窗口开发技巧
  5. 匿名函数、冒泡排序,二分法, 递归
  6. BZOJ 2818 Gcd
  7. 白鹭引擎 - 显示对象的基准点与横纵坐标 ( 绘制一个来回移动的绿色方块 )
  8. 【每日scrum】NO.5
  9. 视觉中的经典图像特征小结(一): 颜色直方图, HOG, LBP
  10. 详细讲解Quartz.NET