102
Notificações no iOS 10 Rodrigo Borges Soares iOS Developer @ VivaReal

Notificações no iOS 10

Embed Size (px)

Citation preview

Notificações no iOS 10Rodrigo Borges Soares

iOS Developer @ VivaReal

Eu 🤓

• Manauara

• iOS Developer @ VivaReal 🏡

• Mobile & Co-Founder @ Meatless 🌱🚲

Eu 🤓

• Manauara

• iOS Developer @ VivaReal 🏡

• Mobile & Co-Founder @ Meatless 🌱🚲

Eu 🤓

• Manauara

• iOS Developer @ VivaReal 🏡

• Mobile & Co-Founder @ Meatless 🌱🚲

Resumo• Novidades da WWDC 2016

• O basicão do UserNotifications Framework

• Registrar, Configurações, Triggers, Enviar e Receber

• Notification Content Extension

• Notification Service Extension

Novidades da WWDC 2016Principais novidades de Notificações lançadas na WWDC 2016

Notificações no iOS 10

• Nova interface

• Título, subtítulo, corpo e imagem

• UserNotifications Framework

• Novos Triggers

• Time Interval, Calendar, Location

Notificações no iOS 10

• Nova interface

• Título, subtítulo, corpo e imagem

• UserNotifications Framework

• Novos Triggers

• Time Interval, Calendar, Location

Unificação das APIs

Local Notifications

&

Remote Notifications

Unificação das APIs

Local Notifications

&

Remote Notifications

Unificação das APIs

Local Notifications

&

Remote Notifications

Notifications 👏

Callbacks fora do AppDelegate

didReceiveRemoteNotifications

didReceiveLocalNotifications

no AppDelegate

Callbacks fora do AppDelegate

didReceiveRemoteNotifications

didReceiveLocalNotifications

no AppDelegate

Callbacks fora do AppDelegate

didReceiveRemoteNotifications

didReceiveLocalNotifications

no AppDelegate

UNUserNotificationCenter

Delegate 🎉

Notification Extensions

Notification Extensions

• Content Extension

• Permite criar interfaces expandidas para as notificações

Notification Extensions

• Service Extension

• Permite implementarmos o tratamento de uma notificação remota antes de ser mostrada para o usuário (Ex: baixar novos dados e imagem)

• Content Extension

• Permite criar interfaces expandidas para as notificações

O basicão da UserNotificationsRegistrando, configurando e enviando uma notificação

Registrando

UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { granted, error in if granted { print("Notification authorization granted!") }

}

Registrando

UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { granted, error in if granted { print("Notification authorization granted!") }

}

Registrando

UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { granted, error in if granted { print("Notification authorization granted!") }

}

Registrando

UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { granted, error in if granted { print("Notification authorization granted!") }

}

UNUserNotificationCenter.current().getNotificationSettings { settings in if settings.authorizationStatus == .authorized { print("Authorized 👍") } else if settings.authorizationStatus == .denied { print("Denied 🚫") } else { print("Not determined 🤔") } }

Consultando configurações

UNUserNotificationCenter.current().getNotificationSettings { settings in if settings.authorizationStatus == .authorized { print("Authorized 👍") } else if settings.authorizationStatus == .denied { print("Denied 🚫") } else { print("Not determined 🤔") } }

Consultando configurações

UNUserNotificationCenter.current().getNotificationSettings { settings in if settings.authorizationStatus == .authorized { print("Authorized 👍") } else if settings.authorizationStatus == .denied { print("Denied 🚫") } else { print("Not determined 🤔") } }

Consultando configurações

UNUserNotificationCenter.current().getNotificationSettings { settings in if settings.authorizationStatus == .authorized { print("Authorized 👍") } else if settings.authorizationStatus == .denied { print("Denied 🚫") } else { print("Not determined 🤔") } }

Consultando configurações

Enviando uma notificação

1. Definir conteúdo

