Skip to content

armgit / core

Public Imported from GitHub
0

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

Updated to match the Android code for StorageProvider #108

Michael Rademaker74c97d72d618
diff --git a/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj b/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj
index 14920fc85..b7b5f62f0 100644
--- a/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj
+++ b/console/iOS/ORLib/ORLib.xcodeproj/project.pbxproj
@@ -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 */,
diff --git a/console/iOS/ORLib/ORLib/Constants.swift b/console/iOS/ORLib/ORLib/Constants.swift
index d81fcc652..8a4703600 100644
--- a/console/iOS/ORLib/ORLib/Constants.swift
+++ b/console/iOS/ORLib/ORLib/Constants.swift
@@ -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,6 +38,7 @@ 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 {
@@ -46,11 +46,14 @@ public enum Actions {
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 {
diff --git a/console/iOS/ORLib/ORLib/GeofenceProvider.swift b/console/iOS/ORLib/ORLib/GeofenceProvider.swift
index 11d09abc3..769dfcd85 100644
--- a/console/iOS/ORLib/ORLib/GeofenceProvider.swift
+++ b/console/iOS/ORLib/ORLib/GeofenceProvider.swift
@@ -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()
}
}
diff --git a/console/iOS/ORLib/ORLib/ORAppDelegate.swift b/console/iOS/ORLib/ORLib/ORAppDelegate.swift
index ea4267727..06c52f57f 100644
--- a/console/iOS/ORLib/ORLib/ORAppDelegate.swift
+++ b/console/iOS/ORLib/ORLib/ORAppDelegate.swift
@@ -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)
+ }
+ }
}
}
diff --git a/console/iOS/ORLib/ORLib/ORViewController.swift b/console/iOS/ORLib/ORLib/ORViewController.swift
index 68b8806d2..036969752 100644
--- a/console/iOS/ORLib/ORLib/ORViewController.swift
+++ b/console/iOS/ORLib/ORLib/ORViewController.swift
@@ -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
diff --git a/console/iOS/ORLib/ORLib/PushNotificationProvider.swift b/console/iOS/ORLib/ORLib/PushNotificationProvider.swift
index d91311f22..3b63c049d 100644
--- a/console/iOS/ORLib/ORLib/PushNotificationProvider.swift
+++ b/console/iOS/ORLib/ORLib/PushNotificationProvider.swift
@@ -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)]
])
})
diff --git a/console/iOS/ORLib/ORLib/TokenManager.swift b/console/iOS/ORLib/ORLib/TokenManager.swift
index ffacca776..e02b5388e 100644
--- a/console/iOS/ORLib/ORLib/TokenManager.swift
+++ b/console/iOS/ORLib/ORLib/TokenManager.swift
@@ -24,80 +24,32 @@ import WebKit
public class TokenManager:NSObject, URLSessionDelegate {
- public var offlineToken : String?
- public var refreshToken : String?
- public var idToken : String?
- public var deviceId : String?
- public var hasToken: Bool
+ let defaults = UserDefaults(suiteName: ORAppGroup.entitlement)
public static let sharedInstance = TokenManager()
- override init() {
- let defaults = UserDefaults(suiteName: ORAppGroup.entitlement)
- defaults?.synchronize()
- if defaults?.value(forKey: DefaultsKey.token) != nil
- && defaults?.value(forKey: DefaultsKey.refreshToken) != nil
- && defaults?.value(forKey: DefaultsKey.idToken) != nil {
- hasToken = true
- offlineToken = defaults?.value(forKey: DefaultsKey.token) as? String
- refreshToken = defaults?.value(forKey: DefaultsKey.refreshToken) as? String
- idToken = defaults?.value(forKey: DefaultsKey.idToken) as? String
- } else {
- hasToken = false
- offlineToken = nil
- refreshToken = nil
- idToken = nil
- }
- deviceId = defaults?.value(forKey: DefaultsKey.deviceId) as? String
- super.init()
- }
-
- public func storeTokens(tokenJsonDictionnary : [String : String]?) {
- let defaults = UserDefaults(suiteName: ORAppGroup.entitlement)
-
- if (tokenJsonDictionnary?["refreshToken"] != nil) {
- offlineToken = tokenJsonDictionnary?["token"] ?? nil
- refreshToken = tokenJsonDictionnary?["refreshToken"]! ?? nil
- idToken = tokenJsonDictionnary?["idToken"] ?? nil
- defaults?.set(offlineToken, forKey: DefaultsKey.token)
- defaults?.set(refreshToken, forKey: DefaultsKey.refreshToken)
- defaults?.set(idToken, forKey: DefaultsKey.idToken)
- hasToken = true;
-
- // We just got a token, try to send the FCM token, we might not have been able to talk to backend when we got it initialy
- sendDeviceId()
- }
- }
-
public func logout() {
resetToken()
}
public func resetToken() {
- hasToken = false
- offlineToken = nil
- refreshToken = nil
- idToken = nil
- let defaults = UserDefaults(suiteName: ORAppGroup.entitlement)
- defaults?.removeObject(forKey: DefaultsKey.token)
- defaults?.removeObject(forKey: DefaultsKey.refreshToken)
- defaults?.removeObject(forKey: DefaultsKey.idToken)
+ defaults?.removeObject(forKey: DefaultsKey.fcmDeviceIdKey)
+ defaults?.removeObject(forKey: DefaultsKey.refreshTokenKey)
+ defaults?.removeObject(forKey: DefaultsKey.fcmTokenKey)
}
public func resetTokenAndAuthenticate() {
resetToken()
- // authenticate()
}
- public func storeDeviceId(token : String) {
- let defaults = UserDefaults(suiteName: ORAppGroup.entitlement)
- deviceId = token
- defaults?.set(token, forKey: DefaultsKey.deviceId)
+ public func storeDeviceId(token : String, deviceId: String) {
+ defaults?.set(token, forKey: DefaultsKey.fcmTokenKey)
+ defaults?.set(deviceId, forKey: DefaultsKey.fcmDeviceIdKey)
sendDeviceId()
}
- public func sendDeviceId() {
- if (deviceId != nil && hasToken) {
+ private func sendDeviceId() {
+ if let fcmToken = defaults?.string(forKey: DefaultsKey.fcmTokenKey), let deviceId = defaults?.string(forKey: DefaultsKey.fcmDeviceIdKey) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.getAccessToken { (accessTokenResult) in
switch accessTokenResult {
@@ -109,7 +61,7 @@ public class TokenManager:NSObject, URLSessionDelegate {
let request = NSMutableURLRequest(url: urlRequest)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
request.httpMethod = "PUT"
- let postString = String(format:"token=%@&device_id=%@", self.deviceId!, (UIDevice.current.identifierForVendor?.uuidString)!)
+ let postString = String(format:"token=%@&device_id=%@", fcmToken, deviceId)
request.httpBody = postString.data(using: .utf8)
request.addValue(String(format:"Bearer %@", accessToken!), forHTTPHeaderField: "Authorization")
let sessionConfiguration = URLSessionConfiguration.default
@@ -146,10 +98,13 @@ public class TokenManager:NSObject, URLSessionDelegate {
public func getAccessToken(callback: @escaping (AccesTokenResult<String>) -> ()) {
guard let tkurlRequest = URL(string: String(format:"\(ORServer.scheme)://%@/auth/realms/%@/protocol/openid-connect/token", ORServer.hostURL, ORServer.realm)) else { return }
+
+ guard let refreshToken = defaults?.string(forKey: DefaultsKey.refreshTokenKey) else { return }
+
let tkRequest = NSMutableURLRequest(url: tkurlRequest)
tkRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
tkRequest.httpMethod = "POST"
- let postString = String(format:"grant_type=refresh_token&refresh_token=%@&client_id=%@", refreshToken!, ORClient.clientId)
+ let postString = String(format:"grant_type=refresh_token&refresh_token=%@&client_id=%@", refreshToken, ORClient.clientId)
tkRequest.httpBody = postString.data(using: .utf8)
let sessionConfiguration = URLSessionConfiguration.default