100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
iOS console : encapsulated reused code
William Balcaend7a8fb0cfdeb
diff --git a/console/iOS/console/Constants.swift b/console/iOS/console/Constants.swiftindex a4cc2fd79..8780fed0d 100644--- a/console/iOS/console/Constants.swift+++ b/console/iOS/console/Constants.swift@@ -8,9 +8,14 @@import Foundation+enum AccesTokenResult<String>+{+ case Success(String?)+ case Failure(NSError?)+}+enum Server {- static let hostURL = "192.168.0.138"- static let port = "8080"+ static let hostURL = "192.168.0.177"static let initialPath = String(format:"console/%@/index.html",Server.realm)static let realm = "blok61"static let apiTestResource = String(format:"https://%@/%@/notification/alert",Server.hostURL,Server.realm)diff --git a/console/iOS/console/ORViewController.swift b/console/iOS/console/ORViewController.swiftindex 9ff0a0a2f..f5bfbc223 100644--- a/console/iOS/console/ORViewController.swift+++ b/console/iOS/console/ORViewController.swift@@ -75,76 +75,36 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa// just for testing purpose (ask backend to get list of notifications or send a notification to device)func apiCall() {- guard let tkurlRequest = URL(string: String(format:"https://%@/auth/realms/%@/protocol/openid-connect/token",Server.hostURL,Server.realm)) 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=%@",(TokenManager.sharedInstance.refreshToken )!,Client.clientId)- tkRequest.httpBody = postString.data(using: .utf8)- let sessionConfiguration = URLSessionConfiguration.default- let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)- let req = session.dataTask(with: tkRequest as URLRequest, completionHandler: { (data, response, error) in- if (data != nil){- do {- let jsonDictionnary: Dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]- if ((jsonDictionnary["access_token"]) != nil) {- guard let urlRequest = URL(string: String(Server.apiTestResource)) else { return }- let request = NSMutableURLRequest(url: urlRequest)- request.httpMethod = "GET" // 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\" : \"http://www.openremote.org\",\"actions\": [ {\"title\" : \"Open link\" , \"type\": \"ACTION_DEEP_LINK\"},{\"title\" : \"background call\" , \"type\": \"ACTION_ACTUATOR\" , \"assetId\" : \"9sGrlb-CSZWgOeUCTYZ9Yw\", \"attributeName\" : \"targetTemp\", \"rawJson\" : \"45\" } ]}".data(using: .utf8)- request.addValue(String(format:"Bearer %@", jsonDictionnary["access_token"] as! String), 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 {- 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: "")- ])- self.showError(error: error)- } else {- print(response.debugDescription)- _ = self.myWebView?.load(data!, mimeType: "text/html", characterEncodingName: "utf8", baseURL: URL(string:Server.apiTestResource)!)- }- }- })- reqDataTask.resume()+ TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in+ switch accessTokenResult {+ case .Failure(let error) :+ self.showError(error: error!)+ case .Success(let accessToken) :+ guard let urlRequest = URL(string: String(Server.apiTestResource)) else { return }+ let request = NSMutableURLRequest(url: urlRequest)+ request.httpMethod = "GET" // 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\" : \"http://www.openremote.org\",\"actions\": [ {\"title\" : \"Open link\" , \"type\": \"ACTION_DEEP_LINK\"},{\"title\" : \"background call\" , \"type\": \"ACTION_ACTUATOR\" , \"assetId\" : \"9sGrlb-CSZWgOeUCTYZ9Yw\", \"attributeName\" : \"targetTemp\", \"rawJson\" : \"45\" } ]}".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 {+ 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: "")+ ])+ self.showError(error: error)} else {- if let httpResponse = response as? HTTPURLResponse {- NSLog("error %@", httpResponse)- let error = NSError(domain: "", code: httpResponse.statusCode, userInfo: [- NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")- ])- self.showError(error: error)- } else {- if (error != nil) {- NSLog("error %@", (error as! NSError).localizedDescription as String)- }- let error = NSError(domain: "", code: 0, userInfo: [- NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")- ])- self.showError(error: error)- }+ print(response.debugDescription)+ _ = self.myWebView?.load(data!, mimeType: "text/html", characterEncodingName: "utf8", baseURL: URL(string:Server.apiTestResource)!)}}- catch let error as NSError {- NSLog("error %@", error.localizedDescription)- let error = NSError(domain: "", code: 0, userInfo: [- NSLocalizedDescriptionKey : NSLocalizedString("ErrorDeserializingJSON", value: "Could not convert received data", comment: "")- ])- self.showError(error: error)- }- } else {- NSLog("error %@", (error as! NSError).localizedDescription)- let error = NSError(domain: "", code: 0, userInfo: [- NSLocalizedDescriptionKey : NSLocalizedString("NoDataReceived", value: "Did not receive any data", comment: "")- ])- self.showError(error: error)- }- })- req.resume()+ })+ reqDataTask.resume()+ }+ }}func login() {@@ -214,78 +174,37 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa}func updateAssetAttribute(assetId : String, attributeName : String, rawJson : String) {- guard let tkurlRequest = URL(string: String(format:"https://%@/auth/realms/%@/protocol/openid-connect/token",Server.hostURL,Server.realm)) 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=%@",(TokenManager.sharedInstance.refreshToken )!,Client.clientId)- tkRequest.httpBody = postString.data(using: .utf8)- let sessionConfiguration = URLSessionConfiguration.default- let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)- let req = session.dataTask(with: tkRequest as URLRequest, completionHandler: { (data, response, error) in- if (data != nil){- do {- let jsonDictionnary: Dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]- if ((jsonDictionnary["access_token"]) != nil) {- guard let urlRequest = URL(string: String(String(format: "https://%@/%@/asset/%@/attribute/%@", Server.hostURL, Server.realm, assetId,attributeName))) else { return }- print(urlRequest)- let request = NSMutableURLRequest(url: urlRequest)- request.httpMethod = "PUT"- request.addValue("application/json", forHTTPHeaderField: "Content-Type")- request.httpBody = rawJson.data(using: .utf8)- request.addValue(String(format:"Bearer %@", jsonDictionnary["access_token"] as! String), 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 {- 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: "")- ])- self.showError(error: error)- } else {- print(response.debugDescription)- _ = self.myWebView?.load(data!, mimeType: "text/html", characterEncodingName: "utf8", baseURL: URL(string:Server.apiTestResource)!)- }- }- })- reqDataTask.resume()+ TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in+ switch accessTokenResult {+ case .Failure(let error) :+ self.showError(error: error!)+ case .Success(let accessToken) :+ guard let urlRequest = URL(string: String(String(format: "https://%@/%@/asset/%@/attribute/%@", Server.hostURL, Server.realm, assetId,attributeName))) else { return }+ print(urlRequest)+ let request = NSMutableURLRequest(url: urlRequest)+ request.httpMethod = "PUT"+ request.addValue("application/json", forHTTPHeaderField: "Content-Type")+ request.httpBody = rawJson.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 {+ 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: "")+ ])+ self.showError(error: error)} else {- if let httpResponse = response as? HTTPURLResponse {- NSLog("error %@", httpResponse)- let error = NSError(domain: "", code: httpResponse.statusCode, userInfo: [- NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")- ])- self.showError(error: error)- } else {- if (error != nil) {- NSLog("error %@", (error as! NSError).localizedDescription as String)- }- let error = NSError(domain: "", code: 0, userInfo: [- NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")- ])- self.showError(error: error)- }+ print(response.debugDescription)+ _ = self.myWebView?.load(data!, mimeType: "text/html", characterEncodingName: "utf8", baseURL: URL(string:Server.apiTestResource)!)}}- catch let error as NSError {- NSLog("error %@", error.localizedDescription)- let error = NSError(domain: "", code: 0, userInfo: [- NSLocalizedDescriptionKey : NSLocalizedString("ErrorDeserializingJSON", value: "Could not convert received data", comment: "")- ])- self.showError(error: error)- }- } else {- NSLog("error %@", (error as! NSError).localizedDescription)- let error = NSError(domain: "", code: 0, userInfo: [- NSLocalizedDescriptionKey : NSLocalizedString("NoDataReceived", value: "Did not receive any data", comment: "")- ])- self.showError(error: error)- }- })- req.resume()-+ })+ reqDataTask.resume()+ }+ }}diff --git a/console/iOS/console/TokenManager.swift b/console/iOS/console/TokenManager.swiftindex 34294322e..72efd5a1a 100644--- a/console/iOS/console/TokenManager.swift+++ b/console/iOS/console/TokenManager.swift@@ -10,7 +10,7 @@ import Foundationimport UIKitimport WebKit-class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate {+class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate, URLSessionDelegate {var offlineToken : String?var refreshToken : String?@@ -184,6 +184,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD}func sendDeviceId() {+ func getAccessToken(callback: @escaping (AccesTokenResult<String>) -> ()) {guard let tkurlRequest = URL(string: String(format:"https://%@/auth/realms/%@/protocol/openid-connect/token",Server.hostURL,Server.realm)) else { return }let tkRequest = NSMutableURLRequest(url: tkurlRequest)tkRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");@@ -191,50 +192,20 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationDlet postString = String(format:"grant_type=refresh_token&refresh_token=%@&client_id=%@",(TokenManager.sharedInstance.refreshToken )!,Client.clientId)tkRequest.httpBody = postString.data(using: .utf8)let sessionConfiguration = URLSessionConfiguration.default- let session = URLSession(configuration: sessionConfiguration)+ let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)let req = session.dataTask(with: tkRequest as URLRequest, completionHandler: { (data, response, error) inif (data != nil){do {let jsonDictionnary: Dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]if ((jsonDictionnary["access_token"]) != nil) {- guard let urlRequest = URL(string: String(Server.registerDeviceResource)) else { return }- 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=%@", FCM.serverKey, TokenManager.sharedInstance.deviceId!)- request.httpBody = postString.data(using: .utf8)- request.addValue(String(format:"Bearer %@", jsonDictionnary["access_token"] as! String), forHTTPHeaderField: "Authorization")- let sessionConfiguration = URLSessionConfiguration.default- let session = URLSession(configuration: sessionConfiguration)- let reqDataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in- DispatchQueue.main.async {- 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: "")- ])- self.showError(error: error)- } else {- if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 204 {- let error = NSError(domain: "", code: 0, userInfo: [- NSLocalizedDescriptionKey : NSLocalizedString("ErrorSendingDeviceId", value: "Could not register your device for notifications", comment: "")- ])- self.showError(error: error)- } else {- NSLog("Device registred")- self.isDeviceIdSend = true- }- }- }- })- reqDataTask.resume()+ callback(AccesTokenResult.Success(jsonDictionnary["access_token"] as? String))} else {if let httpResponse = response as? HTTPURLResponse {NSLog("error %@", httpResponse)let error = NSError(domain: "", code: httpResponse.statusCode, userInfo: [NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")])- self.showError(error: error)+ callback(AccesTokenResult.Failure(error))} else {if (error != nil) {NSLog("error %@", (error as! NSError).localizedDescription as String)@@ -242,7 +213,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationDlet error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : NSLocalizedString("ErrorCallingAPI", value: "Could not get data", comment: "")])- self.showError(error: error)+ callback(AccesTokenResult.Failure(error))}}}@@ -251,27 +222,27 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationDlet error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : NSLocalizedString("ErrorDeserializingJSON", value: "Could not convert received data", comment: "")])- self.showError(error: error)+ callback(AccesTokenResult.Failure(error))}} else {NSLog("error %@", (error as! NSError).localizedDescription)let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : NSLocalizedString("NoDataReceived", value: "Did not receive any data", comment: "")])- self.showError(error: error)+ callback(AccesTokenResult.Failure(error))}})req.resume()}- func showError(error : Error) {- NSLog("showing error %@",error as NSError)- let alertVC = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)- let alertAction = UIAlertAction(title: "Done", style: .cancel) { (action) in- self.viewController.dismiss(animated: true, completion: nil)+ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {+ if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {+ if challenge.protectionSpace.host == Server.hostURL {+ completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))+ } else {+ completionHandler(.performDefaultHandling, nil)+ }+}-- alertVC.addAction(alertAction)- viewController.present(alertVC, animated: true, completion: nil)}}