-
Notifications
You must be signed in to change notification settings - Fork 0
/
Notification.swift
73 lines (56 loc) · 2.83 KB
/
Notification.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import SwiftUI
import UserNotifications
import UserNotifications
class NotificationManager: ObservableObject {
static let shared = NotificationManager()
func requestPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
print("Erro ao solicitar permissão: \(error.localizedDescription)")
}
}
}
func scheduleNotification(for remedio: Remedio) {
let content = UNMutableNotificationContent()
content.title = "Hora de tomar \(remedio.nome)"
content.body = "Tome \(remedio.quantidade) \(remedio.unidade)"
content.sound = .default
// Adicionar informações extras no userInfo
content.userInfo = [
"id": remedio.id,
"nome": remedio.nome,
"quantidade": remedio.quantidade,
"unidade": remedio.unidade,
"hora": remedio.hora
]
// Convertendo a string "hh:mm" para DateComponents
let horaComponents = remedio.hora.split(separator: ":").compactMap { Int($0) }
guard horaComponents.count == 2 else { return }
var triggerDate = DateComponents()
triggerDate.hour = horaComponents[0]
triggerDate.minute = horaComponents[1]
let requestIdentifier = "\(remedio.id)_\(remedio.id)" // Usando id para o identificador da notificação
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)
let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Erro ao agendar notificação: \(error.localizedDescription)")
}
}
}
}
import UIKit
import SwiftUI
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
@ObservedObject var notificationManager = NotificationManager.shared
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
// Função chamada quando a notificação é recebida com o app em foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
// Exibir a tela ScreenIdoso
NotificationCenter.default.post(name: NSNotification.Name("ShowScreenIdoso"), object: notification.request.content)
}
}