跳到主要内容

推送通知

问题

iOS 远程推送和本地通知的实现?

答案

APNs 远程推送

// 注册推送
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
guard granted else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}

// 获取 Device Token
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
// 发送 token 到服务器
}

// 接收推送
class AppDelegate: UIResponder, UNUserNotificationCenterDelegate {
// 前台收到推送
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound, .badge])
}

// 用户点击推送
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// 处理跳转
completionHandler()
}
}

本地通知

let content = UNMutableNotificationContent()
content.title = "提醒"
content.body = "该喝水了"
content.sound = .default

// 延迟触发
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)

let request = UNNotificationRequest(identifier: "water", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)

常见面试问题

Q1: 静默推送是什么?

答案content-available: 1 的推送不弹通知,只在后台唤醒 App 执行 application(_:didReceiveRemoteNotification:fetchCompletionHandler:),用于后台数据更新。需要开启 Background Modes → Remote notifications。

Q2: 推送到达率不高怎么排查?

答案:检查 Token 是否更新、APNs 证书/Key 是否正确、payload 格式是否正确。生产和沙盒环境的 APNs 地址不同。用户关闭通知权限不影响静默推送。

相关链接