From 927144cf8accf5143e3f74816c292856ae657559 Mon Sep 17 00:00:00 2001 From: Dan Cunningham Date: Sun, 26 May 2024 13:54:59 -0700 Subject: [PATCH] Switch to using FCM for messaging (#758) Signed-off-by: Dan Cunningham --- .../Sources/OpenHABCore/Util/Endpoint.swift | 2 +- openHAB.xcodeproj/project.pbxproj | 8 +++ openHAB/AppDelegate.swift | 56 +++++++++---------- 3 files changed, 34 insertions(+), 32 deletions(-) diff --git a/OpenHABCore/Sources/OpenHABCore/Util/Endpoint.swift b/OpenHABCore/Sources/OpenHABCore/Util/Endpoint.swift index b0999ffd..775eebc6 100644 --- a/OpenHABCore/Sources/OpenHABCore/Util/Endpoint.swift +++ b/OpenHABCore/Sources/OpenHABCore/Util/Endpoint.swift @@ -56,7 +56,7 @@ public extension Endpoint { deviceName: String) -> Endpoint { Endpoint( baseURL: prefsURL, - path: "/addAppleRegistration", + path: "/addIosRegistration", queryItems: [ URLQueryItem(name: "regId", value: deviceToken), URLQueryItem(name: "deviceId", value: deviceId), diff --git a/openHAB.xcodeproj/project.pbxproj b/openHAB.xcodeproj/project.pbxproj index 003c7b82..a3a765f5 100644 --- a/openHAB.xcodeproj/project.pbxproj +++ b/openHAB.xcodeproj/project.pbxproj @@ -16,6 +16,7 @@ 65570A7D2476D16A00D524EA /* OpenHABWebViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65570A7C2476D16A00D524EA /* OpenHABWebViewController.swift */; }; 6557AF8F2C0241C10094D0C8 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 6557AF8E2C0241C10094D0C8 /* PrivacyInfo.xcprivacy */; }; 6557AF902C0241C10094D0C8 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 6557AF8E2C0241C10094D0C8 /* PrivacyInfo.xcprivacy */; }; + 6557AF922C039D140094D0C8 /* FirebaseMessaging in Frameworks */ = {isa = PBXBuildFile; productRef = 6557AF912C039D140094D0C8 /* FirebaseMessaging */; }; 656916D91FCB82BC00667B2A /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 656916D81FCB82BC00667B2A /* GoogleService-Info.plist */; }; 6595667E28E0BE8E00E8A53B /* MulticastDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6595667D28E0BE8E00E8A53B /* MulticastDelegate.swift */; }; 932602EE2382892B00EAD685 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = DAC6608B236F6F4200F4501E /* Assets.xcassets */; }; @@ -500,6 +501,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 6557AF922C039D140094D0C8 /* FirebaseMessaging in Frameworks */, DFB2622B18830A3600D3244D /* Foundation.framework in Frameworks */, 937E4485270B379900A98C26 /* DeviceKit in Frameworks */, DFB2622F18830A3600D3244D /* UIKit.framework in Frameworks */, @@ -1097,6 +1099,7 @@ 93F8064C27AE7A4D0035A6B0 /* DynamicButton */, 93F8064F27AE7A830035A6B0 /* SideMenu */, 93F8065227AE7B580035A6B0 /* SVGKit */, + 6557AF912C039D140094D0C8 /* FirebaseMessaging */, ); productName = openHAB; productReference = DFB2622718830A3600D3244D /* openHAB.app */; @@ -2221,6 +2224,11 @@ /* End XCRemoteSwiftPackageReference section */ /* Begin XCSwiftPackageProductDependency section */ + 6557AF912C039D140094D0C8 /* FirebaseMessaging */ = { + isa = XCSwiftPackageProductDependency; + package = 93F8063327AE6C620035A6B0 /* XCRemoteSwiftPackageReference "firebase-ios-sdk" */; + productName = FirebaseMessaging; + }; 934E592428F16EBA00162004 /* OpenHABCore */ = { isa = XCSwiftPackageProductDependency; productName = OpenHABCore; diff --git a/openHAB/AppDelegate.swift b/openHAB/AppDelegate.swift index 625eb93c..31ca0b1a 100644 --- a/openHAB/AppDelegate.swift +++ b/openHAB/AppDelegate.swift @@ -12,6 +12,7 @@ import AlamofireNetworkActivityIndicator import AVFoundation import Firebase +import FirebaseMessaging import Kingfisher import OpenHABCore import os.log @@ -49,7 +50,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { os_log("didFinishLaunchingWithOptions started", log: .viewCycle, type: .info) - setupCrashReporting() + setupFirebase() let appDefaults = ["CacheDataAgressively": NSNumber(value: true)] UserDefaults.standard.register(defaults: appDefaults) @@ -84,11 +85,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate { return true } - private func setupCrashReporting() { + private func setupFirebase() { // init Firebase crash reporting FirebaseApp.configure() FirebaseApp.app()?.isDataCollectionDefaultEnabled = false Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(Preferences.sendCrashReports) + Messaging.messaging().delegate = self } func activateWatchConnectivity() { @@ -113,17 +115,13 @@ class AppDelegate: UIResponder, UIApplicationDelegate { guard let self else { return } os_log("Permission granted: %{PUBLIC}@", log: .notifications, type: .info, granted ? "YES" : "NO") guard granted else { return } - getNotificationSettings() - } - } - - func getNotificationSettings() { - UNUserNotificationCenter.current().getNotificationSettings { settings in - os_log("Notification settings: %{PUBLIC}@", log: .notifications, type: .info, settings) + UNUserNotificationCenter.current().getNotificationSettings { settings in + os_log("Notification settings: %{PUBLIC}@", log: .notifications, type: .info, settings) - guard settings.authorizationStatus == .authorized else { return } - DispatchQueue.main.async { - UIApplication.shared.registerForRemoteNotifications() + guard settings.authorizationStatus == .authorized else { return } + DispatchQueue.main.async { + UIApplication.shared.registerForRemoteNotifications() + } } } } @@ -146,16 +144,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { // This is only informational - on success - DID Register func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { - let deviceTokenString = deviceToken.reduce("") { $0 + String(format: "%02X", $1) } // try "%02.2hhx", - - os_log("My token is: %{PUBLIC}@", log: .notifications, type: .info, deviceTokenString) - - let dataDict = [ - "deviceToken": deviceTokenString, - "deviceId": UIDevice.current.identifierForVendor?.uuidString ?? "", - "deviceName": UIDevice.current.name - ] - NotificationCenter.default.post(name: NSNotification.Name("apsRegistered"), object: self, userInfo: dataDict) + // Do nothing now, we are using FCM } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { @@ -166,16 +155,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate { fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // version without completionHandler is deprecated // func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { - os_log("didReceiveRemoteNotification", log: .notifications, type: .info) + os_log("didReceiveRemoteNotification %{PUBLIC}@", log: .notifications, type: .info, userInfo) if application.applicationState == .active { os_log("App is active and got a remote notification", log: .notifications, type: .info) - - guard let aps = userInfo["aps"] as? [String: AnyObject] else { - completionHandler(.failed) - return - } - let soundPath: URL? = Bundle.main.url(forResource: "ping", withExtension: "wav") if let soundPath { do { @@ -189,9 +172,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } player = try? AVAudioPlayer(contentsOf: soundPath) } - os_log("%{PUBLIC}@", log: .notifications, type: .info, aps) - let message = (aps["alert"] as? [String: String])?["body"] ?? NSLocalizedString("message_not_decoded", comment: "") + let message = userInfo["message"] as? String ?? NSLocalizedString("message_not_decoded", comment: "") var config = SwiftMessages.Config() config.duration = .seconds(seconds: 5) @@ -231,3 +213,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } + +extension AppDelegate: MessagingDelegate { + func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { + os_log("My FCM token is: %{PUBLIC}@", log: .notifications, type: .info, fcmToken ?? "") + let dataDict = [ + "deviceToken": fcmToken ?? "", + "deviceId": UIDevice.current.identifierForVendor?.uuidString ?? "", + "deviceName": UIDevice.current.name + ] + NotificationCenter.default.post(name: NSNotification.Name("apsRegistered"), object: self, userInfo: dataDict) + } +}