处理通知载荷
响应前台和后台通知。
处理通知载荷 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 4 节课。
有效负载结构
远程通知是服务器发送到 APNs 的 JSON 字典。保留的 aps 键包含用户可见的内容——提醒、声音和角标;同级的其他键则携带您的自定义数据,例如用于打开某个项目的 ID。
// Example payload JSON:
// {
// "aps": { "alert": { "title": "Hi", "body": "..." },
// "sound": "default", "badge": 1 },
// "itemId": "42"
// }aps 字典
在 aps 中,alert 可以是字符串,也可以是包含标题、正文和副标题的对象。sound、badge 以及 content-available 和 mutable-content 等标志也位于这里。aps 之外的所有内容都由您自行定义。
// aps keys:
// alert: { title, subtitle, body }
// sound: "default" or critical sound object
// badge: Int
// content-available: 1 (silent / background)
// mutable-content: 1 (allow modification)前台传递
默认情况下,应用处于前台时收到的通知不会显示。若要仍然显示通知,请实现委托对象的 willPresent,并返回您需要的展示选项,例如横幅和声音。
import UserNotifications
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification
) async -> UNNotificationPresentationOptions {
return [.banner, .sound, .badge]
}响应点击
用户点击通知时(无论应用是在后台运行还是已终止),委托对象的 didReceive response 都会执行。您可以在这里读取有效负载并导航到正确的界面。
import UserNotifications
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse
) async {
let info = response.notification.request
.content.userInfo
if let id = info["itemId"] as? String {
print("open item", id)
}
}读取 userInfo
完整的有效负载(包括您的自定义键)会以 content.userInfo 的形式提供,它是一个 [AnyHashable: Any] 字典。请谨慎转换每个值;切勿强制解包,因为格式错误的有效负载不应导致应用崩溃。
import UserNotifications
func route(_ userInfo: [AnyHashable: Any]) {
guard let screen = userInfo["screen"] as? String
else { return }
switch screen {
case "profile": print("go to profile")
case "cart": print("go to cart")
default: break
}
}静默(后台)通知
设置 content-available: 1 并省略提醒后,就会创建一个静默推送,在后台唤醒应用以获取数据,而不会显示界面。这类通知会受到系统限制,并且需要启用远程通知后台模式。
// Silent payload — no alert, just a wake-up:
// { "aps": { "content-available": 1 }, "sync": true }
let silent = "content-available wakes app quietly"
_ = silent后台获取处理程序
静默推送会通过应用委托对象的 didReceiveRemoteNotification 异步方法到达应用。您需要执行数据获取,并返回 UIBackgroundFetchResult,让系统知道是否获取到了新数据,以便系统规划今后的唤醒次数。
import UIKit
func application(
_ app: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any]
) async -> UIBackgroundFetchResult {
// fetch fresh data here
return .newData
}可变内容与服务扩展
使用 mutable-content: 1 时,通知服务扩展可以在通知显示前拦截推送,以解密正文、下载图片附件或重写标题。扩展完成这些操作的时间非常有限。
// Service extension entry point (UNNotificationServiceExtension):
// override didReceive(_:withContentHandler:)
// modify bestAttemptContent, then call contentHandler
let mutable = "mutable-content enables interception"
_ = mutable本地化提醒
若要在服务器端本地化文本,请发送 title-loc-key 和 loc-key,引用应用本地化字符串资源中的键,并使用 loc-args 提供替换参数。设备会根据用户的语言呈现文本,无需您发送预先翻译的内容。
// Localized alert payload:
// "alert": {
// "loc-key": "NEW_MESSAGE",
// "loc-args": ["Ada"]
// }
let localized = "loc-key resolves on device"
_ = localized更新角标
badge 值会设置应用图标上的数字。发送 badge: 0 会清除该数字。用户阅读内容后,您也可以通过代码调用 setBadgeCount 进行设置,使角标与未读状态保持同步。
import UserNotifications
func clearBadge() async {
try? await UNUserNotificationCenter.current()
.setBadgeCount(0)
}稳健的处理程序
将这些部分结合起来:在前台显示通知,在点击时进行导航,并验证每次类型转换。处理程序不会因意外的有效负载而崩溃,并且会尽可能提取信息。
import UserNotifications
func handleTap(_ response: UNNotificationResponse) {
let info = response.notification.request
.content.userInfo
guard let id = info["itemId"] as? String else {
print("no item id; open home")
return
}
print("navigate to item", id)
}快速检查
请回顾如何响应通知点击。
回顾
您已学会处理有效负载:
aps字典包含用户可见的内容;同级键包含您的数据,可通过userInfo读取。- 重写
willPresent以显示前台通知,并重写didReceive response以处理点击。 content-available: 1会触发静默后台获取,并返回UIBackgroundFetchResult。mutable-content可启用服务扩展;loc-key可在设备上本地化文本。
常见问题解答
「处理通知载荷」课时是免费的吗?
是的 — 「处理通知载荷」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 4 节课。
「处理通知载荷」这节课中我会学到什么?
响应前台和后台通知。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Swift Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「处理通知载荷」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Swift Academy 课中编写并运行代码吗?
能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。