Skip to content

armgit / core

Public Imported from GitHub
0

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

iOS console : code cleaning

William Balcaen2196e3e58eb9
diff --git a/console/iOS/console/AppDelegate.swift b/console/iOS/console/AppDelegate.swift
index bdc9cd12a..fe2e83592 100644
--- a/console/iOS/console/AppDelegate.swift
+++ b/console/iOS/console/AppDelegate.swift
@@ -19,7 +19,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
var reachabilityAlert : UIAlertController?
var reachabilityAlertShown = false
let internetReachability = Reachability.forInternetConnection()
-
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
@@ -29,13 +28,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
options: authOptions,
completionHandler: {_, _ in })
- //FIRMessaging.messaging().remoteMessageDelegate = self
-
FIRApp.configure()
application.registerForRemoteNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
-
NotificationCenter.default.addObserver(self,
selector: #selector(self.reachabilityChanged(note:)),
name: NSNotification.Name.reachabilityChanged,
@@ -91,12 +87,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
}
- func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
- // Print full message.
- }
-
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
- //self.scheduleLocalNotification()
completionHandler(UIBackgroundFetchResult.noData)
}
@@ -113,9 +104,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
UIApplication.shared.isNetworkActivityIndicatorVisible = true
switch response.actionIdentifier {
case ActionType.ACTION_DEEP_LINK :
- // open url
if let urlToOpen = response.notification.request.content.userInfo["appUrl"] { // until now we are considering anchor name (without the #)
- (self.window?.rootViewController as! ViewController).loadUrl(url: URL(string: String(format: "https://%@/%@%@", Server.hostURL, Server.navigationPath,urlToOpen as! String))!)
+ guard let urlRequest = URL(string:String(format: "https://%@/%@%@", Server.hostURL, Server.navigationPath,urlToOpen as! String)) else { return }
+ (self.window?.rootViewController as! ViewController).loadUrl(url:urlRequest)
NSLog("Action asked : %@",response.actionIdentifier)
}
case ActionType.ACTION_ACTUATOR :
@@ -187,7 +178,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
FIRMessaging.messaging().connect { (error) in
if (error != nil)
{
- //NSLog("Unable to connect with FCM. \(error)")
if let token = FIRInstanceID.instanceID().token() {
NSLog("Connected to FCM. Token is %@",token as String)
TokenManager.sharedInstance.storeDeviceId(token: token)
@@ -198,8 +188,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
if let token = FIRInstanceID.instanceID().token() {
NSLog("Connected to FCM. Token is %@",token as String)
TokenManager.sharedInstance.storeDeviceId(token: token)
- } else {
- // NSLog("Connected to FCM. Token is currently nil")
}
}
}
@@ -257,10 +245,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
} else {
completionHandler(.performDefaultHandling, nil)
}
-
}
}
-
}
diff --git a/console/iOS/console/Constants.swift b/console/iOS/console/Constants.swift
index 26bc355de..49c9ba3cd 100644
--- a/console/iOS/console/Constants.swift
+++ b/console/iOS/console/Constants.swift
@@ -18,6 +18,7 @@ enum Server {
static let hostURL = "192.168.0.177"
static let initialPath = String(format:"console/%@/",Server.realm)
static let navigationPath = String(format:"console/%@/#/",Server.realm)
+ static let navigationPath = String(format:"console/%@/",Server.realm)
static let realm = "blok61"
static let apiTestResource = String(format:"https://%@/%@/notification/alert",Server.hostURL,Server.realm)
// static let apiTestResource = String(format:"https://%@/%@/asset/user/current",Server.hostURL,Server.realm)
diff --git a/console/iOS/console/ORViewController.swift b/console/iOS/console/ORViewController.swift
index fba9b75d6..50f9cf153 100644
--- a/console/iOS/console/ORViewController.swift
+++ b/console/iOS/console/ORViewController.swift
@@ -43,8 +43,8 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if (navigationAction.request.url?.absoluteString.contains("logout"))! {
- decisionHandler(.allow)
TokenManager.sharedInstance.didLogOut = true
+ decisionHandler(.cancel)
self.dismiss(animated: false, completion: nil)
} else {
decisionHandler(.allow)
@@ -70,48 +70,6 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
decisionHandler(.allow)
}
-/*
- // just for testing purpose (ask backend to get list of notifications or send a notification to device)
- func apiCall() {
- UIApplication.shared.isNetworkActivityIndicatorVisible = true
- TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in
- switch accessTokenResult {
- case .Failure(let error) :
- UIApplication.shared.isNetworkActivityIndicatorVisible = false
- print(error ?? "")
- ErrorManager.showError(error: NSError(domain: "", code: 0, userInfo: [
- NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingapi", value: "Delete app and restart token probably expired", comment: "")
- ]))
-
- case .Success(let accessToken) :
- guard let urlRequest = URL(string: String(Server.apiTestResource)) else { return }
- let request = NSMutableURLRequest(url: urlRequest)
- request.httpMethod = "POST" // post to create a notification alert, get to get a list of notification alerts
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- request.httpBody = "{\"title\" :\" notif alert title\",\"message\" : \"notif alert message\",\"appUrl\" : \"Veilig\",\"actions\": [ {\"title\" : \"Open link\" , \"type\": \"ACTION_DEEP_LINK\"},{\"title\" : \"background call\" , \"type\": \"ACTION_ACTUATOR\" , \"assetId\" : \"2E2vrICRSEa6mfzOquZzxA\", \"attributeName\" : \"targetTemp\", \"rawJson\" : \"18\" } ]}".data(using: .utf8)
- request.addValue(String(format:"Bearer %@", accessToken!), forHTTPHeaderField: "Authorization")
- let sessionConfiguration = URLSessionConfiguration.default
- let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue : nil)
- let reqDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
- DispatchQueue.main.async {
- UIApplication.shared.isNetworkActivityIndicatorVisible = false
- if (error != nil) {
- NSLog("error %@", (error! as NSError).localizedDescription)
- let error = NSError(domain: "", code: 0, userInfo: [
- NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")
- ])
- ErrorManager.showError(error: error)
- } else {
- print(response.debugDescription)
- _ = self.myWebView?.load(data!, mimeType: "text/html", characterEncodingName: "utf8", baseURL: URL(string:Server.apiTestResource)!)
- }
- }
- })
- reqDataTask.resume()
- }
- }
- }
-*/
func login() {
guard let request = URL(string: String(format:"https://%@/%@",Server.hostURL,Server.initialPath)) else { return }
UIApplication.shared.isNetworkActivityIndicatorVisible = true
@@ -145,6 +103,7 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
+
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if challenge.protectionSpace.host == Server.hostURL {
diff --git a/console/iOS/console/TokenManager.swift b/console/iOS/console/TokenManager.swift
index c3dba5c80..f644e3e8e 100644
--- a/console/iOS/console/TokenManager.swift
+++ b/console/iOS/console/TokenManager.swift
@@ -20,7 +20,6 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
var viewController : TokenManagerViewController
var myWebView : WKWebView
var didLogOut : Bool = false
-
static let sharedInstance = TokenManager()
@@ -92,7 +91,11 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
myWebView.uiDelegate = self;
myWebView.navigationDelegate = self;
viewController.view.addSubview(myWebView)
- UIApplication.shared.keyWindow?.rootViewController?.present(viewController, animated: true, completion: nil)
+ if (UIApplication.shared.keyWindow?.rootViewController?.presentedViewController == nil) {
+ UIApplication.shared.keyWindow?.rootViewController?.present(viewController, animated: true, completion: nil)
+ }
+
+
guard let request = URL(string: String(format:"https://%@/%@",Server.hostURL,Server.initialPath)) else { return }
myWebView.load(URLRequest(url: request))
}
@@ -200,17 +203,20 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
}
}
+
func storeDeviceId(token : String) {
let defaults = UserDefaults(suiteName: AppGroup.entitlement)
if deviceId == nil || (deviceId != token){
deviceId = token
defaults?.set(token, forKey: DefaultsKey.deviceId)
+ TokenManager.sharedInstance.sendDeviceId()
} else {
deviceId = defaults?.object(forKey: DefaultsKey.deviceId) as! String?
}
}
func sendDeviceId() {
+ if (TokenManager.sharedInstance.deviceId != "" && TokenManager.sharedInstance.hasToken ) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.getAccessToken { (accessTokenResult) in
switch accessTokenResult {
@@ -238,6 +244,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
ErrorManager.showError(error: error)
} else {
if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 204 {
+ NSLog("Device not registred ",response.debugDescription)
let error = NSError(domain: "", code: 0, userInfo: [
NSLocalizedDescriptionKey : NSLocalizedString("ErrorSendingDeviceId", value: "Could not register your device for notifications", comment: "")
])
@@ -253,6 +260,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
reqDataTask.resume()
}
}
+ }
}
func getAccessToken(callback: @escaping (AccesTokenResult<String>) -> ()) {