Files
bitchat/bitchat/Services/NotificationService.swift
T
jack d6ae19e11e Enable notifications on macOS
- Add macOS support to NotificationService
- Use NSApplication.shared.isActive to check app state on macOS
- Move notification logic outside of iOS-only block in ChatViewModel
- Notifications now work for both mentions and private messages on macOS
- Keep haptic feedback iOS-only as it's not available on macOS
2025-07-03 23:21:29 +02:00

76 lines
2.6 KiB
Swift

import Foundation
import UserNotifications
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
class NotificationService {
static let shared = NotificationService()
private init() {}
func requestAuthorization() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
print("[NOTIFICATIONS] Permission granted")
} else if let error = error {
print("[NOTIFICATIONS] Permission error: \(error)")
}
}
}
func sendLocalNotification(title: String, body: String, identifier: String) {
// Check if app is in foreground
#if os(iOS)
guard UIApplication.shared.applicationState != .active else {
print("[NOTIFICATIONS] App is active/foreground, skipping notification")
return
}
print("[NOTIFICATIONS] App state: \(UIApplication.shared.applicationState.rawValue), sending notification")
#elseif os(macOS)
// On macOS, check if app is active
guard !NSApplication.shared.isActive else {
print("[NOTIFICATIONS] App is active/foreground, skipping notification")
return
}
print("[NOTIFICATIONS] App is not active, sending notification")
#endif
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
let request = UNNotificationRequest(
identifier: identifier,
content: content,
trigger: nil // Deliver immediately
)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("[NOTIFICATIONS] Error sending notification: \(error)")
} else {
print("[NOTIFICATIONS] Notification sent: \(title)")
}
}
}
func sendMentionNotification(from sender: String, message: String) {
let title = "Mentioned by \(sender)"
let body = message
let identifier = "mention-\(UUID().uuidString)"
sendLocalNotification(title: title, body: body, identifier: identifier)
}
func sendPrivateMessageNotification(from sender: String, message: String) {
let title = "Private message from \(sender)"
let body = message
let identifier = "private-\(UUID().uuidString)"
sendLocalNotification(title: title, body: body, identifier: identifier)
}
}