Permalink
Browse files

Updated to match the Android code for StorageProvider #108

  • Loading branch information...
Miggets7 committed Feb 6, 2019
1 parent 23cbc2c commit 74c97d72d6181ba64f095dc369c7b8d10ddd5d36
@@ -7,6 +7,7 @@
objects = {

/* Begin PBXBuildFile section */
4C33B4772209D10200681732 /* StorageProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C33B4762209D10200681732 /* StorageProvider.swift */; };
4C4C2FB81FD8044A0071CBDA /* ORNotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C4C2FB71FD8044A0071CBDA /* ORNotificationService.swift */; };
4C56E5E520C583FB004483C7 /* ORAssetResoure.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C56E5E420C583FB004483C7 /* ORAssetResoure.swift */; };
4C77278520BC13E800322CBC /* PushNotificationProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C77278320BC13E800322CBC /* PushNotificationProvider.swift */; };
@@ -27,6 +28,7 @@
/* End PBXBuildFile section */

/* Begin PBXFileReference section */
4C33B4762209D10200681732 /* StorageProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StorageProvider.swift; sourceTree = "<group>"; };
4C4C2FB71FD8044A0071CBDA /* ORNotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ORNotificationService.swift; sourceTree = "<group>"; };
4C56E5E420C583FB004483C7 /* ORAssetResoure.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ORAssetResoure.swift; sourceTree = "<group>"; };
4C77278320BC13E800322CBC /* PushNotificationProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PushNotificationProvider.swift; sourceTree = "<group>"; };
@@ -106,6 +108,7 @@
4CC3FD8E210F63650025579A /* ConsoleProviders */ = {
isa = PBXGroup;
children = (
4C33B4762209D10200681732 /* StorageProvider.swift */,
4C77278420BC13E800322CBC /* GeofenceProvider.swift */,
4C77278320BC13E800322CBC /* PushNotificationProvider.swift */,
);
@@ -209,6 +212,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
4C33B4772209D10200681732 /* StorageProvider.swift in Sources */,
4C77278620BC13E800322CBC /* GeofenceProvider.swift in Sources */,
4C9FC2F2211B2F8100D8FD18 /* ORPushNotificationButton.swift in Sources */,
4C56E5E520C583FB004483C7 /* ORAssetResoure.swift in Sources */,
@@ -27,10 +27,9 @@ public enum AccesTokenResult<String>
}

public enum DefaultsKey {
public static let token = "token"
public static let refreshToken = "refreshToken"
public static let idToken = "idToken"
public static let deviceId = "deviceToken"
public static let refreshTokenKey = "REFRESH_TOKEN"
public static let fcmTokenKey = "FCM_TOKEN_KEY"
public static let fcmDeviceIdKey = "FCM_DEVICE_ID_KEY"
public static let actionKey = "action"
public static let buttonsKey = "buttons"
public static let providerKey = "provider"
@@ -39,18 +38,22 @@ public enum DefaultsKey {
public static let hasPermissionKey = "hasPermission"
public static let successKey = "success"
public static let dataKey = "data"
public static let enabledKey = "enabled"
}

public enum Actions {
public static let providerInit = "PROVIDER_INIT"
public static let providerEnable = "PROVIDER_ENABLE"
public static let providerDisable = "PROVIDER_DISABLE"
public static let geofenceRefresh = "GEOFENCE_REFRESH"
public static let store = "STORE"
public static let retrieve = "RETRIEVE"
}

public enum Providers {
public static let push = "push"
public static let geofence = "geofence"
public static let storage = "storage"
}

public enum NotificationsNames {
@@ -8,7 +8,7 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
static let geoPostUrlsKey = "geoPostUrls"

let version = "ORConsole"
let geofenceFetchEndpoint = "rules/geofences/"
let geofenceFetchEndpoint = "api/rules/geofences/"
let locationManager = CLLocationManager()
let userdefaults = UserDefaults(suiteName: ORAppGroup.entitlement)
var geoPostUrls = [String:[String]]()
@@ -37,9 +37,10 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
DefaultsKey.actionKey: Actions.providerInit,
DefaultsKey.providerKey: Providers.geofence,
DefaultsKey.versionKey: version,
DefaultsKey.requiresPermissionKey: true,
DefaultsKey.hasPermissionKey: checkPermission(),
DefaultsKey.successKey: true
DefaultsKey.requiresPermissionKey: false,
DefaultsKey.hasPermissionKey: true,
DefaultsKey.successKey: true,
DefaultsKey.enabledKey: true
]
}

