0

Cuando le doy tap a la notificación para expander, me aparece arriba lo que es el titulo y el mensaje, en la parte de abajo la imagen. Lo que estoy buscando es cambiar ese orden, que la imagen este arriba y el body abajo.

  • Aclaro que esto lo estoy haciendo todo por fuera del ViewController, desde el AppDelegade se esta utilizando firebase para obtener esta data y así crear la notificación localmente en otra clase.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
      registerDataNotification(didReceiveRemoteNotification: userInfo)
      completionHandler(UIBackgroundFetchResult.newData)
    }
  • Esto es lo que estoy obteniendo por ahora:

introducir la descripción de la imagen aquí

  • El objetivo es llegar a esto:

introducir la descripción de la imagen aquí

  • El código que tengo es el siguiente:
fileprivate func triggerNotification(image: String?, id: String?, title: String?, body: String?, visualizationMode: VisualizationMode){
        let content = UNMutableNotificationContent()
        content.title = title!
        content.body = body!
        content.badge = 2
        content.sound = UNNotificationSound.default()
        if image == nil || image?.count==0 {
            notifyUser(id, content)
        }else{
            do {
                let fileUrl = URL(string: image!)
                let data = try Data(contentsOf: fileUrl!)
                var uIImage = UIImage(data: data)
                uIImage = visualizationMode.rawValue.contains("Text") ? uIImage!.resized(toWidth: uIImage!.size.width) : uIImage
                if let attachment = UNNotificationAttachment.create(identifier: id!, image: uIImage!, options: nil) {
                    content.attachments = [attachment]
                }
                notifyUser(id, content)
            }
            catch{
                print(error.localizedDescription)
                notifyUser(id, content)
            }
        }
    }
fileprivate func notifyUser(_ id: String?, _ content: UNMutableNotificationContent) {
        let masivNotification = MasivNotification(didReceiveRemoteNotification: jsonCleanUserInfo)
        eventService.registerEvent(masivNotification: masivNotification, masivEventType: MasivEventType.Received, token: token,
                                           country: country, masivPlatform: masivPlatform.Ios, externalAppId: externalAppId)
        let request = UNNotificationRequest.init(identifier: (id)!, content: content, trigger: nil)
        UNUserNotificationCenter.current().add(request)
    }
extension UNNotificationAttachment {

    static func create(identifier: String, image: UIImage, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
        let fileManager = FileManager.default
        let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
        let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)
        do {
            try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)
            let imageFileIdentifier = identifier+".png"
            let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier)
            let imageData = UIImagePNGRepresentation(image)
            try imageData?.write(to: fileURL)
            let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL, options: options)
            return imageAttachment
        } catch {
            print("error " + error.localizedDescription)
        }
        return nil
    }
}

1 respuesta 1

0

Debes crear un nuevo target en tu proyecto:

introducir la descripción de la imagen aquí

y seleccionar Notification Content Extension:

introducir la descripción de la imagen aquí

Esto te va a crear un storyboard con un ViewController en donde vas a tener el diseño:

introducir la descripción de la imagen aquí

Agregas los elementos necesarios al ViewController:

@IBOutlet weak var imageNotification: UIImageView!

@IBOutlet weak var titleNotification: UILabel!
@IBOutlet weak var subtitleNotification: UILabel!

Agregas el siguiente código para leer los datos de la notificación:

func didReceive(_ notification: UNNotification) {
        //Validas si hay una imagen como adjunto y le agregas al imageView
        if let attachment = notification.request.content.attachments.first {
            if attachment.url.startAccessingSecurityScopedResource() {
                let data = NSData(contentsOfFile: attachment.url.path)
                self.imageNotification.image = UIImage(data: data! as Data)
                attachment.url.stopAccessingSecurityScopedResource()
            }
        }
        //Validas que los campos recibidos existan
        if let validTitle = notification.request.content.userInfo["title"] as? String,
           let validDescription = notification.request.content.userInfo["description"] as? String {
            self.titleNotification.text = validTitle
            self.subtitleNotification.text = validDescription
        }
    }

Debes modificar el .plist de la extensión agregando los siguientes valores:

introducir la descripción de la imagen aquí

Debes agregar un nuevo valor en el contenido de la notificación que es el categoryIdentifier y debe coincidir con el del archivo .plist.

let notificationContent = UNMutableNotificationContent()
    notificationContent.title = "Mi Notificación"
    notificationContent.categoryIdentifier = "mi_notificacion"

Configuramos la imagen para la notificación:

let attachement = try! UNNotificationAttachment(identifier: "image",
                       url: Bundle.main.url(forResource: "fondo", withExtension: "png")!, options: nil)

Ahora agregamos la información de la notificación que es la que va a recibir la extensión creada:

notificationContent.attachments = [attachement]
notificationContent.userInfo = [
        "title" : "Este es el título",
        "description" : "Esta es el subtitulo"
    ]

Por último agregamos el tiempo para mostrar la notificación y agregamos el contenido creado anteriormente:

let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 1.0, repeats: false)
let notificationRequest = UNNotificationRequest(identifier: "mi_notificacion", content: notificationContent, trigger: notificationTrigger)
let notificationCategory = UNNotificationCategory(identifier: "mi_notificacion",actions: [],intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "",options: .customDismissAction)

UNUserNotificationCenter.current().setNotificationCategories([notificationCategory])
        
        UNUserNotificationCenter.current().add(notificationRequest) { (error) in
            if let error = error {
                print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
            }
        }

Ejecutas en el simulador y obtienes lo siguiente al expandir la notificación:

introducir la descripción de la imagen aquí

1
  • todo funciono ok. De nuevo ty eres un crack.
    – David Leon
    el 3 oct. 2021 a las 19:04

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.