2. Configurar Trigger

3. Criar e submeter Notification Request

Enviando uma notificação1. Definir conteúdo

Enviando uma notificação1. Definir conteúdo

let content = UNMutableNotificationContent() content.title = “Notificações no iOS 10" content.subtitle = "Rodrigo Borges" content.body = "Nessa palestra vamos falar sobre as novas notificações do iOS 10, lançadas na WWDC 2016."

Enviando uma notificação1. Definir conteúdo

let content = UNMutableNotificationContent() content.title = “Notificações no iOS 10" content.subtitle = "Rodrigo Borges" content.body = "Nessa palestra vamos falar sobre as novas notificações do iOS 10, lançadas na WWDC 2016."

let attachment = try? UNNotificationAttachment(identifier: "notification-image", url: imageURL, options: [:]) if let attachment = attachment { content.attachments = [attachment] }

Enviando uma notificação1. Definir conteúdo

let content = UNMutableNotificationContent() content.title = “Notificações no iOS 10" content.subtitle = "Rodrigo Borges" content.body = "Nessa palestra vamos falar sobre as novas notificações do iOS 10, lançadas na WWDC 2016."

let attachment = try? UNNotificationAttachment(identifier: "notification-image", url: imageURL, options: [:]) if let attachment = attachment { content.attachments = [attachment] }

Enviando uma notificação2. Configurar Trigger

Enviando uma notificação2. Configurar Trigger

// Time Interval Trigger let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

Enviando uma notificação2. Configurar Trigger

// Time Interval Trigger let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

// Calendar Trigger var date = DateComponents() date.day = 25 date.month = 10 date.hour = 19 let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)

Enviando uma notificação2. Configurar Trigger

// Location Trigger let center = CLLocationCoordinate2DMake(-23.524192, -46.760732) let region = CLCircularRegion.init(center: center, radius: 500.0, identifier: “mercadolivre”)

region.notifyOnEntry = true region.notifyOnExit = true

let trigger = UNLocationNotificationTrigger(region: region, repeats: false)

Enviando uma notificação3. Criar e submeter Notification Request

Enviando uma notificação3. Criar e submeter Notification Request

// Create Request let request = UNNotificationRequest(identifier: "notification-request1",

content: content, trigger: trigger)

Enviando uma notificação3. Criar e submeter Notification Request

// Create Request let request = UNNotificationRequest(identifier: "notification-request1",

content: content, trigger: trigger)

// Post request UNUserNotificationCenter.current().add(request) { error in

}

Enviando uma notificação3. Criar e submeter Notification Request

// Create Request let request = UNNotificationRequest(identifier: "notification-request1",

content: content, trigger: trigger)

// Post request UNUserNotificationCenter.current().add(request) { error in

}

Enviando uma notificação3. Criar e submeter Notification Request

// Create Request let request = UNNotificationRequest(identifier: "notification-request1",

content: content, trigger: trigger)

// Post request UNUserNotificationCenter.current().add(request) { error in

}

UNUserNotificationCenter.current().delegate = self

Recebendo a notificação

extension ViewController: UNUserNotificationCenterDelegate {

}

Recebendo a notificação

extension ViewController: UNUserNotificationCenterDelegate {

}

// Quando a notificação chega e o app está abertofunc userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { }

Recebendo a notificação

extension ViewController: UNUserNotificationCenterDelegate {

}

// Quando a notificação chega e o app está abertofunc userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { }

// Quando usuário clica na notificaçãofunc userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { }

Recebendo a notificação

Notification Content ExtensionCriando interfaces expandidas para as notificações

Notification Content Extension

• Interface expandida

• Acessível através do 3D Touch

• Suporte a imagens, áudio e vídeo

• Interface sem interação

• Ações rápidas

Notification Content Extension

1. Criar um novo target Content Extension

2. Adicionar chaves no Info.plist

3. Implementar a NotificationViewController

