Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Implemented new notification system in iOS lib

Michael Rademaker5414050cc72f
diff --git a/console/iOS/ORLib/ORLib.podspec b/console/iOS/ORLib/ORLib.podspec
index 62e592bc8..bce4348da 100644
--- a/console/iOS/ORLib/ORLib.podspec
+++ b/console/iOS/ORLib/ORLib.podspec
@@ -10,7 +10,7 @@ Pod::Spec.new do |s|
s.name = "ORLib"
s.summary = "The OpenRemote library to create console apps."
s.requires_arc = true
- s.version = '1.1.0'
+ s.version = '1.1.1'
s.authors = 'OpenRemote'
s.homepage = "http://www.openremote.io"
s.source = { :git => 'https://github.com/openremote/openremote.git', :tag => 'cocoapod' + s.version.to_s }
diff --git a/console/iOS/ORLib/ORLib/Constants.swift b/console/iOS/ORLib/ORLib/Constants.swift
index d5662c9c6..d81fcc652 100644
--- a/console/iOS/ORLib/ORLib/Constants.swift
+++ b/console/iOS/ORLib/ORLib/Constants.swift
@@ -32,6 +32,7 @@ public enum DefaultsKey {
public static let idToken = "idToken"
public static let deviceId = "deviceToken"
public static let actionKey = "action"
+ public static let buttonsKey = "buttons"
public static let providerKey = "provider"
public static let versionKey = "version"
public static let requiresPermissionKey = "requiresPermission"
@@ -71,6 +72,10 @@ public enum ActionType {
public static let title = "title"
public static let type = "type"
public static let appUrl = "appUrl"
+ public static let silent = "silent"
+ public static let httpMethod = "httpMethod"
+ public static let openInBrowser = "openInBrowser"
+ public static let notificationId = "notification-id"
public static let ACTION_DEEP_LINK = "LINK"
public static let ACTION_ACTUATOR = "ACTUATOR"
}
diff --git a/console/iOS/ORLib/ORLib/ORAppDelegate.swift b/console/iOS/ORLib/ORLib/ORAppDelegate.swift
index 5bd61f7c6..96d93d5b8 100644
--- a/console/iOS/ORLib/ORLib/ORAppDelegate.swift
+++ b/console/iOS/ORLib/ORLib/ORAppDelegate.swift
@@ -115,6 +115,11 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
(self.window?.rootViewController as! ORViewcontroller).geofenceProvider?.refreshGeofences()
}
}
+ if let notificationIdString = userInfo[ActionType.notificationId] as? String, let notificationId = Int64(notificationIdString) {
+ if let consoleId = UserDefaults.standard.string(forKey: GeofenceProvider.consoleIdKey) {
+ ORNotificationResource.sharedInstance.notificationDelivered(notificationId: notificationId, targetId: consoleId)
+ }
+ }
completionHandler(UIBackgroundFetchResult.newData)
}
@@ -179,34 +184,43 @@ extension ORAppDelegate : UNUserNotificationCenterDelegate {
}
open func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
- var assetId : String = ""
- var attributeName : String = ""
- var rawJson : String = ""
- UIApplication.shared.isNetworkActivityIndicatorVisible = true
+
+ var notificationId : Int64? = nil
+ let consoleId = UserDefaults.standard.string(forKey: GeofenceProvider.consoleIdKey)
+
+ if let notificationIdString = response.notification.request.content.userInfo[ActionType.notificationId] as? String{
+ notificationId = Int64(notificationIdString)
+ }
+
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier,
- ActionType.ACTION_DEEP_LINK :
- if let urlToOpen = response.notification.request.content.userInfo["appUrl"] as? String {
+ "pushAction" :
+ if let notiId = notificationId, let conId = consoleId {
+ ORNotificationResource.sharedInstance.notificationAcknowledged(notificationId: notiId, targetId: conId, acknowledgement: "acknowledged")
+ }
+
+ if let urlToOpen = response.notification.request.content.userInfo[ActionType.appUrl] as? String {
+ let urlRequest: URL?
if urlToOpen.hasPrefix("http") || urlToOpen.hasPrefix("https") {
- guard let urlRequest = URL(string:urlToOpen) else { return }
- (self.window?.rootViewController as! ORViewcontroller).loadURL(url:urlRequest)
+ urlRequest = URL(string:urlToOpen)
} else {
- guard let urlRequest = URL(string:String(format: "%@://%@/%@%@", ORServer.scheme, ORServer.hostURL, ORServer.navigationPath, urlToOpen)) else { return }
- (self.window?.rootViewController as! ORViewcontroller).loadURL(url:urlRequest)
+ urlRequest = URL(string:String(format: "%@://%@/%@%@", ORServer.scheme, ORServer.hostURL, ORServer.navigationPath, urlToOpen))
+ }
+ if let request = urlRequest{
+ if let openInBrowser = response.notification.request.content.userInfo[ActionType.openInBrowser] as? Bool {
+ if openInBrowser {
+ UIApplication.shared.open(request)
+ } else {
+ (self.window?.rootViewController as! ORViewcontroller).loadURL(url:request)
+ }
+ } else {
+ (self.window?.rootViewController as! ORViewcontroller).loadURL(url:request)
+ }
}
- NSLog("Action asked : %@", response.actionIdentifier)
- }
- case ActionType.ACTION_ACTUATOR :
- NSLog("Action asked : %@", response.actionIdentifier)
-
- if let actions = response.notification.request.content.userInfo["actions"] {
- assetId = (actions as! Dictionary<String,String>)["assetId"]!
- attributeName = (actions as! Dictionary<String,String>)["attributeName"]!
- rawJson = (actions as! Dictionary<String,String>)["rawJson"]!
}
-
- if let jsonData = rawJson.data(using: .utf8) {
- ORAssetResoure.sharedInstance.updateAssetAttribute(assetId : assetId, attributeName : attributeName, rawJson : jsonData)
+ case UNNotificationDismissActionIdentifier:
+ if let notiId = notificationId, let conId = consoleId {
+ ORNotificationResource.sharedInstance.notificationAcknowledged(notificationId: notiId, targetId: conId, acknowledgement: "dismissed")
}
default : break
}
diff --git a/console/iOS/ORLib/ORLib/ORNotificationService.swift b/console/iOS/ORLib/ORLib/ORNotificationService.swift
index 64add3a08..81a0f1a6f 100644
--- a/console/iOS/ORLib/ORLib/ORNotificationService.swift
+++ b/console/iOS/ORLib/ORLib/ORNotificationService.swift
@@ -30,39 +30,65 @@ open class ORNotificationService: UNNotificationServiceExtension, URLSessionDele
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
print("NotifExtension Change content : %@ ", bestAttemptContent?.userInfo ?? "")
if let bestAttemptContent = bestAttemptContent {
- if let actionsString = bestAttemptContent.userInfo["actions"] as? String {
- if let actionsData = actionsString.data(using: .utf8){
- if let actions = try? JSONSerialization.jsonObject(with: actionsData, options: []) as? [[String: String]], actions != nil {
+ print(bestAttemptContent.userInfo)
+ if let notificationIdString = bestAttemptContent.userInfo[ActionType.notificationId] as? String, let notificationId = Int64(notificationIdString) {
+ if let consoleId = UserDefaults.standard.string(forKey: GeofenceProvider.consoleIdKey) {
+ ORNotificationResource.sharedInstance.notificationDelivered(notificationId: notificationId, targetId: consoleId)
+ }
+ }
+
+ //Actions
+ if let actionString = bestAttemptContent.userInfo[DefaultsKey.actionKey] as? String {
+ if let actionsData = actionString.data(using: .utf8){
+ if let action = try? JSONDecoder().decode(ORPushNotificationAction.self, from: actionsData) {
+ let categoryName = "openremoteNotification"
+ bestAttemptContent.categoryIdentifier = categoryName
+
+ bestAttemptContent.userInfo[ActionType.appUrl] = action.url
+ bestAttemptContent.userInfo[ActionType.silent] = action.silent
+ bestAttemptContent.userInfo[ActionType.openInBrowser] = action.openInBrowser
+ bestAttemptContent.userInfo[ActionType.httpMethod] = action.httpMethod ?? "GET"
+ bestAttemptContent.userInfo[DefaultsKey.dataKey] = action.data ?? "null"
+
+ let category = UNNotificationCategory(identifier: categoryName, actions: [], intentIdentifiers: [], options: [])
+ let categories : Set = [category]
+ UNUserNotificationCenter.current().setNotificationCategories(categories)
+ }
+ }
+ contentHandler(bestAttemptContent)
+ }
+
+ //Buttons
+ if let buttonsString = bestAttemptContent.userInfo[DefaultsKey.buttonsKey] as? String {
+ if let buttonsData = buttonsString.data(using: .utf8) {
+ if let buttons = try? JSONDecoder().decode([ORPushNotificationButton].self, from: buttonsData) {
+
let categoryName = "openremoteNotification"
bestAttemptContent.categoryIdentifier = categoryName
var notificationActions = [UNNotificationAction]()
- for i in (0..<actions!.count) {
- let actionTitle = actions![i]["title"]!
- let actionType = actions![i]["type"]!
- switch actionType {
- case ActionType.ACTION_ACTUATOR :
- bestAttemptContent.userInfo["actions"] = actions![i]
- notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.destructive))
- case ActionType.ACTION_DEEP_LINK :
- if let appUrl = actions![i]["appUrl"] {
- bestAttemptContent.userInfo["appUrl"] = appUrl
- notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.foreground))
- } else {
- notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.destructive))
- }
- default : break
+
+ for button in buttons {
+ if let action = button.action {
+ bestAttemptContent.userInfo[ActionType.appUrl] = action.url
+ bestAttemptContent.userInfo[ActionType.silent] = action.silent
+ bestAttemptContent.userInfo[ActionType.openInBrowser] = action.openInBrowser
+ bestAttemptContent.userInfo[ActionType.httpMethod] = action.httpMethod ?? "GET"
+ bestAttemptContent.userInfo[DefaultsKey.dataKey] = action.data ?? "null"
}
+ notificationActions.append(UNNotificationAction(identifier: "pushAction", title: button.title, options: UNNotificationActionOptions.foreground))
}
+
let category = UNNotificationCategory(identifier: categoryName, actions: notificationActions, intentIdentifiers: [], options: [])
let categories : Set = [category]
UNUserNotificationCenter.current().setNotificationCategories(categories)
}
}
- contentHandler(bestAttemptContent)
}
+ contentHandler(bestAttemptContent)
}
}
+
open override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
diff --git a/console/iOS/ORLib/ORLib/ORViewController.swift b/console/iOS/ORLib/ORLib/ORViewController.swift
index c1b4ddf7f..f5adeae2e 100644
--- a/console/iOS/ORLib/ORLib/ORViewController.swift
+++ b/console/iOS/ORLib/ORLib/ORViewController.swift
@@ -60,9 +60,13 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
self.sendData(data: initalizeData)
})
} else if action == Actions.providerEnable {
- pushProvider?.enable(callback: { enableData in
- self.sendData(data: enableData)
- })
+ if let data = postMessageDict[DefaultsKey.dataKey] as? [String: String] {
+ if let consoleId = data[GeofenceProvider.consoleIdKey] {
+ pushProvider?.enable(consoleId: consoleId, callback: { enableData in
+ self.sendData(data: enableData)
+ })
+ }
+ }
} else if action == Actions.providerDisable {
if let disableData = pushProvider?.disbale() {
sendData(data: disableData)
@@ -76,7 +80,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
sendData(data: initializeData)
} else if action == Actions.providerEnable {
if let data = postMessageDict[DefaultsKey.dataKey] as? [String: String] {
- if let consoleId = data["consoleId"] {
+ if let consoleId = data[GeofenceProvider.consoleIdKey] {
geofenceProvider?.enable(baseUrl: "\(ORServer.baseUrl)\(ORServer.realm)", consoleId: consoleId, callback: { enableData in
self.sendData(data: enableData)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
@@ -110,7 +114,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
encoding: .utf8)
let returnMessage = "openremote.INSTANCE.console.handleProviderResponse('\(theJSONText ?? "null")')"
DispatchQueue.main.async {
- self.myWebView?.evaluateJavaScript("\(returnMessage)", completionHandler: { (any, error) in
+ self.myWebView?.evaluateJavaScript("\(returnMessage)", completionHandler: { (any, error) in
print("JSON string = \(theJSONText!)")
})
}
@@ -161,7 +165,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
if let response = navigationResponse.response as? HTTPURLResponse {
if response.statusCode != 200 && response.statusCode != 204 {
decisionHandler(.cancel)
- NSLog("error http status : %@ message : %@", response.statusCode, response.description)
+
let error = NSError(domain: "", code: 0, userInfo: [
NSLocalizedDescriptionKey : NSLocalizedString("HTTPErrorReturned", value: "Connection Error", comment: "")
])
@@ -171,6 +175,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
self.dismiss(animated: true) {
ErrorManager.showError(error:error)
}
+ return
}
}
decisionHandler(.allow)
diff --git a/console/iOS/ORLib/ORLib/PushNotificationProvider.swift b/console/iOS/ORLib/ORLib/PushNotificationProvider.swift
index 024cca879..dc4dcb5e6 100644
--- a/console/iOS/ORLib/ORLib/PushNotificationProvider.swift
+++ b/console/iOS/ORLib/ORLib/PushNotificationProvider.swift
@@ -9,9 +9,11 @@
import UIKit
import UserNotifications
-class PushNotificationProvider: NSObject {
+public class PushNotificationProvider: NSObject {
+ let userdefaults = UserDefaults.standard
let version = "fcm"
+ public var consoleId: String = ""
public override init() {
super.init()
@@ -54,7 +56,10 @@ class PushNotificationProvider: NSObject {
}
}
- public func enable(callback:@escaping ([String: Any]) ->(Void)) {
+ public func enable(consoleId: String, callback:@escaping ([String: Any]) ->(Void)) {
+ self.consoleId = consoleId
+ userdefaults.set(self.consoleId, forKey: GeofenceProvider.consoleIdKey)
+ userdefaults.synchronize()
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
switch settings.authorizationStatus {