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 : get notification data from server

William Balcaendf598a3abe88
diff --git a/console/iOS/NotificationExtension/Constants.swift b/console/iOS/NotificationExtension/Constants.swift
index a4654aca1..839e4a2dd 100644
--- a/console/iOS/NotificationExtension/Constants.swift
+++ b/console/iOS/NotificationExtension/Constants.swift
@@ -19,9 +19,13 @@ struct AppGroup {
}
enum Server {
- static let hostURL = "192.168.0.138"
- static let port = "8080"
+ static let hostURL = "192.168.0.173"
static let initialPath = String(format:"console/%@/index.html",Server.realm)
static let realm = "blok61"
- static let apiTestResource = String(format:"http://%@:%@/%@/asset",Server.hostURL,Server.port,Server.realm)
+ static let apiTestResource = String(format:"https://%@/%@/notification/alert",Server.hostURL,Server.realm)
+}
+
+enum ActionType {
+ static let ACTION_TYPE1 = "ACTION_TYPE1"
+ static let ACTION_TYPE2 = "ACTION_TYPE2"
}
diff --git a/console/iOS/NotificationExtension/NotificationService.swift b/console/iOS/NotificationExtension/NotificationService.swift
index 7aa71d836..da65f03b5 100644
--- a/console/iOS/NotificationExtension/NotificationService.swift
+++ b/console/iOS/NotificationExtension/NotificationService.swift
@@ -8,7 +8,7 @@
import UserNotifications
-class NotificationService: UNNotificationServiceExtension {
+class NotificationService: UNNotificationServiceExtension, URLSessionDelegate {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
@@ -20,10 +20,10 @@ class NotificationService: UNNotificationServiceExtension {
if let bestAttemptContent = bestAttemptContent {
// Call backend to get payload and adapt title, body and actions
let defaults = UserDefaults(suiteName: AppGroup.entitlement)
+
defaults?.synchronize()
- bestAttemptContent.title = "You received an alarm from blok61 :"
- bestAttemptContent.body = "payload received from backend..."
- guard let tkurlRequest = URL(string:String(format: "http://%@:%@/auth/realms/%@/protocol/openid-connect/token",Server.hostURL, Server.port,Server.realm))
+
+ 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");
@@ -31,7 +31,7 @@ class NotificationService: UNNotificationServiceExtension {
let postString = String(format: "grant_type=refresh_token&refresh_token=%@&client_id=openremote", defaults!.object(forKey: DefaultsKey.refreshToken) as! CVarArg)
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) in
if (data != nil){
do {
@@ -41,13 +41,39 @@ class NotificationService: UNNotificationServiceExtension {
let request = NSMutableURLRequest(url: urlRequest)
request.addValue(String(format:"Bearer %@", jsonDictionnary["access_token"] as! String), forHTTPHeaderField: "Authorization")
let sessionConfiguration = URLSessionConfiguration.default
- let session = URLSession(configuration: sessionConfiguration)
+ 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) {
bestAttemptContent.body = error.debugDescription
} else {
- bestAttemptContent.body = String(data: data!, encoding: .utf8)!
+ do {
+ let json = try JSONSerialization.jsonObject(with: data!) as? [[String: Any]]
+ let detailedJson = (json?[0])! as [String: Any]
+ bestAttemptContent.title = detailedJson["title"] as! String
+ bestAttemptContent.body = detailedJson["message"] as! String
+ let actions = detailedJson["actions"] as! [[String : Any]]
+ var notificationActions = [UNNotificationAction]()
+ for var i in (0..<actions.count) {
+ let actionTitle = actions[i]["title"]! as! String
+ let actionType = actions[i]["type"]! as! String
+ switch actionType {
+ case ActionType.ACTION_TYPE1 :
+ notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.destructive))
+ case ActionType.ACTION_TYPE2 :
+ notificationActions.append(UNNotificationAction(identifier: actionType, title: actionTitle, options: UNNotificationActionOptions.foreground))
+ default : break
+
+ }
+ i += 1
+ }
+ let categoryName = "blok61Notification"
+ let category = UNNotificationCategory(identifier: categoryName, actions: notificationActions, intentIdentifiers: [], options: [])
+ let categories : Set = [category]
+ UNUserNotificationCenter.current().setNotificationCategories(categories)
+ } catch {
+ bestAttemptContent.body = "could not deserialize JSON"
+ }
contentHandler(bestAttemptContent)
}
}
@@ -89,4 +115,15 @@ class NotificationService: UNNotificationServiceExtension {
contentHandler(bestAttemptContent)
}
}
+
+ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
+ if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
+ if challenge.protectionSpace.host == Server.hostURL || challenge.protectionSpace.host == "fonts.googleapis.com" {
+ completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
+ } else {
+ print("Error : unsupported domain :",challenge.protectionSpace.serverTrust ?? "")
+ }
+
+ }
+ }
}
diff --git a/console/iOS/console/AppDelegate.swift b/console/iOS/console/AppDelegate.swift
index db3bdae9f..ce8e56842 100644
--- a/console/iOS/console/AppDelegate.swift
+++ b/console/iOS/console/AppDelegate.swift
@@ -24,7 +24,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
- setActions()
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
@@ -109,7 +108,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
- NSLog("Action asked : %@",response.actionIdentifier)
+ switch response.actionIdentifier {
+ case ActionType.ACTION_TYPE1 :
+ NSLog("Action asked : %@",response.actionIdentifier)
+ case ActionType.ACTION_TYPE2 :
+ NSLog("Action asked : %@",response.actionIdentifier)
+ default : break
+ }
+ completionHandler()
}
@@ -188,24 +194,5 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD
}
-func setActions() {
- let openApp = UNNotificationAction(
- identifier: "openApp",
- title: "Open Application",
- options : [.foreground]
- )
- let dismiss = UNNotificationAction(
- identifier: "dismiss",
- title: "Dismiss",
- options: [.destructive]
- )
- let category = UNNotificationCategory(
- identifier: "blok61Notification",
- actions: [openApp, dismiss],
- intentIdentifiers: []
- )
-
- UNUserNotificationCenter.current().setNotificationCategories([category])
-}
diff --git a/console/iOS/console/Constants.swift b/console/iOS/console/Constants.swift
index 6602ba0c8..a901d988b 100644
--- a/console/iOS/console/Constants.swift
+++ b/console/iOS/console/Constants.swift
@@ -45,3 +45,8 @@ enum Notifications {
static let fullScreenHidden = Notification.Name("fullScreenHidden")
static let idleTimerFired = Notification.Name("idleTimerFired")
}
+
+enum ActionType {
+ static let ACTION_TYPE1 = "ACTION_TYPE1"
+ static let ACTION_TYPE2 = "ACTION_TYPE2"
+}
diff --git a/console/iOS/console/ORViewController.swift b/console/iOS/console/ORViewController.swift
index bf760ef62..e762ae95a 100644
--- a/console/iOS/console/ORViewController.swift
+++ b/console/iOS/console/ORViewController.swift
@@ -75,14 +75,14 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
// just for testing purpose (ask backend to send a notification to device)
func apiCall() {
- guard let tkurlRequest = URL(string: String(format:"http://%@:%@/auth/realms/%@/protocol/openid-connect/token",Server.hostURL,Server.port,Server.realm)) else { return }
+ 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)
+ 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 {
@@ -90,12 +90,12 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
if ((jsonDictionnary["access_token"]) != nil) {
guard let urlRequest = URL(string: String(Server.apiTestResource)) else { return }
let request = NSMutableURLRequest(url: urlRequest)
- request.httpMethod = "POST"
+ request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- request.httpBody = "{\"title\" :\" The Title\",\"message\" : \"Message\",\"appUrl\" : \" AppUrl\",\"actions\": [ {\"title\" : \"Action title\" , \"type\": \"ACTION_TYPE1\"} ]}".data(using: .utf8)
+ request.httpBody = "{\"title\" :\" oula\",\"message\" : \"sdlkfslkdfjslkdfj\",\"appUrl\" : \" kljlkjlkjlk\",\"actions\": [ {\"title\" : \"Action title\" , \"type\": \"ACTION_TYPE1\"},{\"title\" : \"Action title\" , \"type\": \"ACTION_TYPE2\"} ]}".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 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) {
@@ -105,6 +105,7 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
])
self.showError(error: error)
} else {
+ print(response.debugDescription)
_ = self.myWebView?.load(data!, mimeType: "text/html", characterEncodingName: "utf8", baseURL: URL(string:Server.apiTestResource)!)
}
}
@@ -147,7 +148,7 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
}
func login() {
- guard let request = URL(string: String(format:"http://%@:%@/%@",Server.hostURL,Server.port,Server.initialPath)) else { return }
+ guard let request = URL(string: String(format:"https://%@/%@",Server.hostURL,Server.initialPath)) else { return }
_ = self.myWebView?.load(URLRequest(url: request))
}
@@ -158,6 +159,28 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
]))
}
+ func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
+ if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
+ if challenge.protectionSpace.host == Server.hostURL || challenge.protectionSpace.host == "fonts.googleapis.com" {
+ completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
+ } else {
+ print("Error : unsupported domain :",challenge.protectionSpace.serverTrust ?? "")
+ }
+
+ }
+ }
+
+ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
+ if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
+ if challenge.protectionSpace.host == Server.hostURL || challenge.protectionSpace.host == "fonts.googleapis.com" {
+ completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
+ } else {
+ print("Error : unsupported domain :",challenge.protectionSpace.serverTrust ?? "")
+ }
+
+ }
+ }
+
func configureAccess() {
webCfg = WKWebViewConfiguration()
let userController:WKUserContentController = WKUserContentController()
@@ -182,8 +205,8 @@ class ORViewcontroller : UIViewController, URLSessionDelegate, WKScriptMessageHa
myWebView?.navigationDelegate = self;
view.addSubview(myWebView!)
- //self.apiCall()
- self.login()
+ self.apiCall()
+ //self.login()
}
}
diff --git a/console/iOS/console/TokenManager.swift b/console/iOS/console/TokenManager.swift
index ce95e025e..44c938f46 100644
--- a/console/iOS/console/TokenManager.swift
+++ b/console/iOS/console/TokenManager.swift
@@ -92,7 +92,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
myWebView.navigationDelegate = self;
viewController.view.addSubview(myWebView)
UIApplication.shared.keyWindow?.rootViewController?.present(viewController, animated: true, completion: nil)
- guard let request = URL(string: String(format:"http://%@:%@/%@",Server.hostURL,Server.port,Server.initialPath)) else { return }
+ guard let request = URL(string: String(format:"https://%@/%@",Server.hostURL,Server.initialPath)) else { return }
myWebView.load(URLRequest(url: request))
}
@@ -151,6 +151,17 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
]))
}
+ func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
+ if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
+ if challenge.protectionSpace.host == Server.hostURL || challenge.protectionSpace.host == "fonts.googleapis.com" {
+ completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
+ } else {
+ print("Error : unsupported domain :",challenge.protectionSpace.serverTrust ?? "")
+ }
+
+ }
+ }
+
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
let errorCode = (error as NSError).code
if errorCode != NSURLErrorCancelled {
@@ -173,7 +184,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
}
func sendDeviceId() {
- guard let tkurlRequest = URL(string: String(format:"http://%@:%@/auth/realms/%@/protocol/openid-connect/token",Server.hostURL,Server.port,Server.realm)) else { return }
+ 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"