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 : notifications (WIP)

William Balcaen206c34391871
diff --git a/-f b/-f
new file mode 100644
index 000000000..e69de29bb
diff --git a/console/iOS/console.xcodeproj/project.pbxproj b/console/iOS/console.xcodeproj/project.pbxproj
index a40d2cf04..0756f68ff 100644
--- a/console/iOS/console.xcodeproj/project.pbxproj
+++ b/console/iOS/console.xcodeproj/project.pbxproj
@@ -20,6 +20,19 @@
FAA226BC1E7163D9009A8FEC /* TokenManagerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FAA226BB1E7163D9009A8FEC /* TokenManagerViewController.swift */; };
/* End PBXBuildFile section */
+/* Begin PBXCopyFilesBuildPhase section */
+ FAAFD0C61E78115700F01155 /* Embed App Extensions */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 2147483647;
+ dstPath = "";
+ dstSubfolderSpec = 13;
+ files = (
+ );
+ name = "Embed App Extensions";
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXCopyFilesBuildPhase section */
+
/* Begin PBXFileReference section */
146098EE6A2181297FD32B8D /* Pods-console.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-console.debug.xcconfig"; path = "Pods/Target Support Files/Pods-console/Pods-console.debug.xcconfig"; sourceTree = "<group>"; };
6A25CEFE37281B00C9BA7EB5 /* Pods-console.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-console.release.xcconfig"; path = "Pods/Target Support Files/Pods-console/Pods-console.release.xcconfig"; sourceTree = "<group>"; };
@@ -36,6 +49,9 @@
FAA226B71E71563F009A8FEC /* TokenManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TokenManager.swift; sourceTree = "<group>"; };
FAA226B91E715ED6009A8FEC /* TokenManagerView.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = TokenManagerView.xib; sourceTree = "<group>"; };
FAA226BB1E7163D9009A8FEC /* TokenManagerViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TokenManagerViewController.swift; sourceTree = "<group>"; };
+ FAAFD0B41E77EB6E00F01155 /* console.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = console.entitlements; sourceTree = "<group>"; };
+ FAAFD0BD1E78115700F01155 /* NotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = "<group>"; };
+ FAAFD0BF1E78115700F01155 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -71,6 +87,7 @@
isa = PBXGroup;
children = (
FA1D73E01E53374E00F6240A /* console */,
+ FAAFD0BC1E78115700F01155 /* consoleNSE */,
FA1D73DF1E53374E00F6240A /* Products */,
B5A9A3A4436D6649979AAD5D /* Pods */,
D99D42C10629DD05EE566F2F /* Frameworks */,
@@ -88,6 +105,7 @@
FA1D73E01E53374E00F6240A /* console */ = {
isa = PBXGroup;
children = (
+ FAAFD0B41E77EB6E00F01155 /* console.entitlements */,
FA1D73E11E53374E00F6240A /* AppDelegate.swift */,
FA1D73E31E53374E00F6240A /* ViewController.swift */,
FA1D73F51E53392F00F6240A /* ORViewController.swift */,
@@ -111,6 +129,15 @@
name = utils;
sourceTree = "<group>";
};
+ FAAFD0BC1E78115700F01155 /* consoleNSE */ = {
+ isa = PBXGroup;
+ children = (
+ FAAFD0BD1E78115700F01155 /* NotificationService.swift */,
+ FAAFD0BF1E78115700F01155 /* Info.plist */,
+ );
+ path = consoleNSE;
+ sourceTree = "<group>";
+ };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -124,6 +151,7 @@
FA1D73DC1E53374E00F6240A /* Resources */,
2E1F88AEF407A152C63657FF /* [CP] Embed Pods Frameworks */,
EE81FADDE7C1DBD70C93FA57 /* [CP] Copy Pods Resources */,
+ FAAFD0C61E78115700F01155 /* Embed App Extensions */,
);
buildRules = (
);
@@ -146,8 +174,17 @@
TargetAttributes = {
FA1D73DD1E53374E00F6240A = {
CreatedOnToolsVersion = 8.2.1;
+ DevelopmentTeam = 4W5599S8TP;
LastSwiftMigration = 0820;
ProvisioningStyle = Automatic;
+ SystemCapabilities = {
+ com.apple.BackgroundModes = {
+ enabled = 1;
+ };
+ com.apple.Push = {
+ enabled = 1;
+ };
+ };
};
};
};
@@ -366,7 +403,9 @@
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CODE_SIGN_ENTITLEMENTS = console/console.entitlements;
INFOPLIST_FILE = console/Info.plist;
+ IPHONEOS_DEPLOYMENT_TARGET = 10.2;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = org.openremote.console;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -380,7 +419,9 @@
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CODE_SIGN_ENTITLEMENTS = console/console.entitlements;
INFOPLIST_FILE = console/Info.plist;
+ IPHONEOS_DEPLOYMENT_TARGET = 10.2;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = org.openremote.console;
PRODUCT_NAME = "$(TARGET_NAME)";
diff --git a/console/iOS/console/AppDelegate.swift b/console/iOS/console/AppDelegate.swift
index 779e11d60..616208fae 100644
--- a/console/iOS/console/AppDelegate.swift
+++ b/console/iOS/console/AppDelegate.swift
@@ -8,40 +8,98 @@
import UIKit
import AppAuth
+import UserNotifications
+import Firebase
@UIApplicationMain
-class AppDelegate: UIResponder, UIApplicationDelegate {
-
+class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
+
var window: UIWindow?
var currentAuthorizationFlow : OIDAuthorizationFlowSession?
-
+ let gcmMessageIDKey = "gcm.message_id"
+ var isGrantedNotificationAccess:Bool = false
+
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// allows to catch all request and add custom headers (works only with UIWebView not WKWebView).
+ // For iOS 10 display notification (sent via APNS)
+ UNUserNotificationCenter.current().delegate = self
+
+ let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
+ UNUserNotificationCenter.current().requestAuthorization(
+ options: authOptions,
+ completionHandler: {_, _ in })
+
+ // For iOS 10 data message (sent via FCM)
+ FIRMessaging.messaging().remoteMessageDelegate = self
+
+ FIRApp.configure()
+
+ application.registerForRemoteNotifications()
+ NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
+
+ UNUserNotificationCenter.current().requestAuthorization(
+ options: [.alert,.sound,.badge],
+ completionHandler: { (granted,error) in
+ self.isGrantedNotificationAccess = granted
+ let ok = UNNotificationAction(identifier: "OpenApp",
+ title: "Open App", options: [.foreground])
+
+ let cancel = UNNotificationAction(identifier: "ResetAlarm",
+ title: "Reset Alarm",
+ options: [.destructive])
+
+ let category = UNNotificationCategory(identifier: "message", actions: [ok, cancel], intentIdentifiers: [], options: [])
+
+ UNUserNotificationCenter.current().setNotificationCategories([category])
+ }
+ )
return true
}
-
+
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
-
+
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
-
+
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
-
+
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
+ connectToFcm()
}
-
+
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-
+
+ func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
+ FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
+ //FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Prod)
+
+ }
+
+ func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
+ if let messageID = userInfo[gcmMessageIDKey] {
+ print("Message ID: \(messageID)")
+ }
+
+ // Print full message.
+ print(userInfo)
+ self.scheduleLocalNotification()
+ }
+
+ func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
+ self.scheduleLocalNotification()
+ completionHandler(UIBackgroundFetchResult.noData)
+ }
+
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
if (self.currentAuthorizationFlow?.resumeAuthorizationFlow(with: url))! {
self.currentAuthorizationFlow = nil
@@ -49,6 +107,65 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
return false
}
+
+ func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
+ print("Action asked : ",response.actionIdentifier)
+ }
+
+ func connectToFcm()
+ {
+ FIRMessaging.messaging().connect { (error) in
+ if (error != nil)
+ {
+ print("Unable to connect with FCM. \(error)")
+ }
+ else
+ {
+ print("Connected to FCM. Token is ",FIRInstanceID.instanceID().token()! as String)
+ }
+ }
+ }
+
+ func tokenRefreshNotification(notification: NSNotification)
+ {
+ if let refreshedToken = FIRInstanceID.instanceID().token()
+ {
+ print("InstanceID token: \(refreshedToken)")
+ }
+ // Connect to FCM since connection may have failed when attempted before having a token.
+ connectToFcm()
+ }
+
+ private func scheduleLocalNotification() {
+ // Create Notification Content
+ let notificationContent = UNMutableNotificationContent()
+ // Configure Notification Content
+ notificationContent.title = "Cocoacasts"
+ notificationContent.subtitle = "Local Notifications"
+ notificationContent.body = "In this tutorial, you learn how to schedule local notifications with the User Notifications framework."
+ notificationContent.categoryIdentifier = "message"
+ // Add Trigger
+ let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)
+
+ // Create Notification Request
+ let notificationRequest = UNNotificationRequest(identifier: "cocoacasts_local_notification", content: notificationContent, trigger: notificationTrigger)
+
+ // Add Request to User Notification Center
+ UNUserNotificationCenter.current().add(notificationRequest) { (error) in
+ if let error = error {
+ print("Unable to Add Notification Request (\(error), \(error.localizedDescription))")
+ }
+ }
+ }
+}
+
+
+// [START ios_10_data_message_handling]
+extension AppDelegate : FIRMessagingDelegate {
+ // Receive data message on iOS 10 devices while app is in the foreground.
+ func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
+ print(remoteMessage.appData)
+ }
}
diff --git a/console/iOS/console/Info.plist b/console/iOS/console/Info.plist
index 298adf827..f648391c6 100644
--- a/console/iOS/console/Info.plist
+++ b/console/iOS/console/Info.plist
@@ -33,6 +33,10 @@
<true/>
<key>NSPhotoLibraryUsageDescription</key>
<string>$(PRODUCT_NAME) photo use</string>
+ <key>UIBackgroundModes</key>
+ <array>
+ <string>remote-notification</string>
+ </array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
diff --git a/console/iOS/console/TokenManager.swift b/console/iOS/console/TokenManager.swift
index a2880d965..a1f5b5a6a 100644
--- a/console/iOS/console/TokenManager.swift
+++ b/console/iOS/console/TokenManager.swift
@@ -17,11 +17,14 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
var idToken : String?
var hasToken: Bool
var viewController : TokenManagerViewController
+ var myWebView : WKWebView
static let sharedInstance = TokenManager()
override init() {
viewController = TokenManagerViewController()
+ let webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
+ myWebView = WKWebView(frame: viewController.view.frame, configuration: webCfg)
if let token = UserDefaults.standard.value(forKey: DefaultsKey.offlineToken) {
hasToken = true
offlineToken = token as? String
@@ -37,6 +40,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
}
func authenticate() {
+ print("authenticate")
let defaults = UserDefaults.standard
let webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
@@ -48,6 +52,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
var exec_template = "var iOSToken"
if let offlineToken = defaults.object(forKey: DefaultsKey.offlineToken) {
+ print("offlinetoken exists")
let refreshToken = defaults.object(forKey: DefaultsKey.refreshToken)
let idToken = defaults.object(forKey: DefaultsKey.idToken)
exec_template = String(format: "var iOSToken = \"%@\"; var iOSRefreshToken = \"%@\"; var iOSTokenId = \"%@\";", offlineToken as! String, refreshToken as! String, idToken as! String)
@@ -58,7 +63,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
webCfg.userContentController = userController;
- let myWebView = WKWebView(frame: viewController.view.frame, configuration: webCfg)
+ myWebView = WKWebView(frame: viewController.view.frame, configuration: webCfg)
myWebView.uiDelegate = self;
myWebView.navigationDelegate = self;
viewController.view.addSubview(myWebView)
@@ -94,6 +99,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
}
if (offlineToken != nil && refreshToken != nil && idToken != nil ) {
self.hasToken = true
+ //myWeb
self.viewController.dismiss(animated: true, completion: {
let notificationName = Notification.Name(NotificationsNames.isAuthenticated)
NotificationCenter.default.post(name: notificationName, object: nil)
@@ -107,6 +113,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
let alertAction = UIAlertAction(title: "Done", style: .cancel) { (action) in
completionHandler()
}
+ print("javascript message %@",message)
alertView.addAction(alertAction)
viewController.present(alertView, animated: true, completion: nil)
}
@@ -114,6 +121,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
showError(error: error)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
+ print("navigation failed %@",error)
let errorCode = (error as NSError).code
if errorCode != NSURLErrorCancelled {
showError(error: error)
@@ -121,6 +129,7 @@ class TokenManager:NSObject, WKScriptMessageHandler, WKUIDelegate, WKNavigationD
}
}
func showError(error : Error) {
+ print("showing error %@",error)
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)
diff --git a/console/iOS/console/console.entitlements b/console/iOS/console/console.entitlements
new file mode 100644
index 000000000..903def2af
--- /dev/null
+++ b/console/iOS/console/console.entitlements
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>aps-environment</key>
+ <string>development</string>
+</dict>
+</plist>
diff --git a/console/iOS/podfile b/console/iOS/podfile
index e15c81427..9772321f9 100644
--- a/console/iOS/podfile
+++ b/console/iOS/podfile
@@ -1,4 +1,6 @@
target 'console' do
use_frameworks!
pod 'AppAuth'
+pod 'Firebase/Core'
+pod 'Firebase/Messaging'
end
diff --git a/nohup.out b/nohup.out
new file mode 100644
index 000000000..e69de29bb
diff --git a/up b/up
new file mode 100644
index 000000000..e69de29bb