我必须更新按批发送的通知。我必须:
我的问题是:当我将其发送到后端时,didReceive函数已完成,并且通知在更新之前发送。
我如何等待后端的响应? 还是您有其他想法?
import BatchExtension
import Core
import Middleware
import RxSwift
class NotificationService: BAENotificationServiceExtension {
var alreadySend: Bool = false
let batchHelper = BAERichNotificationHelper()
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
let userInfo = request.content.userInfo
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let defaultMessage = userInfo["on_error"] as? String {
let body = request.content.body
if body.contains("$") {
if let image = userInfo["image"] as? String {
renderPush(title: request.content.title, body: body, image: image, defaultMessage: defaultMessage)
}
}
} else {
super.didReceive(request, withContentHandler: contentHandler)
return
}
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
private func renderPush(title: String, body: String, image: String?, defaultMessage: String) {
let customPushNotification = CustomPushNotificationContent(body: body, image: image)
let credentialsStore = DummyCredentialStore()
let serviceProvider = ServiceProvider(
networkProvider: NetworkProvider(
endPoint: Server.endPoint,
timeoutIntervalForResource: 10,
timeoutIntervalForRequest: 10
),
credentialsStore: credentialsStore
)
if let credentials = DummyCredentialStore.getCredentialsFromSharedContainer() {
let service = serviceProvider.getPushNotificationService(credentials: credentials)
_ = service.renderPush(pushNotificationContent: customPushNotification)
.subscribe(onNext: { result in
let content = UNMutableNotificationContent()
content.title = title
if result.result != "ok" {
content.body = defaultMessage
} else {
content.body = result.body
}
if result.image != nil {
if let urlImage = URL(string: result.image ?? "") {
do {
let attachement = try UNNotificationAttachment(identifier: "image", url: urlImage, options: nil)
content.attachments.append(attachement)
} catch {}
}
}
self.bestAttemptContent = content
})
}
}
}