Skip to content

Commit

Permalink
Chat(notifications): initial logic
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasfroeller committed Jun 12, 2024
1 parent 68f0435 commit dd81b39
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions core/features/Chat/ViewModel/ChatViewModel.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Foundation
import SwiftUI
import UserNotifications

class ChatViewModel: ObservableObject {
@AppStorage("USER_KEY") var email: String = ""
Expand All @@ -17,6 +18,14 @@ class ChatViewModel: ObservableObject {
if Environment.isDebug { print("updating chat messages...") }
self.updateChatWithNewMessage(message, monitor_hash: monitorId)
}

UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound]) { granted, error in
if let error = error {
print("Error requesting notification permission: \(error.localizedDescription)")
} else if granted {
print("Notification permission granted")
}
}
}

public func connect() {
Expand Down Expand Up @@ -73,6 +82,23 @@ class ChatViewModel: ObservableObject {
updatedChats[chatIndex] = updatedChat

chatsModel.setChats(chats: updatedChats)

if message.email != email {
let content = UNMutableNotificationContent()
content.title = "New Message from \(String(describing: message.email)) in \(String(describing: updatedChat.title))"
content.body = message.text ?? "no message body..."
content.sound = UNNotificationSound.default

let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error creating notification: \(error.localizedDescription)")
} else {
print("Notification created successfully")
}
}
}

// if (Environment.isDebug) { print("chat messages updated") }
// if (Environment.isDebug) { print("chat count", chatsModel.chats.endIndex) }
}
Expand Down

0 comments on commit dd81b39

Please sign in to comment.