Skip to content

armgit / core

Public Imported from GitHub
0

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

Improved geofenceing capabilities. Better error handeling

Michael Rademaker91e1624f5b27
diff --git a/console/iOS/ORLib/ORLib.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate b/console/iOS/ORLib/ORLib.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate
index 1bd3c4be8..7b39e1597 100644
Binary files a/console/iOS/ORLib/ORLib.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate and b/console/iOS/ORLib/ORLib.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate differ
diff --git a/console/iOS/ORLib/ORLib/GeofenceProvider.swift b/console/iOS/ORLib/ORLib/GeofenceProvider.swift
index 19f92f661..11d09abc3 100644
--- a/console/iOS/ORLib/ORLib/GeofenceProvider.swift
+++ b/console/iOS/ORLib/ORLib/GeofenceProvider.swift
@@ -10,11 +10,9 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
let version = "ORConsole"
let geofenceFetchEndpoint = "rules/geofences/"
let locationManager = CLLocationManager()
- let userdefaults = UserDefaults.standard
+ let userdefaults = UserDefaults(suiteName: ORAppGroup.entitlement)
var geoPostUrls = [String:[String]]()
var enableCallback : (([String: Any]) -> (Void))?
- var timer: Timer?
- var insideRegion = false
public var baseURL: String = ""
public var consoleId: String = ""
@@ -26,9 +24,12 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
public override init() {
super.init()
locationManager.delegate = self
- self.baseURL = userdefaults.string(forKey: GeofenceProvider.baseUrlKey) ?? ""
- self.consoleId = userdefaults.string(forKey: GeofenceProvider.consoleIdKey) ?? ""
- self.geoPostUrls = userdefaults.value(forKey: GeofenceProvider.geoPostUrlsKey) as? [String:[String]] ?? [String:[String]]()
+ locationManager.allowsBackgroundLocationUpdates = true
+ locationManager.pausesLocationUpdatesAutomatically = false
+ locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
+ self.baseURL = userdefaults?.string(forKey: GeofenceProvider.baseUrlKey) ?? ""
+ self.consoleId = userdefaults?.string(forKey: GeofenceProvider.consoleIdKey) ?? ""
+ self.geoPostUrls = userdefaults?.value(forKey: GeofenceProvider.geoPostUrlsKey) as? [String:[String]] ?? [String:[String]]()
}
public func initialize() -> [String: Any] {
@@ -59,8 +60,8 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
let region = CLCircularRegion(center: CLLocationCoordinate2DMake(geofence.lat, geofence.lng), radius: geofence.radius, identifier:geofence.id)
locationManager.startMonitoring(for: region)
geoPostUrls[geofence.id] = [geofence.httpMethod, geofence.url]
- userdefaults.set(geoPostUrls, forKey: GeofenceProvider.geoPostUrlsKey)
- userdefaults.synchronize()
+ userdefaults?.set(geoPostUrls, forKey: GeofenceProvider.geoPostUrlsKey)
+ userdefaults?.synchronize()
}
public func removeGeofence(id: String) {
@@ -68,8 +69,8 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
guard let circularRegion = region as? CLCircularRegion, circularRegion.identifier == id else {continue}
locationManager.stopMonitoring(for: circularRegion)
geoPostUrls.removeValue(forKey: circularRegion.identifier)
- userdefaults.set(geoPostUrls, forKey: GeofenceProvider.geoPostUrlsKey)
- userdefaults.synchronize()
+ userdefaults?.set(geoPostUrls, forKey: GeofenceProvider.geoPostUrlsKey)
+ userdefaults?.synchronize()
break
}
}
@@ -79,18 +80,19 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
locationManager.stopMonitoring(for: region)
}
geoPostUrls = [String:[String]]()
- userdefaults.set(geoPostUrls, forKey: GeofenceProvider.geoPostUrlsKey)
- userdefaults.synchronize()
+ userdefaults?.set(geoPostUrls, forKey: GeofenceProvider.geoPostUrlsKey)
+ userdefaults?.synchronize()
}
public func enable(baseUrl: String, consoleId: String, callback:@escaping ([String: Any]) ->(Void)) {
self.baseURL = baseUrl
self.consoleId = consoleId
- userdefaults.set(self.baseURL, forKey: GeofenceProvider.baseUrlKey)
- userdefaults.set(self.consoleId, forKey: GeofenceProvider.consoleIdKey)
- userdefaults.synchronize()
+ userdefaults?.set(self.baseURL, forKey: GeofenceProvider.baseUrlKey)
+ userdefaults?.set(self.consoleId, forKey: GeofenceProvider.consoleIdKey)
+ userdefaults?.synchronize()
enableCallback = callback
if checkPermission() {
+ self.locationManager.startMonitoringSignificantLocationChanges()
enableCallback?([
DefaultsKey.actionKey: Actions.providerEnable,
DefaultsKey.providerKey: Providers.geofence,
@@ -111,8 +113,8 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
}
}
- public func disbale()-> [String: Any] {
- timer?.invalidate()
+ public func disable()-> [String: Any] {
+ locationManager.stopMonitoringSignificantLocationChanges()
return [
DefaultsKey.actionKey: "PROVIDER_DISABLE",
DefaultsKey.providerKey: Providers.geofence
@@ -136,6 +138,7 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
return
}
self.clearAllRegions()
+ NSLog("%@", "Geofences count: \(geofences.count)")
print("Geofences count: \(geofences.count)")
for geofence in geofences {
self.addGeofence(geofence: geofence)
@@ -146,7 +149,7 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
let error = NSError(domain: "", code: 0, userInfo: [
NSLocalizedDescriptionKey : NSLocalizedString("NoDataReceived", value: "Did not receive any data", comment: "")
])
- print(error)
+ NSLog("%@", error)
callback?([])
}
})
@@ -170,7 +173,7 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
if !sendQueued {
sendQueued = true
- DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
+ DispatchQueue.global().async {
self.doSendLocation()
}
}
@@ -229,14 +232,14 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
let semaphore = DispatchSemaphore(value: 0)
let sessionConfiguration = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
- let req = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
+ let req = session.dataTask(with: request as URLRequest, completionHandler: { (responseData, response, error) in
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 204 {
- print("sendLocation succeded")
+ NSLog("%@", "sendLocation succeded with data: \(String(describing: data))")
succes = true
} else {
- print("sendLocation failed")
- if error != nil {
- print(error!)
+ NSLog("%@", "sendLocation failed")
+ if let err = error as NSError? {
+ NSLog("%@", err)
}
}
semaphore.signal()
@@ -268,7 +271,8 @@ public class GeofenceProvider: NSObject, URLSessionDelegate {
extension GeofenceProvider: CLLocationManagerDelegate {
public func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
- print("Entered geofence with id: \(region.identifier)")
+ NSLog("%@", "Entered geofence with id: \(region.identifier)")
+
guard let circularRegion = region as? CLCircularRegion else {return}
let postData = [
@@ -280,7 +284,8 @@ extension GeofenceProvider: CLLocationManagerDelegate {
}
public func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
- print("Exited geofence with id: \(region.identifier)")
+ NSLog("%@", "Exited geofence with id: \(region.identifier)")
+
guard let circularRegion = region as? CLCircularRegion else {return}
queueSendLocation(geofenceId: circularRegion.identifier, data: nil)
@@ -294,6 +299,8 @@ extension GeofenceProvider: CLLocationManagerDelegate {
DefaultsKey.hasPermissionKey: checkPermission(),
DefaultsKey.successKey: true
])
+ } else if status == .authorizedAlways {
+ self.locationManager.startMonitoringSignificantLocationChanges()
}
}
}
diff --git a/console/iOS/ORLib/ORLib/ORAppDelegate.swift b/console/iOS/ORLib/ORLib/ORAppDelegate.swift
index ae7faf470..ea4267727 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 CoreLocation
@UIApplicationMain
open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate {
@@ -32,18 +33,31 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
public var reachabilityAlertShown = false
public let internetReachability = Reachability()
+ private var geofenceProvider : GeofenceProvider?
+
open func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
+ 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")
// create new GeofenceProvider which creates a CLLocationManager that will receive the location update
- _ = GeofenceProvider()
+ geofenceProvider = GeofenceProvider()
+ if CLLocationManager.authorizationStatus() == .authorizedAlways {
+ geofenceProvider?.locationManager.startMonitoringSignificantLocationChanges()
+ }
} else {
- UNUserNotificationCenter.current().delegate = self
-
FirebaseApp.configure()
Messaging.messaging().delegate = self
- application.registerForRemoteNotifications()
NotificationCenter.default.addObserver(self,
selector: #selector(self.reachabilityChanged(note:)),
name: NSNotification.Name.reachabilityChanged,
@@ -52,7 +66,7 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
try internetReachability?.startNotifier()
self.updateReachabilityStatus(reachability: internetReachability!)
} catch {
- print("Unable to start notifier")
+ NSLog("%@", "Unable to start notifier")
}
}
return true
@@ -81,7 +95,7 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
try self.internetReachability?.startNotifier()
self.updateReachabilityStatus(reachability: self.internetReachability!)
} catch {
- print("Unable to start notifier")
+ NSLog("%@", "Unable to start notifier")
}
}
}
@@ -93,7 +107,7 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
try self.internetReachability?.startNotifier()
self.updateReachabilityStatus(reachability: self.internetReachability!)
} catch {
- print("Unable to start notifier")
+ NSLog("%@", "Unable to start notifier")
}
}
}
@@ -116,10 +130,11 @@ open class ORAppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate
}
}
if let notificationIdString = userInfo[ActionType.notificationId] as? String, let notificationId = Int64(notificationIdString) {
- if let consoleId = UserDefaults.standard.string(forKey: GeofenceProvider.consoleIdKey) {
+ if let defaults = UserDefaults(suiteName: ORAppGroup.entitlement), let consoleId = defaults.string(forKey: GeofenceProvider.consoleIdKey) {
ORNotificationResource.sharedInstance.notificationDelivered(notificationId: notificationId, targetId: consoleId)
}
}
+
completionHandler(UIBackgroundFetchResult.newData)
}
@@ -182,13 +197,12 @@ 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
- let consoleId = UserDefaults.standard.string(forKey: GeofenceProvider.consoleIdKey)
if let notificationIdString = userInfo[ActionType.notificationId] as? String{
notificationId = Int64(notificationIdString)
}
- if let notiId = notificationId, let conId = consoleId {
- ORNotificationResource.sharedInstance.notificationDelivered(notificationId: notiId, targetId: conId)
+ if let notiId = notificationId, let defaults = UserDefaults(suiteName: ORAppGroup.entitlement), let consoleId = defaults.string(forKey: GeofenceProvider.consoleIdKey) {
+ ORNotificationResource.sharedInstance.notificationDelivered(notificationId: notiId, targetId: consoleId)
}
completionHandler([.alert, .sound])
@@ -198,16 +212,22 @@ extension ORAppDelegate : UNUserNotificationCenterDelegate {
let userInfo = response.notification.request.content.userInfo
var notificationId : Int64? = nil
- let consoleId = UserDefaults.standard.string(forKey: GeofenceProvider.consoleIdKey)
+ var consoleId : String?
if let notificationIdString = userInfo[ActionType.notificationId] as? String{
notificationId = Int64(notificationIdString)
}
+ if let defaults = UserDefaults(suiteName: ORAppGroup.entitlement) {
+ consoleId = defaults.string(forKey: GeofenceProvider.consoleIdKey);
+ }
+
+ NSLog("%@", "Action chosen: \(response.actionIdentifier)")
+
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
if let notiId = notificationId, let conId = consoleId {
- ORNotificationResource.sharedInstance.notificationAcknowledged(notificationId: notiId, targetId: conId, acknowledgement: "CLOSED")
+ ORNotificationResource.sharedInstance.notificationDelivered(notificationId: notiId, targetId: conId)
}
if let urlToOpen = userInfo[ActionType.appUrl] as? String {
@@ -217,11 +237,13 @@ extension ORAppDelegate : UNUserNotificationCenterDelegate {
} else {
urlRequest = URL(string:String(format: "%@://%@/%@%@", ORServer.scheme, ORServer.hostURL, ORServer.navigationPath, urlToOpen))
}
- if let request = urlRequest{
+ if let url = urlRequest{
if let openInBrowser = userInfo[ActionType.openInBrowser] as? Bool, openInBrowser {
- UIApplication.shared.open(request)
+ NSLog("%@", "Open in browser: \(url)")
+ UIApplication.shared.open(url)
} else {
- (self.window?.rootViewController as! ORViewcontroller).loadURL(url:request)
+ NSLog("%@", "Open in app: \(url)")
+ (self.window?.rootViewController as! ORViewcontroller).loadURL(url:url)
}
}
}
@@ -261,14 +283,16 @@ extension ORAppDelegate : UNUserNotificationCenterDelegate {
}
})
reqDataTask.resume()
-
} else if action.openInBrowser {
+ NSLog("%@", "Open in browser: \(url)")
UIApplication.shared.open(url)
} else {
+ NSLog("%@", "Open in app: \(url)")
(self.window?.rootViewController as! ORViewcontroller).loadURL(url:url)
}
}
}
+ break
}
}
}
diff --git a/console/iOS/ORLib/ORLib/ORNotificationService.swift b/console/iOS/ORLib/ORLib/ORNotificationService.swift
index 2fa803411..a2837666e 100644
--- a/console/iOS/ORLib/ORLib/ORNotificationService.swift
+++ b/console/iOS/ORLib/ORLib/ORNotificationService.swift
@@ -20,7 +20,7 @@
import UserNotifications
-open class ORNotificationService: UNNotificationServiceExtension, URLSessionDelegate {
+open class ORNotificationService: UNNotificationServiceExtension {
public var contentHandler: ((UNNotificationContent) -> Void)?
public var bestAttemptContent: UNMutableNotificationContent?
@@ -28,42 +28,17 @@ open class ORNotificationService: UNNotificationServiceExtension, URLSessionDele
open override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
- print("NotifExtension Change content : %@ ", bestAttemptContent?.userInfo ?? "")
+
if let bestAttemptContent = bestAttemptContent {
- print(bestAttemptContent.userInfo)
- if let notificationIdString = bestAttemptContent.userInfo[ActionType.notificationId] as? String, let notificationId = Int64(notificationIdString) {
- if let consoleId = UserDefaults.standard.string(forKey: GeofenceProvider.consoleIdKey) {
- ORNotificationResource.sharedInstance.notificationDelivered(notificationId: notificationId, targetId: consoleId)
- }
- }
-
- //Actions
- if let actionString = bestAttemptContent.userInfo[DefaultsKey.actionKey] as? String {
- if let actionsData = actionString.data(using: .utf8){
- if let action = try? JSONDecoder().decode(ORPushNotificationAction.self, from: actionsData) {
- let categoryName = "openremoteNotification"
- bestAttemptContent.categoryIdentifier = categoryName
-
- bestAttemptContent.userInfo[ActionType.appUrl] = action.url
- bestAttemptContent.userInfo[ActionType.silent] = action.silent
- bestAttemptContent.userInfo[ActionType.openInBrowser] = action.openInBrowser
- bestAttemptContent.userInfo[ActionType.httpMethod] = action.httpMethod ?? "GET"
- bestAttemptContent.userInfo[DefaultsKey.dataKey] = action.data ?? "null"
- let category = UNNotificationCategory(identifier: categoryName, actions: [], intentIdentifiers: [], options: [])
- let categories : Set = [category]
- UNUserNotificationCenter.current().setNotificationCategories(categories)
- }
- }
- }
+ let categoryName = "openremoteNotification"
+ bestAttemptContent.categoryIdentifier = categoryName
//Buttons
if let buttonsString = bestAttemptContent.userInfo[DefaultsKey.buttonsKey] as? String {
if let buttonsData = buttonsString.data(using: .utf8) {
if let buttons = try? JSONDecoder().decode([ORPushNotificationButton].self, from: buttonsData) {
- let categoryName = "openremoteNotification"
- bestAttemptContent.categoryIdentifier = categoryName
var notificationActions = [UNNotificationAction]()
for button in buttons {
@@ -80,7 +55,27 @@ open class ORNotificationService: UNNotificationServiceExtension, URLSessionDele
}
}
}
- contentHandler(bestAttemptContent)
+ //Actions
+ if let actionString = bestAttemptContent.userInfo[DefaultsKey.actionKey] as? String {
+ if let actionsData = actionString.data(using: .utf8){
+ if let action = try? JSONDecoder().decode(ORPushNotificationAction.self, from: actionsData) {
+
+ bestAttemptContent.userInfo[ActionType.appUrl] = action.url
+ bestAttemptContent.userInfo[ActionType.silent] = action.silent
+ bestAttemptContent.userInfo[ActionType.openInBrowser] = action.openInBrowser
+ bestAttemptContent.userInfo[ActionType.httpMethod] = action.httpMethod ?? "GET"
+ bestAttemptContent.userInfo[DefaultsKey.dataKey] = action.data ?? "null"
+ }
+ }
+ }
+
+ if let notificationIdString = bestAttemptContent.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)
+ }
+ }
+
+ contentHandler(bestAttemptContent.copy() as! UNNotificationContent)
}
}
@@ -90,19 +85,20 @@ open class ORNotificationService: UNNotificationServiceExtension, URLSessionDele
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
NSLog("NotifExtension Time has expired")
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
- bestAttemptContent.title = "You received an alarm from blok61 :"
- bestAttemptContent.body = "Please open application to check what's happening"
- contentHandler(bestAttemptContent)
- }
- }
+ //Actions
+ if let actionString = bestAttemptContent.userInfo[DefaultsKey.actionKey] as? String {
+ if let actionsData = actionString.data(using: .utf8){
+ if let action = try? JSONDecoder().decode(ORPushNotificationAction.self, from: actionsData) {
- 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)
+ bestAttemptContent.userInfo[ActionType.appUrl] = action.url
+ bestAttemptContent.userInfo[ActionType.silent] = action.silent
+ bestAttemptContent.userInfo[ActionType.openInBrowser] = action.openInBrowser
+ bestAttemptContent.userInfo[ActionType.httpMethod] = action.httpMethod ?? "GET"
+ bestAttemptContent.userInfo[DefaultsKey.dataKey] = action.data ?? "null"
+ }
+ }
}
+ contentHandler(bestAttemptContent)
}
}
}
diff --git a/console/iOS/ORLib/ORLib/ORViewController.swift b/console/iOS/ORLib/ORLib/ORViewController.swift
index f5adeae2e..952ab3973 100644
--- a/console/iOS/ORLib/ORLib/ORViewController.swift
+++ b/console/iOS/ORLib/ORLib/ORViewController.swift
@@ -28,6 +28,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
public var myWebView : WKWebView?
public var defaults : UserDefaults?
public var webCfg : WKWebViewConfiguration?
+ public var isLoading = false
var geofenceProvider: GeofenceProvider?
var pushProvider: PushNotificationProvider?
@@ -83,7 +84,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
if let consoleId = data[GeofenceProvider.consoleIdKey] {
geofenceProvider?.enable(baseUrl: "\(ORServer.baseUrl)\(ORServer.realm)", consoleId: consoleId, callback: { enableData in
self.sendData(data: enableData)
- DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
+ DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) {
self.geofenceProvider?.fetchGeofences()
}
})
@@ -92,7 +93,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
} else if action == Actions.geofenceRefresh {
geofenceProvider?.refreshGeofences()
} else if action == Actions.providerDisable {
- if let disableData = geofenceProvider?.disbale() {
+ if let disableData = geofenceProvider?.disable() {
sendData(data: disableData)
}
}
@@ -159,6 +160,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
decisionHandler(.allow)
}
}
+ isLoading = false
}
open func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
@@ -166,18 +168,12 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
if response.statusCode != 200 && response.statusCode != 204 {
decisionHandler(.cancel)
- let error = NSError(domain: "", code: 0, userInfo: [
- NSLocalizedDescriptionKey : NSLocalizedString("HTTPErrorReturned", value: "Connection Error", comment: "")
- ])
- if let vc = self.presentingViewController as? ORLoginViewController {
- vc.isInError = true
- }
- self.dismiss(animated: true) {
- ErrorManager.showError(error:error)
- }
+ isLoading = false
+ handleError(errorCode: response.statusCode, description: "Error in request", failingUrl: response.url?.absoluteString ?? "", isForMainFrame: true)
return
}
}
+ isLoading = false
decisionHandler(.allow)
}
@@ -185,18 +181,25 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
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
- if let vc = self.presentingViewController as? ORLoginViewController {
- vc.isInError = true
- }
- self.dismiss(animated: true) {
- ErrorManager.showError(error: NSError(domain: "networkError", code: 0, userInfo:[
- NSLocalizedDescriptionKey : NSLocalizedString("FailedLoadingPage", value: "Could not load page in OR", comment: "")
- ]))
+ if let err = error as? URLError {
+
+ let httpCode: Int
+ switch(err.code) {
+ case .cannotFindHost:
+ httpCode = 404
+ default:
+ httpCode = 500
+ }
+
+ handleError(errorCode: httpCode, description: err.localizedDescription, failingUrl: err.failureURLString ?? "", isForMainFrame: true)
+ } else {
+ handleError(errorCode: 0, description: error.localizedDescription, failingUrl: webView.url?.absoluteString ?? "", isForMainFrame: true)
}
}
@@ -247,6 +250,37 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
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) {
@@ -255,7 +289,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
switch accessTokenResult {
case .Failure(let error) :
UIApplication.shared.isNetworkActivityIndicatorVisible = false
- ErrorManager.showError(error: error!)
+ 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)
@@ -269,11 +303,7 @@ open class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMess
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)
+ self.handleError(errorCode: 0, description: error!.localizedDescription, failingUrl: "", isForMainFrame: false)
}
}
})
diff --git a/console/iOS/ORLib/ORLib/ProjectConstants.swift b/console/iOS/ORLib/ORLib/ProjectConstants.swift
index c8ba0f43a..fb88011e4 100644
--- a/console/iOS/ORLib/ORLib/ProjectConstants.swift
+++ b/console/iOS/ORLib/ORLib/ProjectConstants.swift
@@ -28,6 +28,8 @@ public enum ORServer {
public static var realm = "openremote"
public static var baseUrl = "\(ORServer.scheme)://\(ORServer.hostURL)/"
public static var apiTestResource = String(format:"\(ORServer.scheme)://%@/%@/notification/alert",ORServer.hostURL,ORServer.realm)
+ public static var errorUrl = ""
+ public static var ignorePageErrors = false
public static var registerDeviceResource = String(format:"\(ORServer.scheme)://%@/%@/notification/token",ORServer.hostURL,ORServer.realm)
public static var deleteNotifiedAlertResource = String(format:"\(ORServer.scheme)://%@/%@/notification/alert/",ORServer.hostURL,ORServer.realm)
diff --git a/console/iOS/ORLib/ORLib/PushNotificationProvider.swift b/console/iOS/ORLib/ORLib/PushNotificationProvider.swift
index dc4dcb5e6..d91311f22 100644
--- a/console/iOS/ORLib/ORLib/PushNotificationProvider.swift
+++ b/console/iOS/ORLib/ORLib/PushNotificationProvider.swift
@@ -11,7 +11,7 @@ import UserNotifications
public class PushNotificationProvider: NSObject {
- let userdefaults = UserDefaults.standard
+ let userdefaults = UserDefaults(suiteName: ORAppGroup.entitlement)
let version = "fcm"
public var consoleId: String = ""
@@ -23,7 +23,7 @@ public class PushNotificationProvider: NSObject {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
switch settings.authorizationStatus {
- case .authorized:
+ case .authorized, .provisional:
callback( [
DefaultsKey.actionKey: Actions.providerInit,
DefaultsKey.providerKey: Providers.push,
@@ -58,12 +58,15 @@ public class PushNotificationProvider: NSObject {
public func enable(consoleId: String, callback:@escaping ([String: Any]) ->(Void)) {
self.consoleId = consoleId
- userdefaults.set(self.consoleId, forKey: GeofenceProvider.consoleIdKey)
- userdefaults.synchronize()
+ userdefaults?.set(self.consoleId, forKey: GeofenceProvider.consoleIdKey)
+ userdefaults?.synchronize()
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
switch settings.authorizationStatus {
- case .authorized:
+ case .authorized, .provisional:
+ DispatchQueue.main.async {
+ UIApplication.shared.registerForRemoteNotifications()
+ }
callback([
DefaultsKey.actionKey: Actions.providerEnable,
DefaultsKey.providerKey: Providers.push,
@@ -82,10 +85,15 @@ public class PushNotificationProvider: NSObject {
])
case .notDetermined:
- let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
- options: authOptions,
+ options: [.alert, .badge, .sound],
completionHandler: {granted, _ in
+ if granted {
+ DispatchQueue.main.async {
+ UIApplication.shared.registerForRemoteNotifications()
+ }
+ }
+
callback([
DefaultsKey.actionKey: Actions.providerEnable,
DefaultsKey.providerKey: Providers.push,
diff --git a/console/iOS/OpenRemoteApp/OpenRemoteApp.xcodeproj/project.pbxproj b/console/iOS/OpenRemoteApp/OpenRemoteApp.xcodeproj/project.pbxproj
index 7c7d3df10..085042fd0 100644
--- a/console/iOS/OpenRemoteApp/OpenRemoteApp.xcodeproj/project.pbxproj
+++ b/console/iOS/OpenRemoteApp/OpenRemoteApp.xcodeproj/project.pbxproj
@@ -158,7 +158,6 @@
4C5C578B1FE17E0800C13164 /* Resources */,
4C5C57B11FE17E9A00C13164 /* Embed App Extensions */,
8F293E2545B0279AC2CAF14A /* [CP] Embed Pods Frameworks */,
- E11427C21A17056B0546F7BD /* [CP] Copy Pods Resources */,
);
buildRules = (
);
@@ -178,7 +177,6 @@
4C5C57A21FE17E9A00C13164 /* Sources */,
4C5C57A31FE17E9A00C13164 /* Frameworks */,
4C5C57A41FE17E9A00C13164 /* Resources */,
- D1A509DBCF475E9A94CDBCE8 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
@@ -318,36 +316,6 @@
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
- D1A509DBCF475E9A94CDBCE8 /* [CP] Copy Pods Resources */ = {
- isa = PBXShellScriptBuildPhase;
- buildActionMask = 2147483647;
- files = (
- );
- inputPaths = (
- );
- name = "[CP] Copy Pods Resources";
- outputPaths = (
- );
- runOnlyForDeploymentPostprocessing = 0;
- shellPath = /bin/sh;
- shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-NotificationService/Pods-NotificationService-resources.sh\"\n";
- showEnvVarsInLog = 0;
- };
- E11427C21A17056B0546F7BD /* [CP] Copy Pods Resources */ = {
- isa = PBXShellScriptBuildPhase;
- buildActionMask = 2147483647;
- files = (
- );
- inputPaths = (
- );
- name = "[CP] Copy Pods Resources";
- outputPaths = (
- );
- runOnlyForDeploymentPostprocessing = 0;
- shellPath = /bin/sh;
- shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-OpenRemoteApp/Pods-OpenRemoteApp-resources.sh\"\n";
- showEnvVarsInLog = 0;
- };
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -544,6 +512,7 @@
isa = XCBuildConfiguration;
baseConfigurationReference = 70B8E16EFB2F872AC0397DE5 /* Pods-NotificationService.debug.xcconfig */;
buildSettings = {
+ APPLICATION_EXTENSION_API_ONLY = NO;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = MD7Q2M7GWA;
INFOPLIST_FILE = NotificationService/Info.plist;
@@ -560,6 +529,7 @@
isa = XCBuildConfiguration;
baseConfigurationReference = FB93D125B872DE05BAEB4945 /* Pods-NotificationService.release.xcconfig */;
buildSettings = {
+ APPLICATION_EXTENSION_API_ONLY = NO;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = MD7Q2M7GWA;
INFOPLIST_FILE = NotificationService/Info.plist;
diff --git a/console/iOS/OpenRemoteApp/OpenRemoteApp.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate b/console/iOS/OpenRemoteApp/OpenRemoteApp.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate
index 779cac400..cc4f0c190 100644
Binary files a/console/iOS/OpenRemoteApp/OpenRemoteApp.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate and b/console/iOS/OpenRemoteApp/OpenRemoteApp.xcodeproj/project.xcworkspace/xcuserdata/michael.xcuserdatad/UserInterfaceState.xcuserstate differ