SlideShare uma empresa Scribd logo
1 de 102
Baixar para ler offline
Notificações no iOS 10
Rodrigo 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 2016
Principais 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 UserNotifications
Registrando, 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ção
1. Definir conteúdo
Enviando uma notificação
1. 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ção
1. 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ção
1. 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ção
2. Configurar Trigger
Enviando uma notificação
2. Configurar Trigger
// Time Interval Trigger
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
Enviando uma notificação
2. 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ção
2. 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ção
3. Criar e submeter Notification Request
Enviando uma notificação
3. Criar e submeter Notification Request
// Create Request
let request = UNNotificationRequest(identifier: "notification-request1",
content: content,
trigger: trigger)
Enviando uma notificação
3. 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ção
3. 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ção
3. 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á aberto
func 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á aberto
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent
notification: UNNotification, withCompletionHandler completionHandler:
@escaping (UNNotificationPresentationOptions) -> Void) {
}
// Quando usuário clica na notificação
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive
response: UNNotificationResponse, withCompletionHandler completionHandler:
@escaping () -> Void) {
}
Recebendo a notificação
Notification Content Extension
Criando 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 Extension
1. Criar um novo target Content Extension
Notification Content Extension
1. Criar um novo target Content Extension
Notification Content Extension
1. Criar um novo target Content Extension
Notification Content Extension
1. Criar um novo target Content Extension
Notification Content Extension
2. Adicionar chaves no Info.plist
Notification Content Extension
2. Adicionar chaves no Info.plist
Notification Content Extension
3. Implementar a NotificationViewController
Notification Content Extension
3. Implementar a NotificationViewController
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet var label: UILabel?
func didReceive(_ notification: UNNotification) {
}
}
Notification Content Extension
3. 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 Extension
Tratando 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 Extension
1. Criar um novo target Service Extension
Notification Service Extension
1. Criar um novo target Service Extension
Notification Service Extension
1. Criar um novo target Service Extension
Notification Service Extension
1. Criar um novo target Service Extension
Notification Service Extension
2. Implementar a classe NotificationService
Notification Service Extension
2. Implementar a classe NotificationService
class NotificationService: UNNotificationServiceExtension {
}
Notification Service Extension
2. Implementar a classe NotificationService
class NotificationService: UNNotificationServiceExtension {
}
override func didReceive(_ request: UNNotificationRequest, withContentHandler
contentHandler: @escaping (UNNotificationContent) -> Void) {
}
Notification Service Extension
2. Implementar a classe NotificationService
class NotificationService: UNNotificationServiceExtension {
}
override func didReceive(_ request: UNNotificationRequest, withContentHandler
contentHandler: @escaping (UNNotificationContent) -> Void) {
}
override func serviceExtensionTimeWillExpire() {
}
Notification Service Extension
2. 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 Extension
2. 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 Extension
2. 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
rborges.soares@gmail.com
@rdgborges
lindekin.com/in/rdgborges
medium.com/@rdgborges
🤓
📧
🐦
💻
📝

Mais conteúdo relacionado

Destaque

iOS 10 - What you need to know
iOS 10 - What you need to knowiOS 10 - What you need to know
iOS 10 - What you need to knowThe App Business
 
The New Features of the iPhone 7
The New Features of the iPhone 7The New Features of the iPhone 7
The New Features of the iPhone 7UniMaven
 
What is so special about iphone 7?
What is so special about iphone 7?What is so special about iphone 7?
What is so special about iphone 7?lee shin
 

Destaque (6)

iOS 10 - What you need to know
iOS 10 - What you need to knowiOS 10 - What you need to know
iOS 10 - What you need to know
 
Hello, WWDC 2016!
Hello, WWDC 2016!Hello, WWDC 2016!
Hello, WWDC 2016!
 
The New Features of the iPhone 7
The New Features of the iPhone 7The New Features of the iPhone 7
The New Features of the iPhone 7
 
Presentation on iOS
Presentation on iOSPresentation on iOS
Presentation on iOS
 
Seminar on x-max technology ppt
Seminar on x-max technology  pptSeminar on x-max technology  ppt
Seminar on x-max technology ppt
 
What is so special about iphone 7?
What is so special about iphone 7?What is so special about iphone 7?
What is so special about iphone 7?
 

Semelhante a Notificações no iOS 10 - Guia completo

Android app communication
Android app communicationAndroid app communication
Android app communicationEloi Júnior
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...tdc-globalcode
 
Aula 15 e 16 - Navegação - Activities e Fragments.pptx.pdf
Aula 15 e 16 - Navegação - Activities e Fragments.pptx.pdfAula 15 e 16 - Navegação - Activities e Fragments.pptx.pdf
Aula 15 e 16 - Navegação - Activities e Fragments.pptx.pdfnosbisantos
 
