Veloria/NotificationService/NotificationService.swift
2025-06-16 16:44:03 +08:00

68 lines
2.4 KiB
Swift

//
// NotificationService.swift
// NotificationService
//
// Created by on 2025/6/16.
//
import UserNotifications
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
guard let bestAttemptContent = bestAttemptContent else {
contentHandler(request.content)
return
}
if let options = request.content.userInfo["fcm_options"] as? [String : Any],
let imageURLString = options["image"] as? String,
let imageURL = URL(string: imageURLString) {
downloadImage(from: imageURL) { attachment in
if let attachment = attachment {
bestAttemptContent.attachments = [attachment]
}
contentHandler(bestAttemptContent)
}
} else {
contentHandler(bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
//
private func downloadImage(from url: URL, completion: @escaping (UNNotificationAttachment?) -> Void) {
let task = URLSession.shared.downloadTask(with: url) { (downloadedUrl, _, error) in
guard let downloadedUrl = downloadedUrl else {
completion(nil)
return
}
let tmpDir = FileManager.default.temporaryDirectory
let tmpFile = tmpDir.appendingPathComponent(url.lastPathComponent)
do {
try FileManager.default.moveItem(at: downloadedUrl, to: tmpFile)
let attachment = try UNNotificationAttachment(identifier: UUID().uuidString, url: tmpFile, options: nil)
completion(attachment)
} catch {
completion(nil)
}
}
task.resume()
}
}