Skip to content

armgit / core

Public Imported from GitHub
0

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

Restructured ORViewController and improved custom scheme handling

Michael Rademakerf83c3ce1f58e
diff --git a/console/iOS/ORLib/ORLib/ORSchemeHandler.swift b/console/iOS/ORLib/ORLib/ORSchemeHandler.swift
deleted file mode 100644
index 4a25d39d2..000000000
--- a/console/iOS/ORLib/ORLib/ORSchemeHandler.swift
+++ /dev/null
@@ -1,31 +0,0 @@
-//
-// ORSchemeHandler.swift
-// ORLib
-//
-// Created by Michael Rademaker on 24/06/2019.
-//
-
-import UIKit
-import WebKit
-
-class ORSchemeHandler: NSObject, WKURLSchemeHandler {
-
- public static let browserScheme = "webbrowser"
-
- func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
- if let url = urlSchemeTask.request.url, url.scheme == ORSchemeHandler.browserScheme {
- if var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
- components.scheme = "https"
- if let newUrl = components.url {
- UIApplication.shared.open(newUrl)
- }
- }
- urlSchemeTask.didReceive(URLResponse(url: url, mimeType: nil, expectedContentLength: -1, textEncodingName: nil))
- urlSchemeTask.didFinish()
- }
- }
-
- func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
- urlSchemeTask.didFailWithError(WKError(WKError.unknown))
- }
-}
diff --git a/console/iOS/ORLib/ORLib/ORViewController.swift b/console/iOS/ORLib/ORLib/ORViewController.swift
index 40a34ecd0..d4da1d6c8 100644
--- a/console/iOS/ORLib/ORLib/ORViewController.swift
+++ b/console/iOS/ORLib/ORLib/ORViewController.swift
@@ -22,7 +22,7 @@ import Foundation
import UIKit
import WebKit
-open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate {
+open class ORViewcontroller : UIViewController {
public var data : Data?
public var myWebView : WKWebView?
@@ -45,6 +45,169 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
self.configureAccess()
}
+ open func login() {
+ guard let request = URL(string: String(format:"\(ORServer.scheme)://%@/%@", ORServer.hostURL, ORServer.initialPath)) else { return }
+ UIApplication.shared.isNetworkActivityIndicatorVisible = true
+ _ = self.myWebView?.load(URLRequest(url: request))
+ isLoading = true
+ }
+
+ open func sendData(data: [String: Any?]) {
+ if let theJSONData = try? JSONSerialization.data(
+ withJSONObject: data,
+ options: []) {
+ let theJSONText = String(data: theJSONData,
+ encoding: .utf8)
+ let returnMessage = "OpenRemoteConsole._handleProviderResponse('\(theJSONText ?? "null")')"
+ DispatchQueue.main.async {
+ self.myWebView?.evaluateJavaScript("\(returnMessage)", completionHandler: { (any, error) in
+ print("JSON string = \(theJSONText!)")
+ })
+ }
+ }
+ }
+
+ open func configureAccess() {
+ let webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
+ let userController:WKUserContentController = WKUserContentController()
+
+ userController.add(self, name: "int")
+
+ let exec_template : String? = ""
+ let userScript:WKUserScript = WKUserScript(source: exec_template!, injectionTime: .atDocumentStart, forMainFrameOnly: true)
+ userController.addUserScript(userScript)
+
+ webCfg.userContentController = userController;
+ let sbHeight: CGFloat
+ if #available(iOS 11.0, *) {
+ sbHeight = UIApplication.shared.keyWindow?.safeAreaInsets.top ?? UIApplication.shared.statusBarFrame.height
+ } else {
+ sbHeight = UIApplication.shared.statusBarFrame.height
+ }
+ let webFrame = CGRect(x: 0, y: sbHeight, width: view.frame.size.width, height: view.frame.size.height - sbHeight)
+ myWebView = WKWebView(frame: webFrame, configuration: webCfg)
+ myWebView?.autoresizingMask = [.flexibleWidth, .flexibleHeight];
+ myWebView?.navigationDelegate = self;
+ //add observer to get estimated progress value
+ myWebView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil);
+
+ webProgressBar = UIProgressView(progressViewStyle: .bar)
+ webProgressBar?.progressTintColor = UIColor.mainColorAccent
+
+ view.addSubview(myWebView!)
+ view.addSubview(webProgressBar!)
+ view.bringSubviewToFront(webProgressBar!)
+
+ webProgressBar?.translatesAutoresizingMaskIntoConstraints = false
+ webProgressBar?.leadingAnchor.constraint(equalTo: myWebView!.leadingAnchor).isActive = true
+ webProgressBar?.trailingAnchor.constraint(equalTo: myWebView!.trailingAnchor).isActive = true
+ webProgressBar?.topAnchor.constraint(equalTo: myWebView!.topAnchor, constant: -2).isActive = true
+ webProgressBar?.heightAnchor.constraint(equalToConstant: 2).isActive = true
+ }
+
+ override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
+ if keyPath == "estimatedProgress" {
+ if let webView = myWebView {
+ webProgressBar?.progress = Float(webView.estimatedProgress);
+ }
+ }
+ }
+
+ func showProgressView() {
+ if let progressBar = webProgressBar {
+ UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
+ progressBar.alpha = 1
+ }, completion: nil)
+ }
+ }
+
+ func hideProgressView() {
+ if let progressBar = webProgressBar {
+ UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
+ progressBar.alpha = 0
+ }, completion: nil)
+ }
+ }
+
+ open func loadURL(url : URL) {
+ UIApplication.shared.isNetworkActivityIndicatorVisible = true
+ _ = self.myWebView?.load(URLRequest(url:url))
+ isLoading = true
+ }
+
+ internal func handleError(errorCode: Int, description: String, failingUrl: String, isForMainFrame: Bool) {
+ NSLog("%@", "Error requesting '\(failingUrl)': \(errorCode) (\(description))")
+
+ // This will be the URL loaded into the webview itself (false for images etc. of the main page)
+ if isForMainFrame {
+
+ // Check page load error URL
+ let errorUrl = ORServer.errorUrl
+ if let errorURL = URL(string: errorUrl), ORServer.errorUrl != failingUrl {
+ NSLog("%@", "Loading error URL: \(errorUrl)")
+ loadURL(url: errorURL)
+ }
+ } else {
+
+ if ORServer.ignorePageErrors {
+ return;
+ }
+
+ let error = NSError(domain: "", code: 0, userInfo: [
+ NSLocalizedDescriptionKey : NSLocalizedString("HTTPErrorReturned", value: "Connection Error", comment: "Error requesting '\(failingUrl)': \(errorCode) (\(description))")
+ ])
+ if let vc = self.presentingViewController as? ORLoginViewController {
+ vc.isInError = true
+ }
+ self.dismiss(animated: true) {
+ ErrorManager.showError(error:error)
+ }
+ }
+ }
+
+ open func updateAssetAttribute(assetId : String, attributeName : String, rawJson : String) {
+ UIApplication.shared.isNetworkActivityIndicatorVisible = true
+ TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in
+ switch accessTokenResult {
+ case .Failure(let error) :
+ UIApplication.shared.isNetworkActivityIndicatorVisible = false
+ self.handleError(errorCode: 0, description: error!.localizedDescription, failingUrl: "", isForMainFrame: false)
+ case .Success(let accessToken) :
+ guard let urlRequest = URL(string: String(String(format: "\(ORServer.scheme)://%@/%@/asset/%@/attribute/%@", ORServer.hostURL, ORServer.realm, assetId, attributeName))) else { return }
+ 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 {
+ UIApplication.shared.isNetworkActivityIndicatorVisible = false
+ if (error != nil) {
+ self.handleError(errorCode: 0, description: error!.localizedDescription, failingUrl: "", isForMainFrame: false)
+ }
+ }
+ })
+ reqDataTask.resume()
+ }
+ }
+ }
+}
+
+extension ORViewcontroller: URLSessionDelegate {
+ open func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
+ if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
+ if challenge.protectionSpace.host == ORServer.hostURL {
+ completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
+ } else {
+ completionHandler(.performDefaultHandling, nil)
+ }
+ }
+ }
+}
+
+extension ORViewcontroller: WKScriptMessageHandler {
open func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
let jsonDictionnary = message.body as? [String : Any]
if let type = jsonDictionnary?["type"] as? String {
@@ -156,22 +319,9 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
}
}
}
+}
- open func sendData(data: [String: Any?]) {
- if let theJSONData = try? JSONSerialization.data(
- withJSONObject: data,
- options: []) {
- let theJSONText = String(data: theJSONData,
- encoding: .utf8)
- let returnMessage = "OpenRemoteConsole._handleProviderResponse('\(theJSONText ?? "null")')"
- DispatchQueue.main.async {
- self.myWebView?.evaluateJavaScript("\(returnMessage)", completionHandler: { (any, error) in
- print("JSON string = \(theJSONText!)")
- })
- }
- }
- }
-
+extension ORViewcontroller: WKNavigationDelegate {
open func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
NSLog("error %@", message)
TokenManager.sharedInstance.resetTokenAndAuthenticate()
@@ -182,13 +332,21 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
showProgressView()
}
-
+
open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if (navigationAction.request.url?.absoluteString.contains("logout"))! {
TokenManager.sharedInstance.logout()
decisionHandler(.cancel)
self.dismiss(animated: false, completion: nil)
- } else {
+ } else if (navigationAction.request.url?.absoluteString.starts(with: "webbrowser"))! {
+ if let url = navigationAction.request.url, var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
+ components.scheme = "https"
+ if let newUrl = components.url {
+ UIApplication.shared.open(newUrl)
+ }
+ }
+ decisionHandler(.cancel)
+ } else {
let app = UIApplication.shared
if navigationAction.targetFrame == nil, let url = navigationAction.request.url{
if app.canOpenURL(url) {
@@ -201,7 +359,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
}
isLoading = false
}
-
+
open func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if let response = navigationResponse.response as? HTTPURLResponse {
if response.statusCode != 200 && response.statusCode != 204 {
@@ -219,14 +377,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
isLoading = false
decisionHandler(.allow)
}
-
- open func login() {
- guard let request = URL(string: String(format:"\(ORServer.scheme)://%@/%@", ORServer.hostURL, ORServer.initialPath)) else { return }
- UIApplication.shared.isNetworkActivityIndicatorVisible = true
- _ = self.myWebView?.load(URLRequest(url: request))
- isLoading = true
- }
-
+
open func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
NSLog("error %@", error.localizedDescription)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
@@ -245,7 +396,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
handleError(errorCode: 0, description: error.localizedDescription, failingUrl: webView.url?.absoluteString ?? "", isForMainFrame: true)
}
}
-
+
open func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if challenge.protectionSpace.host == ORServer.hostURL {
@@ -255,7 +406,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
}
}
}
-
+
open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
hideProgressView()
@@ -280,145 +431,6 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
}
hideProgressView()
}
-
- open func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
- if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
- if challenge.protectionSpace.host == ORServer.hostURL {
- completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
- } else {
- completionHandler(.performDefaultHandling, nil)
- }
- }
- }
-
- open func configureAccess() {
- let webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
- let userController:WKUserContentController = WKUserContentController()
-
- userController.add(self, name: "int")
-
- let exec_template : String? = ""
- let userScript:WKUserScript = WKUserScript(source: exec_template!, injectionTime: .atDocumentStart, forMainFrameOnly: true)
- userController.addUserScript(userScript)
-
- webCfg.userContentController = userController;
- let sbHeight: CGFloat
- if #available(iOS 11.0, *) {
- sbHeight = UIApplication.shared.keyWindow?.safeAreaInsets.top ?? UIApplication.shared.statusBarFrame.height
- } else {
- sbHeight = UIApplication.shared.statusBarFrame.height
- }
- webCfg.setURLSchemeHandler(ORSchemeHandler(), forURLScheme: ORSchemeHandler.browserScheme)
- let webFrame = CGRect(x: 0, y: sbHeight, width: view.frame.size.width, height: view.frame.size.height - sbHeight)
- myWebView = WKWebView(frame: webFrame, configuration: webCfg)
- myWebView?.autoresizingMask = [.flexibleWidth, .flexibleHeight];
- myWebView?.uiDelegate = self;
- myWebView?.navigationDelegate = self;
- //add observer to get estimated progress value
- myWebView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil);
-
- webProgressBar = UIProgressView(progressViewStyle: .bar)
- webProgressBar?.progressTintColor = UIColor.mainColorAccent
-
- view.addSubview(myWebView!)
- view.addSubview(webProgressBar!)
- view.bringSubviewToFront(webProgressBar!)
-
- webProgressBar?.translatesAutoresizingMaskIntoConstraints = false
- webProgressBar?.leadingAnchor.constraint(equalTo: myWebView!.leadingAnchor).isActive = true
- webProgressBar?.trailingAnchor.constraint(equalTo: myWebView!.trailingAnchor).isActive = true
- webProgressBar?.topAnchor.constraint(equalTo: myWebView!.topAnchor, constant: -2).isActive = true
- webProgressBar?.heightAnchor.constraint(equalToConstant: 2).isActive = true
- }
-
- override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
- if keyPath == "estimatedProgress" {
- if let webView = myWebView {
- webProgressBar?.progress = Float(webView.estimatedProgress);
- }
- }
- }
-
- func showProgressView() {
- if let progressBar = webProgressBar {
- UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
- progressBar.alpha = 1
- }, completion: nil)
- }
- }
-
- func hideProgressView() {
- if let progressBar = webProgressBar {
- UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
- progressBar.alpha = 0
- }, completion: nil)
- }
- }
-
- open func loadURL(url : URL) {
- UIApplication.shared.isNetworkActivityIndicatorVisible = true
- _ = self.myWebView?.load(URLRequest(url:url))
- isLoading = true
- }
-
- internal func handleError(errorCode: Int, description: String, failingUrl: String, isForMainFrame: Bool) {
- NSLog("%@", "Error requesting '\(failingUrl)': \(errorCode) (\(description))")
-
- // This will be the URL loaded into the webview itself (false for images etc. of the main page)
- if isForMainFrame {
-
- // Check page load error URL
- let errorUrl = ORServer.errorUrl
- if let errorURL = URL(string: errorUrl), ORServer.errorUrl != failingUrl {
- NSLog("%@", "Loading error URL: \(errorUrl)")
- loadURL(url: errorURL)
- }
- } else {
-
- if ORServer.ignorePageErrors {
- return;
- }
-
- let error = NSError(domain: "", code: 0, userInfo: [
- NSLocalizedDescriptionKey : NSLocalizedString("HTTPErrorReturned", value: "Connection Error", comment: "Error requesting '\(failingUrl)': \(errorCode) (\(description))")
- ])
- if let vc = self.presentingViewController as? ORLoginViewController {
- vc.isInError = true
- }
- self.dismiss(animated: true) {
- ErrorManager.showError(error:error)
- }
- }
- }
-
- open func updateAssetAttribute(assetId : String, attributeName : String, rawJson : String) {
- UIApplication.shared.isNetworkActivityIndicatorVisible = true
- TokenManager.sharedInstance.getAccessToken { (accessTokenResult) in
- switch accessTokenResult {
- case .Failure(let error) :
- UIApplication.shared.isNetworkActivityIndicatorVisible = false
- self.handleError(errorCode: 0, description: error!.localizedDescription, failingUrl: "", isForMainFrame: false)
- case .Success(let accessToken) :
- guard let urlRequest = URL(string: String(String(format: "\(ORServer.scheme)://%@/%@/asset/%@/attribute/%@", ORServer.hostURL, ORServer.realm, assetId, attributeName))) else { return }
- 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 {
- UIApplication.shared.isNetworkActivityIndicatorVisible = false
- if (error != nil) {
- self.handleError(errorCode: 0, description: error!.localizedDescription, failingUrl: "", isForMainFrame: false)
- }
- }
- })
- reqDataTask.resume()
- }
- }
- }
}
// Helper function inserted by Swift 4.2 migrator.