Swift Pills

Dosis rápidas de conocimiento sobre Swift y desarrollo en ecosistemas Apple

¿Sabías que puedes permitir a los usuarios responder directamente desde una notificación sin abrir tu app?

📝 Las acciones de entrada de texto en notificaciones iOS son una de las funciones más poderosas del framework UserNotifications. Permiten que los usuarios escriban respuestas, proporcionen información o envíen mensajes cortos sin interrumpir su flujo de trabajo.

🎯 La clase UNTextInputNotificationAction representa estas acciones especiales. Aquí un ejemplo creando una acción para que un usuario añada una tarea rápida:

let addTaskAction = UNTextInputNotificationAction(
    identifier: "addQuickTask",
    title: "Nueva tarea",
    options: [],
    textInputButtonTitle: "Guardar",
    textInputPlaceholder: "Escribe tu tarea..."
)

🏗️ Estas acciones deben agruparse en categorías. Puedes combinar acciones de entrada de texto con botones normales:

let postponeAction = UNNotificationAction(
    identifier: "postpone",
    title: "Posponer",
    options: []
)

let category = UNNotificationCategory(
    identifier: "dailyReminder",
    actions: [addTaskAction, postponeAction],
    intentIdentifiers: [],
    options: .customDismissAction
)

📲 Para que funcione, registra las categorías al iniciar la app. Una buena práctica es encapsular esta lógica en una clase NotificationService:

class NotificationService: NSObject, UNUserNotificationCenterDelegate {
    func setup() {
        UNUserNotificationCenter.current().delegate = self
        registerCategories()
    }
    
    private func registerCategories() {
        // Crear acciones y categorías
        UNUserNotificationCenter.current()
            .setNotificationCategories([category])
    }
}

💬 Cuando el usuario responde, capturas el texto mediante UNTextInputNotificationResponse:

func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
) {
    switch response.actionIdentifier {
    case "addQuickTask":
        if let textResponse = response as? UNTextInputNotificationResponse {
            let taskTitle = textResponse.userText
            // Procesar la respuesta del usuario
            TaskManager.shared.addTask(taskTitle)
        }
    default:
        break
    }
    completionHandler()
}

⚡ El manejo ocurre en segundo plano sin abrir la app. Puedes procesar el texto, enviarlo a tu servidor o actualizar la base de datos mientras el usuario continúa con otras tareas.

🔄 Los casos de uso son múltiples: apps de mensajería con respuestas rápidas, apps de productividad capturando notas, apps de fitness registrando datos, o cualquier escenario donde una entrada breve de texto tenga sentido.

🎨 En SwiftUI, integras el servicio fácilmente en tu App:

@main
struct ProductivityApp: App {
    private let notificationService = NotificationService()
    
    init() {
        notificationService.setup()
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

📱 Al enviar la notificación, solo asignas el categoryIdentifier correspondiente:

let content = UNMutableNotificationContent()
content.title = "Planifica tu día"
content.body = "¿Tienes algo pendiente para hoy?"
content.categoryIdentifier = "dailyReminder"

⚠️ Es importante llamar a la función de completado después de procesar la respuesta. Si requieres operaciones de red, considera usar tareas en segundo plano para garantizar que se complete incluso si la app se suspende.

🛠️ Esta funcionalidad está disponible desde iOS 10 y funciona tanto con notificaciones locales como remotas. El sistema se encarga de mostrar el teclado, gestionar el campo de texto y entregar la respuesta a tu app.

👨‍💻 Las acciones de entrada de texto transforman notificaciones pasivas en experiencias interactivas que respetan la experiencia de usuario. ¿Ya las estás usando en tus proyectos?

Posted in

Deja un comentario