Anonymous
Уведомление о Push -Image, не отображающееся в iOS с расширением службы уведомлений
Сообщение
Anonymous » 19 фев 2025, 11:27
В настоящее время я работаю над реализацией уведомлений о Push в моем приложении для iOS, используя расширение службы уведомлений, но изображение не отображается в уведомлении. Ниже приведены подробности моей реализации: < /p>
Код: Выделить всё
import UIKit
import Flutter
import GoogleMaps
import Firebase
import FirebaseMessaging
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
if #available(iOS 12.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
print("Permission granted: \(granted)")
}
}
application.registerForRemoteNotifications()
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
< /code>
natificationservice: < /p>
import UserNotifications
import os.log
class NotificationService: UNNotificationServiceExtension {
private var contentHandler: ((UNNotificationContent) -> Void)?
private var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
os_log("Entered didReceive method.", log: .default, type: .info)
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
defer {
os_log("Completing content handler.", log: .default, type: .info)
contentHandler(bestAttemptContent ?? request.content)
}
guard let attachment = request.attachment else {
os_log("Attachment not found.", log: .default, type: .error)
return
}
os_log("Attachment found: %@", log: .default, type: .info, attachment.identifier)
bestAttemptContent?.attachments = [attachment]
}
override func serviceExtensionTimeWillExpire() {
os_log("Service extension time will expire.", log: .default, type: .info)
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}
extension UNNotificationRequest {
var attachment: UNNotificationAttachment? {
os_log("Attempting to fetch image URL from payload.", log: .default, type: .info)
guard let attachmentURL = content.userInfo["image_url"] as? String else {
os_log("Image URL not found in payload.", log: .default, type: .error)
return nil
}
let encodedURLString = attachmentURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
os_log("Original URL: %@", log: .default, type: .info, attachmentURL)
os_log("Encoded URL: %@", log: .default, type: .info, encodedURLString ?? "nil")
guard let encodedURL = URL(string: encodedURLString ?? ""), let imageData = try? Data(contentsOf: encodedURL) else {
os_log("Failed to create URL from encoded string.", log: .default, type: .error)
return nil
}
os_log("Creating attachment with fetched image data.", log: .default, type: .info)
return try? UNNotificationAttachment(data: imageData, options: nil)
}
}
extension UNNotificationAttachment {
convenience init(data: Data, options: [NSObject: AnyObject]?) throws {
let fileManager = FileManager.default
let temporaryFolderName = ProcessInfo.processInfo.globallyUniqueString
let temporaryFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(temporaryFolderName, isDirectory: true)
try fileManager.createDirectory(at: temporaryFolderURL, withIntermediateDirectories: true, attributes: nil)
let imageFileIdentifier = UUID().uuidString + ".jpg"
let fileURL = temporaryFolderURL.appendingPathComponent(imageFileIdentifier)
try data.write(to: fileURL)
os_log("Image data written to file: %@", log: .default, type: .info, fileURL.absoluteString)
try self.init(identifier: imageFileIdentifier, url: fileURL, options: options)
}
}
< /code>
info.plist:
NSAppTransportSecurity
NSAllowsArbitraryLoads
Playload имеет mitable-content: 1 ,
Несмотря на приведенные выше конфигурации, изображение не отображается в уведомлении. Я гарантировал, что URL -адрес изображения доступен и правильно отформатирован. Любая помощь или понимание решения этой проблемы будут очень оценены.
Подробнее здесь:
https://stackoverflow.com/questions/794 ... e-extensio
1739953625
Anonymous
В настоящее время я работаю над реализацией уведомлений о Push в моем приложении для iOS, используя расширение службы уведомлений, но изображение не отображается в уведомлении. Ниже приведены подробности моей реализации: < /p> [code]import UIKit import Flutter import GoogleMaps import Firebase import FirebaseMessaging @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { FirebaseApp.configure() UNUserNotificationCenter.current().delegate = self if #available(iOS 12.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in print("Permission granted: \(granted)") } } application.registerForRemoteNotifications() GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } < /code> natificationservice: < /p> import UserNotifications import os.log class NotificationService: UNNotificationServiceExtension { private var contentHandler: ((UNNotificationContent) -> Void)? private var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { os_log("Entered didReceive method.", log: .default, type: .info) self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) defer { os_log("Completing content handler.", log: .default, type: .info) contentHandler(bestAttemptContent ?? request.content) } guard let attachment = request.attachment else { os_log("Attachment not found.", log: .default, type: .error) return } os_log("Attachment found: %@", log: .default, type: .info, attachment.identifier) bestAttemptContent?.attachments = [attachment] } override func serviceExtensionTimeWillExpire() { os_log("Service extension time will expire.", log: .default, type: .info) if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } extension UNNotificationRequest { var attachment: UNNotificationAttachment? { os_log("Attempting to fetch image URL from payload.", log: .default, type: .info) guard let attachmentURL = content.userInfo["image_url"] as? String else { os_log("Image URL not found in payload.", log: .default, type: .error) return nil } let encodedURLString = attachmentURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) os_log("Original URL: %@", log: .default, type: .info, attachmentURL) os_log("Encoded URL: %@", log: .default, type: .info, encodedURLString ?? "nil") guard let encodedURL = URL(string: encodedURLString ?? ""), let imageData = try? Data(contentsOf: encodedURL) else { os_log("Failed to create URL from encoded string.", log: .default, type: .error) return nil } os_log("Creating attachment with fetched image data.", log: .default, type: .info) return try? UNNotificationAttachment(data: imageData, options: nil) } } extension UNNotificationAttachment { convenience init(data: Data, options: [NSObject: AnyObject]?) throws { let fileManager = FileManager.default let temporaryFolderName = ProcessInfo.processInfo.globallyUniqueString let temporaryFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(temporaryFolderName, isDirectory: true) try fileManager.createDirectory(at: temporaryFolderURL, withIntermediateDirectories: true, attributes: nil) let imageFileIdentifier = UUID().uuidString + ".jpg" let fileURL = temporaryFolderURL.appendingPathComponent(imageFileIdentifier) try data.write(to: fileURL) os_log("Image data written to file: %@", log: .default, type: .info, fileURL.absoluteString) try self.init(identifier: imageFileIdentifier, url: fileURL, options: options) } } < /code> info.plist: NSAppTransportSecurity NSAllowsArbitraryLoads [/code] Playload имеет mitable-content: 1 , Несмотря на приведенные выше конфигурации, изображение не отображается в уведомлении. Я гарантировал, что URL -адрес изображения доступен и правильно отформатирован. Любая помощь или понимание решения этой проблемы будут очень оценены. Подробнее здесь: [url]https://stackoverflow.com/questions/79450329/image-push-notification-not-displaying-in-ios-with-notification-service-extensio[/url]