diff --git a/BreinifyApi/api/BreinActivity.swift b/BreinifyApi/api/BreinActivity.swift index 6bab870..d1b0380 100644 --- a/BreinifyApi/api/BreinActivity.swift +++ b/BreinifyApi/api/BreinActivity.swift @@ -146,7 +146,12 @@ open class BreinActivity: BreinBase, ISecretStrategy { if nil == getBreinEngine() { throw BreinError.BreinRuntimeError("Rest engine not initialized. You have to configure BreinConfig with a valid engine.") } - try getBreinEngine()?.sendActivity(self, success: success, failure: failure) + + do { + try getBreinEngine()?.sendActivity(self, success: success, failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /// Creates a dictionary that will be used for the request. diff --git a/BreinifyApi/api/BreinLookup.swift b/BreinifyApi/api/BreinLookup.swift index 4d6fd1b..d90f8a9 100644 --- a/BreinifyApi/api/BreinLookup.swift +++ b/BreinifyApi/api/BreinLookup.swift @@ -41,7 +41,11 @@ open class BreinLookup: BreinBase, ISecretStrategy { setUser(breinUser) setBreinDimension(breinDimension) - return try getBreinEngine()!.performLookUp(self, success: successBlock, failure: failureBlock) + do { + return try getBreinEngine()!.performLookUp(self, success: successBlock, failure: failureBlock) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -85,7 +89,7 @@ open class BreinLookup: BreinBase, ISecretStrategy { do { requestData["signatureType"] = try createSignature() as Any? } catch { - BreinLogger.shared.log("Breinify not possible to generate signature") + BreinLogger.shared.log("Breinify not possible to generate signature.") } } diff --git a/BreinifyApi/api/BreinRecommendation.swift b/BreinifyApi/api/BreinRecommendation.swift index e7497c1..d90a0ca 100644 --- a/BreinifyApi/api/BreinRecommendation.swift +++ b/BreinifyApi/api/BreinRecommendation.swift @@ -22,22 +22,22 @@ open class BreinRecommendation: BreinBase, ISecretStrategy { public init(numberOfRecommendation: Int!) { super.init() - self.setNumberOfRecommendations(numberOfRecommendation) + setNumberOfRecommendations(numberOfRecommendation) } public init(breinUser: BreinUser?) { super.init() - self.setUser(breinUser) + setUser(breinUser) } public init(breinUser: BreinUser?, numberOfRecommendation: Int!) { super.init() - self.setUser(breinUser) - self.setNumberOfRecommendations(numberOfRecommendations) + setUser(breinUser) + setNumberOfRecommendations(numberOfRecommendations) } public func getCategory() -> String! { - self.category + category } @discardableResult @@ -47,12 +47,12 @@ open class BreinRecommendation: BreinBase, ISecretStrategy { } public func getNumberOfRecommendations() -> Int { - self.numberOfRecommendations + numberOfRecommendations } @discardableResult public func setNumberOfRecommendations(_ numOfRecommendations: Int) -> BreinRecommendation { - self.numberOfRecommendations = numOfRecommendations + numberOfRecommendations = numOfRecommendations return self } @@ -77,7 +77,7 @@ open class BreinRecommendation: BreinBase, ISecretStrategy { // firstly user data if let breinUser = getUser() { var userData = [String: Any]() - breinUser.prepareUserRequest(&userData, breinConfig: self.getConfig()) + breinUser.prepareUserRequest(&userData, breinConfig: getConfig()) requestData["user"] = userData as Any? } @@ -85,12 +85,12 @@ open class BreinRecommendation: BreinBase, ISecretStrategy { var recommendationData = [String: Any]() // optional field - if let category = self.getCategory() { + if let category = getCategory() { recommendationData["recommendationCategory"] = category as Any? } // mandatory field - recommendationData["numRecommendations"] = self.getNumberOfRecommendations() as Any? + recommendationData["numRecommendations"] = getNumberOfRecommendations() as Any? requestData["recommendation"] = recommendationData as Any?; @@ -110,8 +110,8 @@ open class BreinRecommendation: BreinBase, ISecretStrategy { // create a new recommendation object let clonedBreinRecommendation = BreinRecommendation() - .setNumberOfRecommendations(self.getNumberOfRecommendations()) - .setCategory(self.getCategory()) + .setNumberOfRecommendations(getNumberOfRecommendations()) + .setCategory(getCategory()) // clone from base class clonedBreinRecommendation.cloneBase(self) @@ -124,6 +124,11 @@ open class BreinRecommendation: BreinBase, ISecretStrategy { */ public override func createSignature() throws -> String! { let message = String(getUnixTimestamp()) - return try BreinUtil.generateSignature(message, secret: getConfig()?.getSecret()) + do { + return try BreinUtil.generateSignature(message, secret: getConfig()?.getSecret()) + } catch { + BreinLogger.shared.log(error.localizedDescription) + return "" + } } } diff --git a/BreinifyApi/api/BreinRequestManager.swift b/BreinifyApi/api/BreinRequestManager.swift index 8cb2e85..b9edc6e 100644 --- a/BreinifyApi/api/BreinRequestManager.swift +++ b/BreinifyApi/api/BreinRequestManager.swift @@ -60,7 +60,7 @@ open class BreinRequestManager { @objc public func sendActivityRequests() { - BreinLogger.shared.log("Breinify sendActivityRequests invoked - number of missed requests are: \(self.missedRequests.count)") + BreinLogger.shared.log("Breinify sendActivityRequests invoked - number of missed requests are: \(missedRequests.count)") if missedRequests.count > 0 { BreinLogger.shared.log("Breinify invoking saved activity requests") @@ -82,15 +82,15 @@ open class BreinRequestManager { } public func getMissedRequests() -> [String: JsonRequest] { - self.missedRequests + missedRequests } public func clearMissedRequests() { - self.missedRequests = [String: JsonRequest]() + missedRequests = [String: JsonRequest]() } public func status() -> String { - let numberOfRequests = "# :\(self.missedRequests.count)" + let numberOfRequests = "# :\(missedRequests.count)" return numberOfRequests } @@ -129,7 +129,8 @@ open class BreinRequestManager { */ public func shutdown() { - safeMissedRequests() + // deactivated now + // safeMissedRequests() } /** @@ -144,8 +145,7 @@ open class BreinRequestManager { */ public func safeMissedRequests() { - if self.missedRequests.count > 0 { - + if missedRequests.count > 0 { let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent(kRequestFullFileName) @@ -155,7 +155,7 @@ open class BreinRequestManager { var output = "" - for (_, jsonElement) in self.missedRequests { + for (_, jsonElement) in missedRequests { output = output + "\(jsonElement.creationTime!)" + kDelimiter @@ -178,7 +178,7 @@ open class BreinRequestManager { } // delete file if no entries exists - if self.missedRequests.count == 0 { + if missedRequests.count == 0 { let fileManager = FileManager.default let fileName = kRequestFileName @@ -209,7 +209,7 @@ open class BreinRequestManager { */ public func loadMissedRequests() { - if self.missedRequests.count == 0 { + if missedRequests.count == 0 { let fileName = kRequestFileName let docDirectory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, diff --git a/BreinifyApi/api/BreinTemporalData.swift b/BreinifyApi/api/BreinTemporalData.swift index 942001c..494e6e9 100644 --- a/BreinifyApi/api/BreinTemporalData.swift +++ b/BreinifyApi/api/BreinTemporalData.swift @@ -15,7 +15,7 @@ open class BreinTemporalData: BreinBase, ISecretStrategy { let kShapeTypesField = "shapeTypes" public func setLocation(key: String, value: AnyObject) -> BreinTemporalData { - _ = self.getUser()?.setAdditionalLocationEntry(key: key, value: value) + _ = getUser()?.setAdditionalLocationEntry(key: key, value: value) return self } @@ -36,23 +36,23 @@ open class BreinTemporalData: BreinBase, ISecretStrategy { } public func setLocalDateTime(_ localDateTime: String) -> BreinTemporalData { - _ = self.getUser()?.setLocalDateTime(localDateTime) + _ = getUser()?.setLocalDateTime(localDateTime) return self } public func setTimezone(_ timezone: String) -> BreinTemporalData { - _ = self.getUser()?.setTimezone(timezone) + _ = getUser()?.setTimezone(timezone) return self } // Lookup ip is part of the user.additional section public func setLookUpIpAddress(_ ipAddress: String) -> BreinTemporalData { - _ = self.getUser()?.setIpAddress(ipAddress) + _ = getUser()?.setIpAddress(ipAddress) return self } public func getLookUpIpAddress() -> String? { - self.getUser()?.getIpAddress() + getUser()?.getIpAddress() } /** @@ -103,9 +103,13 @@ open class BreinTemporalData: BreinBase, ISecretStrategy { setUser(breinUser) - return try getBreinEngine()!.performTemporalDataRequest(self, - success: success, - failure: failure) + do { + return try getBreinEngine()!.performTemporalDataRequest(self, + success: success, + failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } override public func prepareJsonRequest() -> [String: Any]! { @@ -116,12 +120,12 @@ open class BreinTemporalData: BreinBase, ISecretStrategy { if let breinUser = getUser() { var userData = [String: Any]() - breinUser.prepareUserRequest(&userData, breinConfig: self.getConfig()) + breinUser.prepareUserRequest(&userData, breinConfig: getConfig()) requestData["user"] = userData as Any? } // base level data... - self.prepareBaseRequestData(&requestData) + prepareBaseRequestData(&requestData) return requestData } diff --git a/BreinifyApi/api/Breinify.swift b/BreinifyApi/api/Breinify.swift index 534d21c..a452913 100644 --- a/BreinifyApi/api/Breinify.swift +++ b/BreinifyApi/api/Breinify.swift @@ -62,6 +62,9 @@ open class Breinify: NSObject { @objc public static func isBreinifyNotificationExtensionRequest(_ request: Any) -> Bool { + + BreinLogger.shared.log("isBreinifyNotificationExtensionRequest invoked with request: \(request)") + if #available(iOS 10.0, *) { let notificationRequest = request as! UNNotificationRequest return BreinifyManager.shared.isBreinifyNotificationExtensionRequest(notificationRequest) @@ -74,6 +77,8 @@ open class Breinify: NSObject { @objc public static func didReceiveNotificationExtensionRequest(_ request: Any, bestAttemptContent: Any) { + + BreinLogger.shared.log("didReceiveNotificationExtensionRequest REQUEST is: \(request)") if #available(iOS 10.0, *) { let notificationRequest = request as! UNNotificationRequest let notificationContent = bestAttemptContent as! UNMutableNotificationContent @@ -373,13 +378,17 @@ open class Breinify: NSObject { let breinAct = getBreinActivity() breinAct.setUser(user) - try activity(breinAct, - user: user, - activityType: activityType, - nil, - nil, - success, - failure) + do { + try activity(breinAct, + user: user, + activityType: activityType, + nil, + nil, + success, + failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -414,13 +423,17 @@ open class Breinify: NSObject { let breinAct = getBreinActivity() breinAct.setUser(user) - try activity(breinAct, - user: user, - activityType: activityType, - category, - description, - success, - failure) + do { + try activity(breinAct, + user: user, + activityType: activityType, + category, + description, + success, + failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -451,13 +464,17 @@ open class Breinify: NSObject { // firstly check if user is valid let user = self.getBreinUser() - try activity(getBreinActivity(), - user: user, - activityType: activityType, - category, - description, - success, - failure) + do { + try activity(getBreinActivity(), + user: user, + activityType: activityType, + category, + description, + success, + failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -501,10 +518,14 @@ open class Breinify: NSObject { let clonedActivity = activity.clone() - // invoke the activity call - try clonedActivity.getBreinEngine()?.sendActivity(clonedActivity, - success: success, - failure: failure) + do { + // invoke the activity call + try clonedActivity.getBreinEngine()?.sendActivity(clonedActivity, + success: success, + failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -538,9 +559,13 @@ open class Breinify: NSObject { // clone breinActivity let clonedBreinActivity = breinActivity.clone() - try clonedBreinActivity.getBreinEngine()?.sendActivity(clonedBreinActivity, - success: success, - failure: failure) + do { + try clonedBreinActivity.getBreinEngine()?.sendActivity(clonedBreinActivity, + success: success, + failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } @@ -590,9 +615,13 @@ open class Breinify: NSObject { // clone breinActivity let clonedBreinActivity = breinActivity.clone() - try clonedBreinActivity.getBreinEngine()?.sendActivity(clonedBreinActivity, - success: success, - failure: failure) + do { + try clonedBreinActivity.getBreinEngine()?.sendActivity(clonedBreinActivity, + success: success, + failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -624,9 +653,13 @@ open class Breinify: NSObject { clonedBreinRecommendation.setSuccessBlock(success) clonedBreinRecommendation.setFailureBlock(failure) - return try clonedBreinRecommendation.getBreinEngine()!.invokeRecommendation(clonedBreinRecommendation, - success: success, - failure: failure) + do { + return try clonedBreinRecommendation.getBreinEngine()!.invokeRecommendation(clonedBreinRecommendation, + success: success, + failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -649,9 +682,13 @@ open class Breinify: NSObject { self.breinTemporalData.setUser(user) - return try temporalData(breinTemporalData, - success, - failure) + do { + return try temporalData(breinTemporalData, + success, + failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -679,9 +716,13 @@ open class Breinify: NSObject { // apply the current configuration clonedBreinTemporalData.setConfig(self.getBreinTemporalData().getConfig()) - return try breinTemporalData.getBreinEngine()!.performTemporalDataRequest(breinTemporalData, - success: success, - failure: failure) + do { + return try breinTemporalData.getBreinEngine()!.performTemporalDataRequest(breinTemporalData, + success: success, + failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -714,9 +755,13 @@ open class Breinify: NSObject { // apply the current configuration clonedBreinTemporalData.setConfig(self.getBreinTemporalData().getConfig()) - return try breinTemporalData.getBreinEngine()!.performTemporalDataRequest(breinTemporalData, - success: success, - failure: failure) + do { + return try breinTemporalData.getBreinEngine()!.performTemporalDataRequest(breinTemporalData, + success: success, + failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -754,9 +799,13 @@ open class Breinify: NSObject { // apply the current configuration clonedBreinTemporalData.setConfig(self.getBreinTemporalData().getConfig()) - return try breinTemporalData.getBreinEngine()!.performTemporalDataRequest(breinTemporalData, - success: success, - failure: failure) + do { + return try breinTemporalData.getBreinEngine()!.performTemporalDataRequest(breinTemporalData, + success: success, + failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -777,11 +826,15 @@ open class Breinify: NSObject { _ failure: @escaping BreinEngine.apiFailure = { _ in }) throws { - return try lookup(breinLookup, - user: user, - dimension: dimension, - success, - failure) + do { + return try lookup(breinLookup, + user: user, + dimension: dimension, + success, + failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } /** @@ -811,14 +864,15 @@ open class Breinify: NSObject { breinLookup.setUser(user) breinLookup.setBreinDimension(dimension) - return try breinLookup.getBreinEngine()!.performLookUp(breinLookup, - success: success, - failure: failure) + do { + return try breinLookup.getBreinEngine()!.performLookUp(breinLookup, + success: success, + failure: failure) + } catch { + BreinLogger.shared.log(error.localizedDescription) + } } - // todo - // - check if willTerminate should be used instead - /// Initiates the shutdown of the engine @objc public class func shutdown() { diff --git a/BreinifyApi/api/BreinifyLifecycle.swift b/BreinifyApi/api/BreinifyLifecycle.swift index c36a21d..37d9f32 100644 --- a/BreinifyApi/api/BreinifyLifecycle.swift +++ b/BreinifyApi/api/BreinifyLifecycle.swift @@ -23,10 +23,12 @@ public extension Breinify { BreinifyManager.shared.didFinishLaunchingWithOptions(apiKey: apiKey, secret: secret, backgroundInterval: backgroundInterval) } + /** This method is invoked when the app is moving to background mode. */ + @objc class func applicationDidEnterBackground() { BreinifyManager.shared.applicationDidEnterBackground() } @@ -36,6 +38,7 @@ public extension Breinify { This method is invoked when the app is going to terminate. */ + @objc class func applicationWillTerminate() { BreinifyManager.shared.applicationWillTerminate() } @@ -46,7 +49,8 @@ public extension Breinify { device token for the iOS device */ - class func didRegisterForRemoteNotificationsWithDeviceToken(_ deviceToken: Data) -> String! { + @objc + class func didRegisterForRemoteNotificationsWithDeviceToken(_ deviceToken: Data) -> String! { let token = BreinifyManager.shared.didRegisterForRemoteNotificationsWithDeviceToken(deviceToken) return token } @@ -56,6 +60,7 @@ public extension Breinify { This method is invoked when it was not possible to register for remote notifications */ + @objc class func didFailToRegisterForRemoteNotificationsWithError(_ error: Error) { BreinifyManager.shared.didFailToRegisterForRemoteNotificationsWithError(error) } @@ -65,6 +70,7 @@ public extension Breinify { This method is invoked when a remove notification is triggered */ + @objc class func didReceiveRemoteNotification(_ userInfo: [AnyHashable: Any]) { BreinifyManager.shared.didReceiveRemoteNotification(userInfo) } @@ -74,6 +80,7 @@ public extension Breinify { This method is invoked when the App becomes active again. */ + @objc class func applicationDidBecomeActive() { BreinifyManager.shared.applicationDidBecomeActive() } @@ -83,10 +90,12 @@ public extension Breinify { the settings of userId. The userId is part of the request. */ + @objc class func setUserId(_ userId: String) { BreinifyManager.shared.setUserId(userId) } + @objc class func getUserId() -> String? { return BreinifyManager.shared.getUserId() } @@ -96,10 +105,12 @@ public extension Breinify { the settings of user email. The user email is part of the request. */ + @objc class func setEmail(_ email: String) { BreinifyManager.shared.setEmail(email) } + @objc class func getEmail() -> String? { return BreinifyManager.shared.getUserEmail() } diff --git a/BreinifyApi/api/BreinifyManager.swift b/BreinifyApi/api/BreinifyManager.swift index d07c092..f0d4600 100644 --- a/BreinifyApi/api/BreinifyManager.swift +++ b/BreinifyApi/api/BreinifyManager.swift @@ -56,7 +56,7 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { instance.configureSession() // detect ip - _ = BreinIpInfo.shared + // _ = BreinIpInfo.shared return instance }() @@ -71,7 +71,7 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { } public func getDeviceToken() -> String? { - self.deviceToken + deviceToken } public func setEmail(_ userEmail: String?) { @@ -79,7 +79,7 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { } public func getUserEmail() -> String? { - self.userEmail + userEmail } public func setUserId(_ userId: String) { @@ -87,7 +87,7 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { } public func getUserId() -> String? { - self.userId + userId } /// setup configuration @@ -100,11 +100,11 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { configureSession() // invoke ipAddress detection to be prepared for the next call - _ = BreinIpInfo.shared + //_ = BreinIpInfo.shared } public func configureSession() { - self.appSessionId = UUID().uuidString + appSessionId = UUID().uuidString } @objc func sendLocationInformation() { @@ -115,12 +115,12 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { BreinLogger.shared.log("Breinify sendActivity invoked") // create a user you are interested in - if self.userEmail != nil { - Breinify.getBreinUser().setEmail(self.userEmail) + if userEmail != nil { + Breinify.getBreinUser().setEmail(userEmail) } - if self.getUserId() != nil { - Breinify.getBreinUser().setUserId(self.getUserId()) + if getUserId() != nil { + Breinify.getBreinUser().setUserId(getUserId()) } // callback in case of success @@ -137,7 +137,6 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { if !additionalContent.isEmpty { // add additional content - // print("Additional Content is: \(additionalContent)") Breinify.getBreinUser().setAdditional(BreinifyManager.kNotificationLabel, map: additionalContent) } @@ -188,21 +187,21 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { let defaults = UserDefaults.standard if let email = defaults.string(forKey: BreinifyManager.kUserDefaultUserEmail) { - self.userEmail = email + userEmail = email Breinify.getBreinUser().setEmail(email) } if let uuid = defaults.string(forKey: BreinifyManager.kUserDefaultUserId) { - self.userId = uuid + userId = uuid } else { // not set yet generate an UUID - self.userId = UUID().uuidString + userId = UUID().uuidString } // set unique user id - Breinify.getBreinUser().setUserId(self.userId) + Breinify.getBreinUser().setUserId(userId) - BreinLogger.shared.log("Breinify readAndInitUserDefault with UserId: \(String(describing: self.userId)) - Email: \(String(describing: self.userEmail))") + BreinLogger.shared.log("Breinify readAndInitUserDefault with UserId: \(String(describing: userId)) - Email: \(String(describing: userEmail))") } /** @@ -231,14 +230,16 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { func registerBackgroundTask() { BreinLogger.shared.log("Breinify registerBackgroundTask called") - backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in + let application = UIApplication.value(forKeyPath: #keyPath(UIApplication.shared)) as! UIApplication + backgroundTask = application.beginBackgroundTask { [weak self] in self?.endBackgroundTask() } } func endBackgroundTask() { BreinLogger.shared.log("Breinify endBackgroundTask called") - UIApplication.shared.endBackgroundTask(backgroundTask) + let application = UIApplication.value(forKeyPath: #keyPath(UIApplication.shared)) as! UIApplication + application.endBackgroundTask(backgroundTask) backgroundTask = UIBackgroundTaskIdentifier.invalid } @@ -252,6 +253,7 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { BreinLogger.shared.log("Breinify UserNotification willPresent invoked with notification: \(notification)") let aps = notification.request.content.userInfo["aps"] as! [String: Any] + BreinLogger.shared.log("APS content is: \(aps)") // call BreinNotification-Handler // Breinify.getNotificationHandler()?.willPresent(notification) @@ -268,7 +270,7 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { BreinLogger.shared.log("Breinify UserNotification didReceive invoked with response: \(response).") let aps = response.notification.request.content.userInfo["aps"] as! [String: Any] - self.sendActivity(BreinActivityType.OPEN_PUSH_NOTIFICATION.rawValue, additionalContent: aps) + sendActivity(BreinActivityType.OPEN_PUSH_NOTIFICATION.rawValue, additionalContent: aps) // call BreinNotification-Handler // Breinify.getNotificationHandler()?.didReceive(response) @@ -279,6 +281,48 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { func registerPushNotifications() { BreinLogger.shared.log("Breinify registerPushNotifications invoked") + let application = UIApplication.value(forKeyPath: #keyPath(UIApplication.shared)) as! UIApplication + + if #available(iOS 10.0, *) { + let center = UNUserNotificationCenter.current() + + center.removeAllDeliveredNotifications() + center.removeAllPendingNotificationRequests() + center.delegate = self + + let application = UIApplication.value(forKeyPath: #keyPath(UIApplication.shared)) as! UIApplication + application.applicationIconBadgeNumber = 0 + + //GENERAL Category + let generalCategory = UNNotificationCategory(identifier: "GENERAL", actions: [], intentIdentifiers: [], options: .customDismissAction) + + //INVITATION Category + let remindLaterAction = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: UNNotificationActionOptions(rawValue: 0)) + let acceptAction = UNNotificationAction(identifier: "accept", title: "Accept", options: .foreground) + let declineAction = UNNotificationAction(identifier: "decline", title: "Decline", options: .destructive) + let commentAction = UNTextInputNotificationAction(identifier: "comment", title: "Comment", options: .authenticationRequired, textInputButtonTitle: "Send", textInputPlaceholder: "Share your thoughts..") + let invitationCategory = UNNotificationCategory(identifier: "INVITATION", actions: [remindLaterAction, acceptAction, declineAction, commentAction], intentIdentifiers: [], options: UNNotificationCategoryOptions(rawValue: 0)) + + center.setNotificationCategories([generalCategory, invitationCategory]) + center.requestAuthorization(options: [.badge, .sound, .alert]) { (granted, error) in + //granted = yes, if app is authorized for all of the requested interaction types + //granted = no, if one or more interaction type is disallowed + } + + } else { + let settings: UIUserNotificationSettings = + UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) + application.registerUserNotificationSettings(settings) + } + + application.registerForRemoteNotifications() + } + + func registerPushNotificationsOrg() { + BreinLogger.shared.log("Breinify registerPushNotifications invoked") + + let application = UIApplication.value(forKeyPath: #keyPath(UIApplication.shared)) as! UIApplication + if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() @@ -286,7 +330,8 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { center.removeAllPendingNotificationRequests() center.delegate = self - UIApplication.shared.applicationIconBadgeNumber = 0 + let application = UIApplication.value(forKeyPath: #keyPath(UIApplication.shared)) as! UIApplication + application.applicationIconBadgeNumber = 0 let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( @@ -303,10 +348,10 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) - UIApplication.shared.registerUserNotificationSettings(settings) + application.registerUserNotificationSettings(settings) } - UIApplication.shared.registerForRemoteNotifications() + application.registerForRemoteNotifications() } func getNotificationSettings() { @@ -319,13 +364,24 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { func isBreinifyNotificationExtensionRequest(_ request: Any) -> Bool { + BreinLogger.shared.log("Breinify isBreinifyNotificationExtensionRequest called with request: \(request)") + + /* if #available(iOS 10.0, *) { let notificationRequest = request as! UNNotificationRequest - BreinLogger.shared.log("Breinify isBreinifyNotificationExtensionRequest called with request: \(notificationRequest)") + BreinLogger.shared.log("NotificationRequest is: \(notificationRequest)") + } + */ + + guard let data = try? JSONSerialization.data(withJSONObject: request, options: .prettyPrinted), + let stringRequest = String(data: data, encoding: .utf8) else { + return false + } + + if stringRequest.contains("breinify") { + return true } - // todo - // - check if notification is a Breinify notification return false } @@ -338,11 +394,12 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { BreinLogger.shared.log("Breinify didReceiveNotificationExtensionRequest called with request: \(notificationRequest)") - notificationContent.title = "\(notificationContent.title) [modified in extensionrequest]" + notificationContent.title = "\(notificationContent.title) [yeah modified in extensionrequest yeah]" guard let content = (notificationRequest.content.mutableCopy() as? UNMutableNotificationContent) else { return } + BreinLogger.shared.log("Content is: \(content)") guard let apnsData = notificationContent.userInfo["data"] as? [String: Any] else { return @@ -360,7 +417,7 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { } notificationContent.attachments = [attachment] - notificationContent.title = "\(notificationContent.title) [modified in extensionrequest]" +// notificationContent.title = "\(notificationContent.title) [modified in extensionrequest]" } } @@ -388,7 +445,7 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { Breinify.readUserDefaults() // register PushNotifications - self.registerPushNotifications() + registerPushNotifications() let locUsage = Breinify.getConfig().getWithLocationManagerUsage() if locUsage == true { @@ -427,7 +484,7 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { name: UIApplication.didBecomeActiveNotification, object: nil) // set session id - Breinify.getBreinUser().setSessionId(self.appSessionId) + Breinify.getBreinUser().setSessionId(appSessionId) } // This method should be invoked from the Application Delegate method @@ -468,11 +525,12 @@ open class BreinifyManager: NSObject, UNUserNotificationCenterDelegate { public func didReceiveRemoteNotification(_ notification: [AnyHashable: Any]) { BreinLogger.shared.log("Breinify didReceiveRemoteNotification called with notification: \(notification)") - // todo show the notification - + // due to a possible URLSession connection time out we wait half a second to send a message + DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { + let notDic = notification["aps"] as! [String: Any] + self.sendActivity(BreinActivityType.RECEIVED_PUSH_NOTIFICATION.rawValue, additionalContent: notDic) + } - let notDic = notification["aps"] as! [String: Any] - self.sendActivity(BreinActivityType.RECEIVED_PUSH_NOTIFICATION.rawValue, additionalContent: notDic) } public func didFailToRegisterForRemoteNotificationsWithError(_ error: Error) {