Audit¢rio 11 desenvolvimento de um app ao vivo - pablo moretti
Audit¢rio 11   desenvolvimento de um app ao vivo - pablo morettiAudit¢rio 11   desenvolvimento de um app ao vivo - pablo moretti
Audit¢rio 11 desenvolvimento de um app ao vivo - pablo morettifsolari
 
TDC2016SP - Trilha Mobile
TDC2016SP - Trilha MobileTDC2016SP - Trilha Mobile
TDC2016SP - Trilha Mobiletdc-globalcode
 
Desenvolvendo aplicações Adobe AIR para Android
Desenvolvendo aplicações Adobe AIR para AndroidDesenvolvendo aplicações Adobe AIR para Android
Desenvolvendo aplicações Adobe AIR para AndroidEric Cavalcanti
 
Congresso TI 2015: Introducao ao Phonegap (Cordova)
Congresso TI 2015: Introducao ao Phonegap (Cordova)Congresso TI 2015: Introducao ao Phonegap (Cordova)
Congresso TI 2015: Introducao ao Phonegap (Cordova)Loiane Groner
 
Aplicando CDI em aplicações Java
Aplicando CDI em aplicações JavaAplicando CDI em aplicações Java
Aplicando CDI em aplicações JavaMichel Graciano
 
Seminário sd android_exemplos
Seminário sd android_exemplosSeminário sd android_exemplos
Seminário sd android_exemplosCalvin Rodrigues
 
TDC2016 Boas Práticas SQL em Banco Relacional para Desenvolvedores
TDC2016 Boas Práticas SQL em Banco Relacional para DesenvolvedoresTDC2016 Boas Práticas SQL em Banco Relacional para Desenvolvedores
TDC2016 Boas Práticas SQL em Banco Relacional para DesenvolvedoresFernando Franquini
 
Ingressos no pulso - Levando festas e ingressos para o Apple Watch
Ingressos no pulso - Levando festas e ingressos para o Apple WatchIngressos no pulso - Levando festas e ingressos para o Apple Watch
Ingressos no pulso - Levando festas e ingressos para o Apple WatchRodrigo Borges
 
google maps api - v1
 google maps api - v1 google maps api - v1
google maps api - v1Lucas Aquiles
 
Live Tiles e Background Executions - TDC SP 2015
Live Tiles e Background Executions - TDC SP 2015Live Tiles e Background Executions - TDC SP 2015
Live Tiles e Background Executions - TDC SP 2015talkitbr
 
Técnicas de Refactoring
Técnicas de RefactoringTécnicas de Refactoring
Técnicas de RefactoringRodrigo Branas
 

Semelhante a Notificações no iOS 10 - Guia completo (20)

Android app communication
Android app communicationAndroid app communication
Android app communication
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
 
Aula 15 e 16 - Navegação - Activities e Fragments.pptx.pdf
Aula 15 e 16 - Navegação - Activities e Fragments.pptx.pdfAula 15 e 16 - Navegação - Activities e Fragments.pptx.pdf
Aula 15 e 16 - Navegação - Activities e Fragments.pptx.pdf
 
Audit¢rio 11 desenvolvimento de um app ao vivo - pablo moretti
Audit¢rio 11   desenvolvimento de um app ao vivo - pablo morettiAudit¢rio 11   desenvolvimento de um app ao vivo - pablo moretti
Audit¢rio 11 desenvolvimento de um app ao vivo - pablo moretti
 
Google Play Services Rocks!!!
Google Play Services Rocks!!!Google Play Services Rocks!!!
Google Play Services Rocks!!!
 
Apresentação Phonegap
Apresentação PhonegapApresentação Phonegap
Apresentação Phonegap
 
TDC2016SP - Trilha Mobile
TDC2016SP - Trilha MobileTDC2016SP - Trilha Mobile
TDC2016SP - Trilha Mobile
 
Android wear
Android wearAndroid wear
Android wear
 
Android Wear
Android WearAndroid Wear
Android Wear
 
Desenvolvendo aplicações Adobe AIR para Android
Desenvolvendo aplicações Adobe AIR para AndroidDesenvolvendo aplicações Adobe AIR para Android
Desenvolvendo aplicações Adobe AIR para Android
 
Congresso TI 2015: Introducao ao Phonegap (Cordova)
Congresso TI 2015: Introducao ao Phonegap (Cordova)Congresso TI 2015: Introducao ao Phonegap (Cordova)
Congresso TI 2015: Introducao ao Phonegap (Cordova)
 
Aplicando CDI em aplicações Java
Aplicando CDI em aplicações JavaAplicando CDI em aplicações Java
Aplicando CDI em aplicações Java
 
