iOS Notification Service

This commit is contained in:
2026-05-07 14:07:02 -04:00
parent 69469fa2ad
commit 5304ab1d6d
4 changed files with 235 additions and 2 deletions

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.usernotifications.service</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).NotificationService</string>
</dict>
</dict>
</plist>

View File

@@ -0,0 +1,49 @@
//
// NotificationService.swift
// NotificationService
//
// Created by Matias Carulli on 5/7/26.
//
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 content = bestAttemptContent,
let imageUrlString = request.content.userInfo["imageUrl"] as? String,
let imageUrl = URL(string: imageUrlString)
else {
contentHandler(request.content)
return
}
URLSession.shared.downloadTask(with: imageUrl) { location, _, error in
defer { contentHandler(content) }
guard let location = location, error == nil else { return }
let tmpFile = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(imageUrl.lastPathComponent)
try? FileManager.default.moveItem(at: location, to: tmpFile)
if let attachment = try? UNNotificationAttachment(identifier: "avatar", url: tmpFile) {
content.attachments = [attachment]
}
}.resume()
}
override func serviceExtensionTimeWillExpire() {
if let contentHandler = contentHandler, let content = bestAttemptContent {
contentHandler(content)
}
}
}