Skip to content

Commit

Permalink
持续响铃推送结束响铃时,不重复显示推送。
Browse files Browse the repository at this point in the history
  • Loading branch information
Finb committed Jul 30, 2024
1 parent f588f83 commit c44005f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
3 changes: 2 additions & 1 deletion NotificationServiceExtension/NotificationService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class NotificationService: UNNotificationServiceExtension {
contentHandler(request.content)
return
}
self.currentContentHandler = contentHandler

// 所有的 processor, 按顺序从上往下对推送进行处理
// ciphertext 需要放在最前面,有可能所有的推送数据都在密文里
Expand Down Expand Up @@ -52,9 +53,9 @@ class NotificationService: UNNotificationServiceExtension {
}

override func serviceExtensionTimeWillExpire() {
super.serviceExtensionTimeWillExpire()
if let handler = self.currentContentHandler {
self.currentNotificationProcessor?.serviceExtensionTimeWillExpire(contentHandler: handler)
}
super.serviceExtensionTimeWillExpire()
}
}
16 changes: 16 additions & 0 deletions NotificationServiceExtension/Processor/CallProcessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class CallProcessor: NotificationContentProcessor {

self.registerObserver()
self.sendLocalNotification(identifier: identifier, content: bestAttemptContent)
self.cancelRemoteNotification(content: bestAttemptContent)
await startAudioWork()
return bestAttemptContent
}
Expand All @@ -38,11 +39,26 @@ class CallProcessor: NotificationContentProcessor {
/// 生成一个本地推送
private func sendLocalNotification(identifier: String, content: UNMutableNotificationContent) {
// 推送id和推送的内容都使用远程APNS的
guard let content = content.mutableCopy() as? UNMutableNotificationContent else {
return
}
content.sound = nil
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}

/// 响铃结束时取消显示远程推送,因为已经用本地推送显示了一遍
private func cancelRemoteNotification(content: UNMutableNotificationContent) {
// 远程推送在响铃结束后静默不显示
// 至于iOS15以下的设备,因不支持这个特性会在响铃结束后再展示一次, 但会取消声音
// 如果设置了 level 参数,就还是以 level 参数为准不做修改
if #available(iOSApplicationExtension 15.0, *), self.content?.userInfo["level"] == nil {
self.content?.interruptionLevel = .passive
} else {
content.sound = nil
}
}

// 开始播放铃声,startAudioWork(completion:) 方法的异步包装
private func startAudioWork() async {
return await withCheckedContinuation { continuation in
Expand Down

0 comments on commit c44005f

Please sign in to comment.