@@ -116,7 +117,7 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
public func disable()-> [String: Any] {
locationManager.stopMonitoringSignificantLocationChanges()
return [
DefaultsKey.actionKey: "PROVIDER_DISABLE",
DefaultsKey.actionKey: Actions.providerDisable,
DefaultsKey.providerKey: Providers.geofence
]
}
@@ -173,7 +174,7 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {

if !sendQueued {
sendQueued = true
DispatchQueue.global().async {
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(2)) {
self.doSendLocation()
}
}
@@ -22,6 +22,7 @@ import UIKit
import UserNotifications
import FirebaseCore
import FirebaseMessaging
import FirebaseInstanceID
import CoreLocation

@UIApplicationMain
@@ -39,13 +40,11 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
UNUserNotificationCenter.current().delegate = self
// if the app was launched because of geofencing
#if DEBUG
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let fileName = "\(Date()).log"
let logFilePath = (documentsDirectory as NSString).appendingPathComponent(fileName)
freopen(logFilePath.cString(using: String.Encoding.ascii)!, "a+", stderr)
#endif

if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {
NSLog("%@", "App started from location update")
@@ -54,6 +53,17 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
if CLLocationManager.authorizationStatus() == .authorizedAlways {
geofenceProvider?.locationManager.startMonitoringSignificantLocationChanges()
}
} else if let remoteNotifcation = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {
NSLog("%@", "App started from remote notification")
if let action = remoteNotifcation[DefaultsKey.actionKey] as? String {
if action == Actions.geofenceRefresh {
geofenceProvider = GeofenceProvider()
geofenceProvider?.refreshGeofences()
if CLLocationManager.authorizationStatus() == .authorizedAlways {
geofenceProvider?.locationManager.startMonitoringSignificantLocationChanges()
}
}
}
} else {
FirebaseApp.configure()
Messaging.messaging().delegate = self
@@ -121,20 +131,43 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate

open func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
InstanceID.instanceID().getID { (result, error) in
if let error = error {
print("Error fetching remote instange ID: \(error)")
}
if let token = InstanceID.instanceID().token(), let deviceId = result {
TokenManager.sharedInstance.storeDeviceId(token: token, deviceId: deviceId)
}
}
}

open func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let action = userInfo[DefaultsKey.actionKey] as? String {
if action == Actions.geofenceRefresh {
(self.window?.rootViewController as! ORViewcontroller).geofenceProvider?.refreshGeofences()
if let controllerGeofenceProvider = (self.window?.rootViewController as! ORViewcontroller).geofenceProvider {
controllerGeofenceProvider.refreshGeofences()
} else if let delegateGeofenceProvider = geofenceProvider {
delegateGeofenceProvider.refreshGeofences()
} else {
geofenceProvider = GeofenceProvider()
geofenceProvider!.refreshGeofences()
}
} else if action == Actions.store {
if let data = userInfo[DefaultsKey.dataKey] as? [String: String] {
if let key = data["key"] {
if let storageProvider = (self.window?.rootViewController as! ORViewcontroller).storageProvider {
storageProvider.store(key: key, data: data["value"])
}
}
}
}
}

if let notificationIdString = userInfo[ActionType.notificationId] as? String, let notificationId = Int64(notificationIdString) {
if let defaults = UserDefaults(suiteName: ORAppGroup.entitlement), let consoleId = defaults.string(forKey: GeofenceProvider.consoleIdKey) {
ORNotificationResource.sharedInstance.notificationDelivered(notificationId: notificationId, targetId: consoleId)
}
}

completionHandler(UIBackgroundFetchResult.newData)
}

@@ -178,7 +211,6 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
reachabilityAlertShown = false
}
}

}

open func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
@@ -193,7 +225,7 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
}

extension ORAppDelegate : UNUserNotificationCenterDelegate {

open func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
var notificationId : Int64? = nil
@@ -306,12 +338,26 @@ extension ORAppDelegate : UNUserNotificationCenterDelegate {
extension ORAppDelegate : MessagingDelegate {
open func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
TokenManager.sharedInstance.storeDeviceId(token: fcmToken)
InstanceID.instanceID().getID { (result, error) in
if let error = error {
print("Error fetching remote instange ID: \(error)")
}
if let token = InstanceID.instanceID().token(), let deviceId = result {
TokenManager.sharedInstance.storeDeviceId(token: token, deviceId: deviceId)
}
}
}

open func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
TokenManager.sharedInstance.storeDeviceId(token: fcmToken)
InstanceID.instanceID().getID { (result, error) in
if let error = error {
print("Error fetching remote instange ID: \(error)")
}
if let token = InstanceID.instanceID().token(), let deviceId = result {
TokenManager.sharedInstance.storeDeviceId(token: token, deviceId: deviceId)
}
}
}
}

@@ -32,6 +32,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess

var geofenceProvider: GeofenceProvider?
var pushProvider: PushNotificationProvider?
var storageProvider: StorageProvider?

