Skip to content

Commit

Permalink
Switch to using FCM for messaging (#758)
Browse files Browse the repository at this point in the history
Signed-off-by: Dan Cunningham <[email protected]>
  • Loading branch information
digitaldan authored May 26, 2024
1 parent e574118 commit 927144c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 32 deletions.
2 changes: 1 addition & 1 deletion OpenHABCore/Sources/OpenHABCore/Util/Endpoint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
8 changes: 8 additions & 0 deletions openHAB.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -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 */; };
Expand Down Expand Up @@ -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 */,
Expand Down Expand Up @@ -1097,6 +1099,7 @@
93F8064C27AE7A4D0035A6B0 /* DynamicButton */,
93F8064F27AE7A830035A6B0 /* SideMenu */,
93F8065227AE7B580035A6B0 /* SVGKit */,
6557AF912C039D140094D0C8 /* FirebaseMessaging */,
);
productName = openHAB;
productReference = DFB2622718830A3600D3244D /* openHAB.app */;
Expand Down Expand Up @@ -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;
Expand Down
56 changes: 25 additions & 31 deletions openHAB/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import AlamofireNetworkActivityIndicator
import AVFoundation
import Firebase
import FirebaseMessaging
import Kingfisher
import OpenHABCore
import os.log
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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() {
Expand All @@ -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()
}
}
}
}
Expand All @@ -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) {
Expand All @@ -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 {
Expand All @@ -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)
Expand Down Expand Up @@ -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)
}
}

0 comments on commit 927144c

Please sign in to comment.