Seminário sd android_exemplos
Seminário sd android_exemplosSeminário sd android_exemplos
Seminário sd android_exemplos
 
Mobile agent
Mobile agentMobile agent
Mobile agent
 
TDC2016 Boas Práticas SQL em Banco Relacional para Desenvolvedores
TDC2016 Boas Práticas SQL em Banco Relacional para DesenvolvedoresTDC2016 Boas Práticas SQL em Banco Relacional para Desenvolvedores
TDC2016 Boas Práticas SQL em Banco Relacional para Desenvolvedores
 
Ingressos no pulso - Levando festas e ingressos para o Apple Watch
Ingressos no pulso - Levando festas e ingressos para o Apple WatchIngressos no pulso - Levando festas e ingressos para o Apple Watch
Ingressos no pulso - Levando festas e ingressos para o Apple Watch
 
Chromecast na Qcon RJ
Chromecast na Qcon RJChromecast na Qcon RJ
Chromecast na Qcon RJ
 
google maps api - v1
 google maps api - v1 google maps api - v1
google maps api - v1
 
Live Tiles e Background Executions - TDC SP 2015
Live Tiles e Background Executions - TDC SP 2015Live Tiles e Background Executions - TDC SP 2015
Live Tiles e Background Executions - TDC SP 2015
 
Técnicas de Refactoring
Técnicas de RefactoringTécnicas de Refactoring
Técnicas de Refactoring
 