open override func viewDidLoad() {
super.viewDidLoad()
@@ -47,9 +48,6 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
let jsonDictionnary = message.body as? [String : Any]
if let type = jsonDictionnary?["type"] as? String {
switch (type) {
case "token":
let tokenJsonDictionnary = jsonDictionnary?[DefaultsKey.dataKey] as? [String : String]
TokenManager.sharedInstance.storeTokens(tokenJsonDictionnary: tokenJsonDictionnary)
case "provider":
if let postMessageDict = jsonDictionnary?[DefaultsKey.dataKey] as? [String: Any] {
if let action = postMessageDict[DefaultsKey.actionKey] as? String {
@@ -73,8 +71,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
sendData(data: disableData)
}
}
}
if provider == Providers.geofence {
} else if provider == Providers.geofence {
if action == Actions.providerInit {
geofenceProvider = GeofenceProvider()
let initializeData = geofenceProvider!.initialize()
@@ -97,6 +94,34 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
sendData(data: disableData)
}
}
} else if provider == Providers.storage {
if action == Actions.providerInit {
storageProvider = StorageProvider()
let initializeData = storageProvider!.initialize()
sendData(data: initializeData)
} else if action == Actions.providerEnable {
if let enableData = storageProvider?.enable() {
sendData(data: enableData)
}
} else if action == Actions.store {
if let data = postMessageDict[DefaultsKey.dataKey] as? [String: String] {
if let key = data["key"] {
storageProvider?.store(key: key, data: data["value"])
}
}
} else if action == Actions.retrieve {
if let data = postMessageDict[DefaultsKey.dataKey] as? [String: String] {
if let key = data["key"] {
if let retrieveData = storageProvider?.retrieve(key: key) {
sendData(data: retrieveData)
}
}
}
} else if action == Actions.providerDisable {
if let disableData = storageProvider?.disable() {
sendData(data: disableData)
}
}
}
}
}
@@ -113,7 +138,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .utf8)
let returnMessage = "OpenRemoteConsole.handleProviderResponse('\(theJSONText ?? "null")')"
let returnMessage = "openremote.INSTANCE.console.handleProviderResponse('\(theJSONText ?? "null")')"
DispatchQueue.main.async {
self.myWebView?.evaluateJavaScript("\(returnMessage)", completionHandler: { (any, error) in
print("JSON string = \(theJSONText!)")
@@ -129,21 +154,6 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
completionHandler()
}

open func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
var exec_template : String? = nil
switch (prompt) {
case "token":
if TokenManager.sharedInstance.offlineToken != nil && TokenManager.sharedInstance.refreshToken != nil && TokenManager.sharedInstance.idToken != nil {
exec_template = "{ \"token\": \"\(TokenManager.sharedInstance.offlineToken ?? "null")\", \"refreshToken\": \"\(TokenManager.sharedInstance.refreshToken ?? "null")\",\"idToken\": \"\(TokenManager.sharedInstance.idToken ?? "null")\"}"
}

default:
print("Unknown message type: \(prompt )")
}

completionHandler(exec_template)
}

open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if (navigationAction.request.url?.absoluteString.contains("logout"))! {
TokenManager.sharedInstance.logout()
@@ -168,6 +178,10 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
if response.statusCode != 200 && response.statusCode != 204 {
decisionHandler(.cancel)

if response.url?.lastPathComponent == "token" && response.statusCode == 400 {
TokenManager.sharedInstance.resetToken()
}

isLoading = false
handleError(errorCode: response.statusCode, description: "Error in request", failingUrl: response.url?.absoluteString ?? "", isForMainFrame: true)
return
@@ -72,7 +72,7 @@ public class PushNotificationProvider: NSObject {
DefaultsKey.providerKey: Providers.push,
DefaultsKey.hasPermissionKey: true,
DefaultsKey.successKey: true,
DefaultsKey.dataKey: [DefaultsKey.token: TokenManager.sharedInstance.deviceId]
DefaultsKey.dataKey: ["token": self.userdefaults?.string(forKey: DefaultsKey.fcmTokenKey)]
])

case .denied:
@@ -81,7 +81,7 @@ public class PushNotificationProvider: NSObject {
DefaultsKey.providerKey: Providers.push,
DefaultsKey.hasPermissionKey: false,
DefaultsKey.successKey: true,
DefaultsKey.dataKey: [DefaultsKey.token: TokenManager.sharedInstance.deviceId]
DefaultsKey.dataKey: ["token": self.userdefaults?.string(forKey: DefaultsKey.fcmTokenKey)]
])

case .notDetermined:
@@ -99,7 +99,7 @@ public class PushNotificationProvider: NSObject {
DefaultsKey.providerKey: Providers.push,
DefaultsKey.hasPermissionKey: granted,
DefaultsKey.successKey: true,
DefaultsKey.dataKey: [DefaultsKey.token: TokenManager.sharedInstance.deviceId]
DefaultsKey.dataKey: ["token": self.userdefaults?.string(forKey: DefaultsKey.fcmTokenKey)]
])
})

Oops, something went wrong.

0 comments on commit 74c97d7

Please sign in to comment.