Notification Content Extension1. Criar um novo target Content Extension

Notification Content Extension1. Criar um novo target Content Extension

Notification Content Extension1. Criar um novo target Content Extension

Notification Content Extension1. Criar um novo target Content Extension

Notification Content Extension2. Adicionar chaves no Info.plist

Notification Content Extension2. Adicionar chaves no Info.plist

Notification Content Extension3. Implementar a NotificationViewController

Notification Content Extension3. Implementar a NotificationViewController

class NotificationViewController: UIViewController, UNNotificationContentExtension {

@IBOutlet var label: UILabel? func didReceive(_ notification: UNNotification) {

}

}

Notification Content Extension3. Implementar a NotificationViewController

class NotificationViewController: UIViewController, UNNotificationContentExtension {

@IBOutlet var label: UILabel? func didReceive(_ notification: UNNotification) {

}

}

self.label?.text = "CocoaheadsConference tá 🔝"

Como associar notificação e interface?

Como associar notificação e interface?

Criando uma categoria!

Como associar notificação e interface?Criando uma categoria!

Como associar notificação e interface?

let categoryOptions = UNNotificationCategoryOptions(rawValue: 0)

Criando uma categoria!

Como associar notificação e interface?

let categoryOptions = UNNotificationCategoryOptions(rawValue: 0)

let confirmAction = UNNotificationAction(identifier: "confirmIdentifier", title: "Confirmar", options: .foreground)let declineAction = UNNotificationAction(identifier: "declineIdentifier", title: "Cancelar", options: [])

Criando uma categoria!

Como associar notificação e interface?

let categoryOptions = UNNotificationCategoryOptions(rawValue: 0)

let confirmAction = UNNotificationAction(identifier: "confirmIdentifier", title: "Confirmar", options: .foreground)let declineAction = UNNotificationAction(identifier: "declineIdentifier", title: "Cancelar", options: [])

let category = UNNotificationCategory(identifier: "cocoaheadsCategory", actions: [confirmAction, declineAction], intentIdentifiers: [], options: categoryOptions)

Criando uma categoria!

Como associar notificação e interface?

let categoryOptions = UNNotificationCategoryOptions(rawValue: 0)

let confirmAction = UNNotificationAction(identifier: "confirmIdentifier", title: "Confirmar", options: .foreground)let declineAction = UNNotificationAction(identifier: "declineIdentifier", title: "Cancelar", options: [])

let category = UNNotificationCategory(identifier: "cocoaheadsCategory", actions: [confirmAction, declineAction], intentIdentifiers: [], options: categoryOptions)

Criando uma categoria!

Como associar notificação e interface?

let categoryOptions = UNNotificationCategoryOptions(rawValue: 0)

let confirmAction = UNNotificationAction(identifier: "confirmIdentifier", title: "Confirmar", options: .foreground)let declineAction = UNNotificationAction(identifier: "declineIdentifier", title: "Cancelar", options: [])

let category = UNNotificationCategory(identifier: "cocoaheadsCategory", actions: [confirmAction, declineAction], intentIdentifiers: [], options: categoryOptions)

UNUserNotificationCenter.current().setNotificationCategories(Set([category]))

Criando uma categoria!

Como associar notificação e interface?Associar categoria à notificação

Como associar notificação e interface?Associar categoria à notificação

let content = UNMutableNotificationContent() content.title = “Notificações no iOS 10" content.subtitle = "Rodrigo Borges" content.body = "Nessa palestra vamos falar sobre as novas notificações do iOS 10, lançadas na WWDC 2016."

Como associar notificação e interface?Associar categoria à notificação

let content = UNMutableNotificationContent() content.title = “Notificações no iOS 10" content.subtitle = "Rodrigo Borges" content.body = "Nessa palestra vamos falar sobre as novas notificações do iOS 10, lançadas na WWDC 2016."