Notificações no iOS 10 - Guia completo

  • 1. Notificações no iOS 10 Rodrigo Borges Soares iOS Developer @ VivaReal
  • 2. Eu 🤓 • Manauara • iOS Developer @ VivaReal 🏡 • Mobile & Co-Founder @ Meatless 🌱🚲
  • 3. Eu 🤓 • Manauara • iOS Developer @ VivaReal 🏡 • Mobile & Co-Founder @ Meatless 🌱🚲
  • 4. Eu 🤓 • Manauara • iOS Developer @ VivaReal 🏡 • Mobile & Co-Founder @ Meatless 🌱🚲
  • 5. Resumo • Novidades da WWDC 2016 • O basicão do UserNotifications Framework • Registrar, Configurações, Triggers, Enviar e Receber • Notification Content Extension • Notification Service Extension
  • 6. Novidades da WWDC 2016 Principais novidades de Notificações lançadas na WWDC 2016
  • 7. Notificações no iOS 10 • Nova interface • Título, subtítulo, corpo e imagem • UserNotifications Framework • Novos Triggers • Time Interval, Calendar, Location
  • 8. Notificações no iOS 10 • Nova interface • Título, subtítulo, corpo e imagem • UserNotifications Framework • Novos Triggers • Time Interval, Calendar, Location
  • 9. Unificação das APIs Local Notifications & Remote Notifications
  • 10. Unificação das APIs Local Notifications & Remote Notifications
  • 11. Unificação das APIs Local Notifications & Remote Notifications Notifications 👏
  • 12. Callbacks fora do AppDelegate didReceiveRemoteNotifications didReceiveLocalNotifications no AppDelegate
  • 13. Callbacks fora do AppDelegate didReceiveRemoteNotifications didReceiveLocalNotifications no AppDelegate
  • 14. Callbacks fora do AppDelegate didReceiveRemoteNotifications didReceiveLocalNotifications no AppDelegate UNUserNotificationCenter Delegate 🎉
  • 16. Notification Extensions • Content Extension • Permite criar interfaces expandidas para as notificações
  • 17. 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
  • 18. O basicão da UserNotifications Registrando, configurando e enviando uma notificação
  • 19. Registrando UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { granted, error in if granted { print("Notification authorization granted!") } }
  • 20. Registrando UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { granted, error in if granted { print("Notification authorization granted!") } }
  • 21. Registrando UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { granted, error in if granted { print("Notification authorization granted!") } }
  • 22. Registrando UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { granted, error in if granted { print("Notification authorization granted!") } }
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. Enviando uma notificação 1. Definir conteúdo 2. Configurar Trigger 3. Criar e submeter Notification Request
  • 28. Enviando uma notificação 1. Definir conteúdo
  • 29. Enviando uma notificação 1. 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."
  • 30. Enviando uma notificação 1. 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] }
  • 31. Enviando uma notificação 1. 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] }
  • 32. Enviando uma notificação 2. Configurar Trigger
  • 33. Enviando uma notificação 2. Configurar Trigger // Time Interval Trigger let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
  • 34. Enviando uma notificação 2. 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)
  • 35. Enviando uma notificação 2. 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)
  • 36. Enviando uma notificação 3. Criar e submeter Notification Request
  • 37. Enviando uma notificação 3. Criar e submeter Notification Request // Create Request let request = UNNotificationRequest(identifier: "notification-request1", content: content, trigger: trigger)
  • 38. Enviando uma notificação 3. 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 }
  • 39. Enviando uma notificação 3. 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 }
  • 40. Enviando uma notificação 3. 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
  • 43. extension ViewController: UNUserNotificationCenterDelegate { } // Quando a notificação chega e o app está aberto func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { } Recebendo a notificação
  • 44. extension ViewController: UNUserNotificationCenterDelegate { } // Quando a notificação chega e o app está aberto func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { } // Quando usuário clica na notificação func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { } Recebendo a notificação
  • 45. Notification Content Extension Criando interfaces expandidas para as notificações
  • 46. 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
  • 47. Notification Content Extension 1. Criar um novo target Content Extension 2. Adicionar chaves no Info.plist 3. Implementar a NotificationViewController
  • 48. Notification Content Extension 1. Criar um novo target Content Extension
  • 49. Notification Content Extension 1. Criar um novo target Content Extension
  • 50. Notification Content Extension 1. Criar um novo target Content Extension
  • 51. Notification Content Extension 1. Criar um novo target Content Extension
  • 52. Notification Content Extension 2. Adicionar chaves no Info.plist
  • 53. Notification Content Extension 2. Adicionar chaves no Info.plist
  • 54. Notification Content Extension 3. Implementar a NotificationViewController
  • 55. Notification Content Extension 3. Implementar a NotificationViewController class NotificationViewController: UIViewController, UNNotificationContentExtension { @IBOutlet var label: UILabel? func didReceive(_ notification: UNNotification) { } }
  • 56. Notification Content Extension 3. Implementar a NotificationViewController class NotificationViewController: UIViewController, UNNotificationContentExtension { @IBOutlet var label: UILabel? func didReceive(_ notification: UNNotification) { } } self.label?.text = "CocoaheadsConference tá 🔝"
  • 58. Como associar notificação e interface? Criando uma categoria!
  • 59. Como associar notificação e interface? Criando uma categoria!
  • 60. Como associar notificação e interface? let categoryOptions = UNNotificationCategoryOptions(rawValue: 0) Criando uma categoria!
  • 61. 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!
  • 62. 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!
  • 63. 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!
  • 64. 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!
  • 65. Como associar notificação e interface? Associar categoria à notificação
  • 66. 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."
  • 67. 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"
  • 69. Como associar notificação e interface? Categoria
  • 70. Como associar notificação e interface? Categoria Category Identifier
  • 71. Como associar notificação e interface? Categoria Category Identifier
  • 72. Como associar notificação e interface? Notificação Content ExtensionCategoria Category Identifier
  • 73. Como associar notificação e interface? Notificação Content ExtensionCategoria Category Identifier
  • 74. E em push notifications?
  • 75. E em push notifications? Categoria no payload!
  • 76. E em push notifications? Categoria no payload!
  • 77. E em push notifications? { aps: { alert: { ... }, category: 'cocoaheadsCategory' } } Categoria no payload!
  • 78. Notification Service Extension Tratando notificações remotas antes de serem mostradas pro usuário
  • 79. Notification Service Extension 1. Criar um novo target Service Extension 2. Implementar a classe NotificationService
  • 80. Notification Service Extension 1. Criar um novo target Service Extension
  • 81. Notification Service Extension 1. Criar um novo target Service Extension
  • 82. Notification Service Extension 1. Criar um novo target Service Extension
  • 83. Notification Service Extension 1. Criar um novo target Service Extension
  • 84. Notification Service Extension 2. Implementar a classe NotificationService
  • 85. Notification Service Extension 2. Implementar a classe NotificationService class NotificationService: UNNotificationServiceExtension { }
  • 86. Notification Service Extension 2. Implementar a classe NotificationService class NotificationService: UNNotificationServiceExtension { } override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { }
  • 87. Notification Service Extension 2. Implementar a classe NotificationService class NotificationService: UNNotificationServiceExtension { } override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { } override func serviceExtensionTimeWillExpire() { }
  • 88. Notification Service Extension 2. 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)
  • 89. Notification Service Extension 2. 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"
  • 90. Notification Service Extension 2. 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"
  • 91. Como app sabe que precisa rodar o Service?
  • 92. Como app sabe que precisa rodar o Service? Payload de novo!
  • 93. Como app sabe que precisa rodar o Service? Payload de novo!
  • 94. Como app sabe que precisa rodar o Service? { aps: { alert: { ... }, mutable-content: 1 } } Payload de novo!
  • 96. 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
  • 99. • 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…
  • 100. • 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…
  • 101. 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
  • 102. That’s all folks! ✌ Rodrigo Borges rborges.soares@gmail.com @rdgborges lindekin.com/in/rdgborges medium.com/@rdgborges 🤓 📧 🐦 💻 📝