content.categoryIdentifier = "cocoaheadsCategory"

Como associar notificação e interface?

Como associar notificação e interface?

Categoria

Como associar notificação e interface?

Categoria

Category Identifier

Como associar notificação e interface?

Categoria

Category Identifier

Como associar notificação e interface?

Notificação Content ExtensionCategoria

Category Identifier

Como associar notificação e interface?

Notificação Content ExtensionCategoria

Category Identifier

E em push notifications?

E em push notifications?

Categoria no payload!

E em push notifications?Categoria no payload!

E em push notifications?

{ aps: { alert: { ... }, category: 'cocoaheadsCategory' } }

Categoria no payload!

Notification Service ExtensionTratando notificações remotas antes de serem mostradas pro usuário

Notification Service Extension

1. Criar um novo target Service Extension

2. Implementar a classe NotificationService

Notification Service Extension1. Criar um novo target Service Extension

Notification Service Extension1. Criar um novo target Service Extension

Notification Service Extension1. Criar um novo target Service Extension

Notification Service Extension1. Criar um novo target Service Extension

Notification Service Extension2. Implementar a classe NotificationService

Notification Service Extension2. Implementar a classe NotificationService

class NotificationService: UNNotificationServiceExtension {

}

Notification Service Extension2. Implementar a classe NotificationService

class NotificationService: UNNotificationServiceExtension {

}

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

}

Notification Service Extension2. Implementar a classe NotificationService

class NotificationService: UNNotificationServiceExtension {

}

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

}

override func serviceExtensionTimeWillExpire() { }

Notification Service Extension2. Implementar a classe NotificationService

class NotificationService: UNNotificationServiceExtension {

}

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

}

override func serviceExtensionTimeWillExpire() { }

var content = (request.content.mutableCopy() as? UNMutableNotificationContent)

Notification Service Extension2. Implementar a classe NotificationService

class NotificationService: UNNotificationServiceExtension {

}

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

}

override func serviceExtensionTimeWillExpire() { }

var content = (request.content.mutableCopy() as? UNMutableNotificationContent)

content?.body = "I ❤ Storyboards"

Notification Service Extension2. Implementar a classe NotificationService

class NotificationService: UNNotificationServiceExtension {

}

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

}

override func serviceExtensionTimeWillExpire() { }

var content = (request.content.mutableCopy() as? UNMutableNotificationContent)

contentHandler(content)

content?.body = "I ❤ Storyboards"

Como app sabe que precisa rodar o Service?

Como app sabe que precisa rodar o Service?

Payload de novo!

Como app sabe que precisa rodar o Service?Payload de novo!

Como app sabe que precisa rodar o Service?

{ aps: { alert: { ... }, mutable-content: 1 } }

Payload de novo!

UserNotifications in a nutshell

UserNotifications in a nutshell• UNUserNotificationCenter & Delegate FTW!

• Triggers oferecem novas oportunidades

• Conteúdo mais rico: title, subtitle, body, attachments

• Notification Extensions FTW!

• Conteúdos expandidos diferentes para cada categoria de notificação

Stay tuned…

Stay tuned…

• Notificações de recomendação de imóveis

• Dados do imóvel no conteúdo expandido

• Imagem e Localização

• Ações para contatar e favoritar

Stay tuned…

• Service Extension

• Baixar informações do imóvel (n˚ de quartos, venda/aluguel, foto, etc)

• Alterar dados da notificação

• Content Extension

• Implementação da interface expandida

Stay tuned…

1. WWDC 2016: Introduction to Notifications

2. WWDC 2016: Advanced Notifications

3. UserNotifications & UserNotificationsUI Frameworks

4. Pushing the Envelope With iOS 10 Notifications (try! Swift NYC)

Referências

That’s all folks! ✌

Rodrigo Borges [email protected] @rdgborges lindekin.com/in/rdgborges medium.com/@rdgborges

🤓 📧 🐦 💻 📝