· 6 years ago · Feb 07, 2020, 11:50 AM
1//
2// AppDelegate.swift
3// mpiosapp3.0
4//
5// Created by admin on 12/02/19.
6// Copyright © 2019 admin. All rights reserved.
7//
8
9import UIKit
10import CoreData
11import IQKeyboardManagerSwift
12import MapmyIndiaAPIKit
13import OpenTok
14import Firebase
15import FirebaseInstanceID
16import FirebaseMessaging
17import FirebaseAnalytics
18import UserNotifications
19import Alamofire
20import SwiftyJSON
21import CoreLocation
22/** start code copy **/
23import AWSPinpoint
24import AWSMobileClient
25/** end code copy **/
26let apppresentWindow = UIApplication.shared.windows.first
27let appDelegate = UIApplication.shared.delegate as! AppDelegate
28enum NotificationType { case background, foreground }
29
30struct FeatureEvent {
31 var eventId = FeatureEventId.DUMMY_EVENT
32 var startTimeStamp: String = ""
33 var endTimeStamp: String = ""
34}
35//@available(iOS 10.0, *)
36//@available(iOS 10.0, *)
37@UIApplicationMain
38class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
39
40 var window: UIWindow?
41 var osType = 1
42 var start_time_string:String = ""
43 var end_time_string:String = ""
44 var SessonDisConnectTime:String?
45 var isCastingStarted:Bool = false
46 var isCSASessionStarted : Bool = false
47 let modelName = UIDevice.modelName
48 let osVersion = UIDevice.current.systemVersion
49 let SESSION_JOINED_EVENT = "CSA_JOINED_SESSION"
50 var connectionID:String = ""
51 var OtpFailCount:Int = 0
52 let currentLanguage = "en"
53 var isClickedOnNotification = false
54 var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
55 var featureEvent = FeatureEvent()
56 // Replace with your OpenTok API key
57 var kApiKey = ""
58 var calFStoday : Date!
59 // Replace with your generated session ID
60 var kSessionId = ""
61 // Replace with your generated token
62 var kToken = ""
63 var analyticsService: AnalyticsService?
64 var openTokSession: OTSession!
65 var publisher: OTPublisher?
66 var subscriber: OTSubscriber?
67 var capturer: ScreenCapturer?
68 var appGlobal : UIApplication?
69 let locationManager = CLLocationManager()
70 var testAnalytica : Int = 0
71 var localNotificationBool = false
72
73 var immobilization = -1
74 var shortcutValue = -1
75
76 /** start code copy **/
77 var pinpoint: AWSPinpoint?
78 /** end code copy **/
79
80
81
82 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
83 // Override point for customization after application launch.
84 UIApplication.shared.applicationIconBadgeNumber = 0
85 initiateAwsPinpoint(launch: launchOptions)
86 let userID = UserDefaults.standard.value(forKey: defaultsKeys.userIdNew)
87 UserDefaults.standard.set(userID, forKey: defaultsKeys.sessionID)
88 appGlobal = application
89 //START FCM NOTIFCATION SETUP
90
91 if launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil {
92 Analytics.logEvent("AppEnterNotification", parameters: nil)
93 }
94 else {
95 Analytics.logEvent("AppEnterViaIcon", parameters: nil)
96 let start_time_date = DatetUtil.getCurrentUtcDate()
97 start_time_string = DatetUtil.getUtcDateStringFromUtcDate(utcDate: start_time_date)
98 }
99
100 let selectedTimeZone = UserDefaults.standard.string(forKey: defaultsKeys.timezone)
101 if selectedTimeZone == nil {
102 UserDefaults.standard.set("Asia/Kolkata", forKey: defaultsKeys.timezone)
103 }
104
105 let selectedLanguage = UserDefaults.standard.string(forKey: defaultsKeys.userPreferredLang)
106 if selectedLanguage == nil {
107 UserDefaults.standard.set("en", forKey: defaultsKeys.userPreferredLang)
108 }
109
110 if #available(iOS 10.0, *) {
111 print("Do nothing for iOS 10 or Above")
112 } else {
113 checkWheatherAppLaunchedViaNotification(didFinishLaunchingWithOptions: launchOptions)
114 }
115
116
117 FirebaseApp.configure()
118 Fabric.sharedSDK().debug = true
119 Messaging.messaging().delegate = self
120
121
122 if #available(iOS 10.0, *) {
123 // For iOS 10 display notification (sent via APNS)
124 UNUserNotificationCenter.current().delegate = self
125 let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
126 UNUserNotificationCenter.current().requestAuthorization(
127 options: authOptions,
128 completionHandler: {_,_ in })
129 // For iOS 10 data message (sent via FCM)
130 Messaging.messaging().shouldEstablishDirectChannel = true
131
132 } else {
133 let settings: UIUserNotificationSettings =
134 UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
135 application.registerUserNotificationSettings(settings)
136 }
137 application.registerForRemoteNotifications()
138
139 // Define the custom actions.
140 if #available(iOS 10.0, *) {
141 let later = UNNotificationAction(identifier: "LATER",
142 title: "Later",
143 options: UNNotificationActionOptions(rawValue: 0))
144 let alreadyKnow = UNNotificationAction(identifier: "ALREADY_KNOW",
145 title: "Already Know",
146 options: UNNotificationActionOptions(rawValue: 0))
147 // Define the notification type
148 if #available(iOS 11.0, *) {
149 let meetingInviteCategory =
150 UNNotificationCategory(identifier: "MEETING_INVITATION",
151 actions: [later, alreadyKnow],
152 intentIdentifiers: [],
153 hiddenPreviewsBodyPlaceholder: "",
154 options: .customDismissAction)
155 // Register the notification type.
156 let notificationCenter = UNUserNotificationCenter.current()
157 notificationCenter.setNotificationCategories([meetingInviteCategory])
158 } else {
159 // Fallback on earlier versions
160 let meetingInviteCategory = UNNotificationCategory(identifier: "MEETING_INVITATION", actions: [later, alreadyKnow], intentIdentifiers: [], options: [])
161
162 UNUserNotificationCenter.current().setNotificationCategories([meetingInviteCategory])
163 }
164
165 } else {
166 // Fallback on earlier versions
167 }
168
169 //END FCM NOTIFCATION SETUP
170
171 IQKeyboardManager.shared.enable = true
172 MapmyIndiaAccountManager.setMapSDKKey("98a0d3451d6afe9c7e3c974aae3b5697")
173 MapmyIndiaAccountManager.setRestAPIKey("72e640cfc15bbe89215171e3cb5006a0")
174 MapmyIndiaAccountManager.setAtlasClientId("xOLm9XH_QYoXD0V6HVzUbGf_BqxupV-TH9xBpecW-W2IIzThJph9dw==")
175 MapmyIndiaAccountManager.setAtlasClientSecret("XYU9wHVnv7suc58cfbzurh_d-R7C4Gc7-ZoCPmP1A6ZtLGfp3GEIbZsMKxhzoYJ0")
176 MapmyIndiaAccountManager.setAtlasGrantType("client_credentials")
177 MapmyIndiaAccountManager.setAtlasAPIVersion("1.3.11")
178
179 if !isLoggedOut() {
180 self.checkForPopup()
181 } else {
182 mpiosapp.shared.isVehicleSummaryPopupToBeOpen = false
183 }
184 if UserDefaults.standard.string(forKey: defaultsKeys.userIdNew) != nil {
185 Analytics.setUserID(UserDefaults.standard.string(forKey: defaultsKeys.userIdNew))
186 }
187
188
189 if (launchOptions?[UIApplication.LaunchOptionsKey.localNotification]) != nil {
190 localNotificationBool = true
191 }else {
192 localNotificationBool = false
193 }
194
195
196 if let activity = launchOptions?[UIApplication.LaunchOptionsKey.userActivityDictionary] {
197
198 }else {
199
200 }
201
202// let activityDictionary = launchOptions?[UIApplication.LaunchOptionsKey.userActivityDictionary]
203// if activityDictionary != nil {
204// let userActivity = activityDictionary?[UIApplication.LaunchOptionsKey.userActivityType]
205// if userActivity != nil {
206// return true
207// }
208// }
209
210 // Other didFinishLaunching code...
211
212 return true
213 }
214
215
216 func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
217 if let incomingUrl = userActivity.webpageURL {
218 print("incoming url \(incomingUrl)")
219
220
221 guard let components = URLComponents(url: incomingUrl, resolvingAgainstBaseURL: true),
222 let queryItems = components.queryItems else { return true }
223
224 shortcutValue = 5
225
226 if let startDate = queryItems.first?.value,
227 let endDate = queryItems.last?.value {
228 let startDateHr = startDate + " 00:00:00"
229 let endDateHr = endDate + " 23:59:59"
230 let startDateObj = DatetUtil.getUtcDateFromUtcString(datetime: startDateHr)
231 let endDateObj = DatetUtil.getUtcDateFromUtcString(datetime: endDateHr)
232
233 let storyboard = UIStoryboard(name: "ReportStoryboard", bundle: nil)
234 let reportVC = storyboard.instantiateViewController(withIdentifier :"ReportViewController") as! ReportViewController
235
236 reportVC.dateStart = startDateHr
237 reportVC.dateEnd = endDateHr
238 reportVC.startDate = startDateObj
239 reportVC.endDate = endDateObj
240
241 if let window = appDelegate.window, let rootViewController = window.rootViewController {
242 var currentController = rootViewController
243 while let presentedController = currentController.presentedViewController {
244 currentController = presentedController
245 }
246 if currentController.isKind(of: UINavigationController.self) {
247 let navVC = currentController as! UINavigationController
248 navVC.pushViewController(reportVC, animated: true)
249 } else {
250 currentController.present(reportVC, animated: true, completion: nil)
251 }
252 }
253 }
254 }
255//
256// let linkHanlded = DynamicLinks.dynamicLinks().handleUniversalLink(incomingUrl) { (dynamic, error) in
257// guard error == nil else {
258// print("Found an Error\(error!.localizedDescription)")
259// return
260// }
261// if let dynamicLink = dynamic {
262// self.hanldeIncomingDynamicLink(dynamicLink)
263// }
264// }
265// if linkHanlded {
266// return true
267// }else {
268// return false
269// }
270// }
271 return true
272 }
273
274
275 func hanldeIncomingDynamicLink(_ dynamicLink: DynamicLink) {
276 guard let url = dynamicLink.url else {
277 print("error")
278 return
279 }
280 print("incoming link: \(url.absoluteString)")
281 guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true),
282 let queryItems = components.queryItems else { return }
283
284 if components.path == "/Report" {
285 print(queryItems.first?.value)
286 }
287
288
289 }
290
291 func immobilizationValue(value : Int){
292 if immobilization != value {
293 immobilization = value
294 NotificationCenter.default.post(name: .immobilizationValueChange, object: nil)
295 }
296 }
297
298 func doSomeDownload() {
299 //call endBackgroundTask() on completion..
300 switch UIApplication.shared.applicationState {
301 case .active:
302 print("App is active.")
303 case .background:
304 print("App is in background.")
305 print("Background time remaining = \(UIApplication.shared.backgroundTimeRemaining) seconds")
306 case .inactive:
307 break
308 }
309 }
310
311 func registerBackgroundTask() {
312 print("register background task")
313 backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
314 self?.endBackgroundTask()
315 }
316 // assert(backgroundTask != UIBackgroundTaskIdentifier.invalid)
317 }
318
319 func endBackgroundTask() {
320 print("Background task ended.")
321 UIApplication.shared.endBackgroundTask(backgroundTask)
322 backgroundTask = UIBackgroundTaskIdentifier.invalid
323 }
324
325 //SET APP LANGUAGE
326 func setCurrentLanguageCode(selectedLanguageCode: String){
327 UserDefaults.standard.set(selectedLanguageCode, forKey: defaultsKeys.currentLanguageCode)
328 }
329
330 //GET CURRENT APP LANGUAGE
331 func getCurrentLanguageCode() -> String{
332 if let languageCode = UserDefaults.standard.string(forKey: defaultsKeys.currentLanguageCode){
333 return languageCode;
334 }
335 return "en"
336 }
337
338 func checkForPopup() {
339 let lastPopupShownDate = UserDefaults.standard.value(forKey: "LastPopupShownDate")
340 if lastPopupShownDate != nil {
341 //TimezoneDate Change
342 //let intervalTime = Date().seconds(from: (lastPopupShownDate as! Date))
343 let intervalTime = DatetUtil.timeZoneCurrentDate.seconds(from: (lastPopupShownDate as! Date))
344 if intervalTime >= mpiosapp.shared.popupTimeIntervalInSeconds {
345 mpiosapp.shared.isVehicleSummaryPopupToBeOpen = true
346 } else {
347 mpiosapp.shared.isVehicleSummaryPopupToBeOpen = false
348 }
349 } else {
350 mpiosapp.shared.isVehicleSummaryPopupToBeOpen = true
351 }
352 }
353
354 func checkWheatherAppLaunchedViaNotification(didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?){
355 if let lo = launchOptions
356 {
357 if let localNotification = lo[UIApplication.LaunchOptionsKey.localNotification] as? UILocalNotification
358 {
359 if (localNotification.userInfo!["local"] as? String) != nil{
360 isClickedOnNotification = true
361 }
362 }
363 }
364 }
365
366
367
368 func convertToDictionarys(text: String) -> [String: Any]? {
369 if let data = text.data(using: .utf8) {
370 do {
371 return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
372 } catch {
373 print(error.localizedDescription)
374 }
375 }
376 return nil
377 }
378
379 func isLoggedOut() -> Bool{
380 let loginVal = UserDefaults.standard.value(forKey: defaultsKeys.timeSession)
381
382 if loginVal != nil {
383 return false
384 }
385 return true
386 }
387
388 //Method to handle local notification
389 func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
390
391 if isLoggedOut(){return}
392 if notification.fireDate!.timeIntervalSinceNow < -0.4 {
393 let dicUserInfo = notification.userInfo
394 NotificationCenter.default.post(name: Notification.Name(rawValue: "Notification Recieved"), object: nil,userInfo: dicUserInfo)
395 }
396 }
397
398 //Method to show local notification
399 func showNotification(_ title:String, message:String,remoteNotification gottenUserInfo: [AnyHashable: Any]) {
400 let notification = UILocalNotification()
401 notification.alertBody = message
402 notification.alertAction = "open"
403 //TimezoneDate Change
404 //notification.fireDate = Date()
405 notification.fireDate = DatetUtil.timeZoneCurrentDate
406 notification.soundName = UILocalNotificationDefaultSoundName
407 notification.userInfo = gottenUserInfo
408 notification.category = title
409 UIApplication.shared.scheduleLocalNotification(notification)
410 }
411
412
413
414 func doWithNotification(userInfo : [AnyHashable : Any], notificationType : NotificationType) -> Bool {
415 var presentNotification = true
416 mpiosapp.shared.isVehicleSummaryPopupToBeOpen = false
417 if let dictString = userInfo["data"] as? String {
418 let data = convertToDictionary(text: dictString)
419 let alertType = data!["alertType"] as? Int
420 let serialNumber = data!["serial_number"] as? String
421 if alertType != nil {
422 if notificationType == .foreground {
423 if alertType == AlertType.MODE_CHANGED { // 101
424 presentNotification = false
425 } else if alertType == AlertType.ACCESS_LEVEL_DENIED { // 140
426 presentNotification = false
427 } else if alertType == AlertType.DNT_TIME_COMPLETE { // 108
428 if mpiosapp.shared.activeVehicleResponse?.strSerial_no == serialNumber {
429 presentNotification = false
430 }
431 }
432 }
433 }
434 }
435 return presentNotification
436 }
437
438 func convertToDictionary(text: String) -> [String: Any]? {
439 if let data = text.data(using: .utf8) {
440 do {
441 return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
442 } catch {
443 print(error.localizedDescription)
444 }
445 }
446 return nil
447 }
448
449
450
451 // end notification part form old app
452
453 func applicationWillResignActive(_ application: UIApplication) {
454 print("Resign Active")
455 }
456
457 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
458 //Format token as you need:
459 let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
460 print(token , "@@@@@token")
461 didRegisterForRemoteNotiicationWithToken(withDeviceToken: deviceToken)
462 InstanceID.instanceID().instanceID { (result, error) in
463 if let error = error {
464 print("Error fetching remote instange ID: \(error)")
465 } else if let result = result {
466 print("Remote instance ID token: \(result.token)")
467 }
468 }
469 }
470
471 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
472 print(userInfo)
473 }
474
475 func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], withResponseInfo responseInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) {
476 print(userInfo)
477 }
478
479 func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
480 let strParam = url.absoluteString
481 print("handleOpen" + strParam)
482 return true
483 }
484
485 func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
486
487 let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)
488 let host = urlComponents?.host ?? ""
489
490 if host == "Report" {
491 shortcutValue = 3
492 if let startDate = urlComponents?.queryItems?.first?.value,
493 let endDate = urlComponents?.queryItems?.last?.value {
494 let startDateHr = startDate + " 00:00:00"
495 let endDateHr = endDate + " 23:59:59"
496 let startDateObj = DatetUtil.getUtcDateFromUtcString(datetime: startDateHr)
497 let endDateObj = DatetUtil.getUtcDateFromUtcString(datetime: endDateHr)
498
499 let storyboard = UIStoryboard(name: "ReportStoryboard", bundle: nil)
500 let reportVC = storyboard.instantiateViewController(withIdentifier :"ReportViewController") as! ReportViewController
501
502 reportVC.dateStart = startDateHr
503 reportVC.dateEnd = endDateHr
504 reportVC.startDate = startDateObj
505 reportVC.endDate = endDateObj
506
507 if let window = appDelegate.window, let rootViewController = window.rootViewController {
508 var currentController = rootViewController
509 while let presentedController = currentController.presentedViewController {
510 currentController = presentedController
511 }
512 if currentController.isKind(of: UINavigationController.self) {
513 let navVC = currentController as! UINavigationController
514 navVC.pushViewController(reportVC, animated: true)
515 } else {
516 currentController.present(reportVC, animated: true, completion: nil)
517 }
518 }
519 }
520 }
521
522 return true
523 }
524
525 func applicationDidEnterBackground(_ application: UIApplication) {
526 // 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.
527 // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
528 print("Enter background")
529 UserDefaults.standard.set(DatetUtil.timeZoneCurrentDate, forKey: "LastPopupShownDate")
530
531 let end_time_date = DatetUtil.getCurrentUtcDate()
532 end_time_string = DatetUtil.getUtcDateStringFromUtcDate(utcDate: end_time_date)
533
534 if Miscellaneous.getAppDelgateInstance().featureEvent.eventId != FeatureEventId.DUMMY_EVENT {
535 //RECORD DATA TO DATABASE
536 Miscellaneous.getAppDelgateInstance().featureEvent.endTimeStamp = DatetUtil.getCurrentUtcDateTimeInString()
537 if let userID = UserDefaults.standard.string(forKey:defaultsKeys.userIdNew){
538 let analyticsData = CollectDataAnalytics()
539 analyticsData.startTime = Miscellaneous.getAppDelgateInstance().featureEvent.startTimeStamp
540 analyticsData.endTime = Miscellaneous.getAppDelgateInstance().featureEvent.endTimeStamp
541 analyticsData.uniqueId = userID.sha256()
542 analyticsData.eventId = String(Miscellaneous.getAppDelgateInstance().featureEvent.eventId)
543 Database.sendDataCollected(analytics: analyticsData)
544 print("Recording event with id \(Miscellaneous.getAppDelgateInstance().featureEvent.eventId) startTime \(Miscellaneous.getAppDelgateInstance().featureEvent.startTimeStamp) endTime is \(Miscellaneous.getAppDelgateInstance().featureEvent.endTimeStamp)")
545
546 }
547 }
548
549 let sessionID = UserDefaults.standard.string(forKey: defaultsKeys.sessionID)
550 if sessionID != nil {
551 let analyticsDataDAUMAU = CollectDataAnalytics()
552 analyticsDataDAUMAU.startTime = start_time_string
553 analyticsDataDAUMAU.endTime = end_time_string
554 analyticsDataDAUMAU.uniqueId = sessionID?.sha256()
555 analyticsDataDAUMAU.eventId = "1"
556 Database.sendDataCollected(analytics: analyticsDataDAUMAU)
557 UserDefaults.standard.set(nil, forKey: defaultsKeys.sessionID)
558 }
559
560 Miscellaneous.getAppDelgateInstance().featureEvent.startTimeStamp = ""
561 Miscellaneous.getAppDelgateInstance().featureEvent.endTimeStamp = ""
562 self.registerBackgroundTask()
563 self.update()
564 }
565
566 @objc func update() {
567 // Something cool
568 print("running in background process successfully.......")
569
570 //endBackgroundTask()
571 sendAnalyticsData()
572 }
573
574 func applicationWillEnterForeground(_ application: UIApplication) {
575 // 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.
576 print("Will Enter Foreground")
577
578 let userID = UserDefaults.standard.value(forKey: defaultsKeys.userIdNew)
579 UserDefaults.standard.set(userID, forKey: defaultsKeys.sessionID)
580
581 initUserLocation()
582
583 Analytics.logEvent("AppEnterViaIcon", parameters: nil)
584
585 let start_time_date = DatetUtil.getCurrentUtcDate()
586 start_time_string = DatetUtil.getUtcDateStringFromUtcDate(utcDate: start_time_date)
587
588 print("TAG",start_time_string,"START TIME")
589
590 if isCastingStarted {
591
592 if !(start_time_string.isEmpty) && !(end_time_string.isEmpty){
593
594 if getDifferenceNumberOfDaysFromFirstAndLast(dateFrom: end_time_string, dateTo: start_time_string) > 300 {
595 disConnect()
596 if(isCSASessionStarted){
597 showScreenSharingFeedBackDialog()
598 }
599 isCastingStarted = false
600 isCSASessionStarted = false
601 }
602 }
603 else {
604 start_time_string = ""
605 end_time_string = ""
606 }
607 }
608 if !isLoggedOut() {
609 self.checkForPopup()
610 } else {
611 mpiosapp.shared.isVehicleSummaryPopupToBeOpen = false
612 }
613 }
614
615 func applicationDidBecomeActive(_ application: UIApplication) {
616 // 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.
617 }
618
619 func applicationWillTerminate(_ application: UIApplication) {
620 // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
621 // Saves changes in the application's managed object context before the application terminates.
622 print("will Terminate")
623
624 if mpiosapp.shared.activeVehicleResponse != nil {
625 UserDefaults.standard.set(mpiosapp.shared.activeVehicleResponse?.strSerial_no, forKey: "ActiveVehicleSerialNo")
626 }
627 self.saveContext()
628
629 //TimezoneDate Change
630 //UserDefaults.standard.set(Date.init(), forKey: "LastPopupShownDate")
631 UserDefaults.standard.set(DatetUtil.timeZoneCurrentDate, forKey: "LastPopupShownDate")
632
633 }
634
635 func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
636 let navigationController = application.windows[0].rootViewController as! UINavigationController
637 switch shortcutItem.type {
638
639 case "timeline":
640 Analytics.logEvent("shortcut_timeline", parameters: nil)
641 shortcutValue = 1
642 calFStoday = Date()
643
644 let searchVC = navigationController.viewControllers.first(where: { (findVC) -> Bool in
645 findVC is TimelineVC
646 })
647
648 if searchVC != nil {
649 let timelineVC = searchVC as! TimelineVC
650 timelineVC.isFromShortcut = true
651 navigationController.popToViewController(timelineVC, animated: true)
652 timelineVC.viewDidLoad()
653 }
654
655 else {
656 let storyboard = UIStoryboard(name: Storyboard.TIMELINE, bundle: nil)
657 let timelineVC = storyboard.instantiateViewController(withIdentifier :ViewControllers.TIMELINE_VIEW_CONTROLLER) as! TimelineVC
658 timelineVC.isFromShortcut = true
659 if let window = self.window, let rootViewController = window.rootViewController {
660 var currentController = rootViewController
661 while let presentedController = currentController.presentedViewController {
662 currentController = presentedController
663 }
664 if currentController.isKind(of: UINavigationController.self) {
665 let navVC = currentController as! UINavigationController
666 navVC.pushViewController(timelineVC, animated: true)
667 } else {
668 currentController.present(timelineVC, animated: true, completion: nil)
669 }
670 }
671 }
672
673 case "authuser":
674 Analytics.logEvent("shortcut_authoriseUser", parameters: nil)
675 print("authuser clicked")
676 shortcutValue = 2
677
678 let searchVC = navigationController.viewControllers.first(where: { (findVC) -> Bool in
679 findVC is activeUsersVC
680 })
681
682 if searchVC != nil {
683 let authuser = searchVC as! activeUsersVC
684 navigationController.popToViewController(authuser, animated: true)
685 }
686 else {
687 let storyBoard = UIStoryboard(name: Storyboard.AUTHORIZED_USER, bundle: nil)
688 let authuser = storyBoard.instantiateViewController(withIdentifier: ViewControllers.ACTIVE_USERS_VC) as! activeUsersVC
689 if let window = self.window, let rootViewController = window.rootViewController {
690 var currentController = rootViewController
691 while let presentedController = currentController.presentedViewController {
692 currentController = presentedController
693 }
694 if currentController.isKind(of: UINavigationController.self) {
695 let navVC = currentController as! UINavigationController
696 navVC.pushViewController(authuser, animated: true)
697 } else {
698 currentController.present(authuser, animated: true, completion: nil)
699 }
700 }
701 }
702 case "report":
703 Analytics.logEvent("shortcut_report", parameters: nil)
704 print("report clicked")
705 shortcutValue = 3
706 calFStoday = Date()
707
708 let searchVC = navigationController.viewControllers.first(where: { (findVC) -> Bool in
709 findVC is ReportViewController
710 })
711
712 if searchVC != nil {
713 let reportVC = searchVC as! ReportViewController
714 reportVC.dateStart = DatetUtil.getLocalDateWithDay2(date: calFStoday)
715 reportVC.dateEnd = DatetUtil.getLocalDateWithDay2(date: calFStoday)
716 reportVC.startDate = calFStoday
717 reportVC.endDate = calFStoday
718 navigationController.popToViewController(reportVC, animated: true)
719 reportVC.viewDidLoad()
720 }
721 else {
722 let storyBoard = UIStoryboard(name: Storyboard.REPORT_STORYBOARD, bundle: nil)
723 let reportVC = storyBoard.instantiateViewController(withIdentifier: ViewControllers.REPORT_VIEW_CONTROLLER) as! ReportViewController
724 reportVC.dateStart = DatetUtil.getLocalDateWithDay2(date: calFStoday)
725 reportVC.dateEnd = DatetUtil.getLocalDateWithDay2(date: calFStoday)
726 reportVC.startDate = calFStoday
727 reportVC.endDate = calFStoday
728
729 if let window = self.window, let rootViewController = window.rootViewController {
730 var currentController = rootViewController
731 while let presentedController = currentController.presentedViewController {
732 currentController = presentedController
733 }
734 if currentController.isKind(of: UINavigationController.self) {
735 let navVC = currentController as! UINavigationController
736 navVC.pushViewController(reportVC, animated: true)
737 } else {
738 currentController.present(reportVC, animated: true, completion: nil)
739 }
740 }
741 }
742 case "notification":
743 Analytics.logEvent("shortcut_notification", parameters: nil)
744 shortcutValue = 4
745
746 let searchVC = navigationController.viewControllers.first(where: { (findVC) -> Bool in
747 findVC is NotificationsVC
748 })
749
750 if searchVC != nil {
751 let notification = searchVC as! NotificationsVC
752 navigationController.popToViewController(notification, animated: true)
753 notification.viewDidLoad()
754 }
755 else {
756 let storyBoard = UIStoryboard(name: Storyboard.NOTIFICATION, bundle: nil)
757 let destVC = storyBoard.instantiateViewController(withIdentifier: ViewControllers.NOTIFICATIONS) as! NotificationsVC
758
759 if let window = self.window, let rootViewController = window.rootViewController {
760 var currentController = rootViewController
761 while let presentedController = currentController.presentedViewController {
762 currentController = presentedController
763 }
764 if currentController.isKind(of: UINavigationController.self) {
765 let navVC = currentController as! UINavigationController
766 navVC.pushViewController(destVC, animated: true)
767 } else {
768 currentController.present(destVC, animated: true, completion: nil)
769 }
770 }
771 }
772 default:
773 print("default")
774 }
775
776 }
777
778 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
779 print(error.localizedDescription)
780 }
781
782 @available(iOS 10.0, *)
783 lazy var persistentContainer: NSPersistentContainer = {
784
785 let container = NSPersistentContainer(name: "mpios_database")
786 container.loadPersistentStores(completionHandler: { (storeDescription, error) in
787 if let error = error as NSError? {
788
789 fatalError("Unresolved error \(error), \(error.userInfo)")
790 }
791 })
792 return container
793 }()
794
795 // iOS 9 and below
796 lazy var applicationDocumentsDirectory: URL = {
797
798 let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
799 return urls[urls.count-1]
800 }()
801
802 lazy var managedObjectModel: NSManagedObjectModel = {
803 // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
804 let modelURL = Bundle.main.url(forResource: "mpios_database", withExtension: "momd")!
805 return NSManagedObjectModel(contentsOf: modelURL)!
806 }()
807
808 lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
809
810 let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
811 let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
812 var failureReason = "There was an error creating or loading the application's saved data."
813 do {
814 try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
815 } catch {
816 // Report any error we got.
817 var dict = [String: AnyObject]()
818 dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
819 dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
820
821 dict[NSUnderlyingErrorKey] = error as NSError
822 let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
823 // Replace this with code to handle the error appropriately.
824 // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
825 NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
826 abort()
827 }
828
829 return coordinator
830 }()
831
832 lazy var managedObjectContext: NSManagedObjectContext = {
833 // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
834 let coordinator = self.persistentStoreCoordinator
835 var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
836 managedObjectContext.persistentStoreCoordinator = coordinator
837 return managedObjectContext
838 }()
839
840 // MARK: - Core Data Saving support
841
842 func saveContext () {
843
844 if #available(iOS 10.0, *) {
845
846 let context = persistentContainer.viewContext
847 if context.hasChanges {
848 do {
849 try context.save()
850 } catch {
851 // Replace this implementation with code to handle the error appropriately.
852 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
853 let nserror = error as NSError
854 fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
855 }
856 }
857 } else {
858 // iOS 9.0 and below - however you were previously handling it
859 if managedObjectContext.hasChanges {
860 do {
861 try managedObjectContext.save()
862 } catch {
863 // Replace this implementation with code to handle the error appropriately.
864 // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
865 let nserror = error as NSError
866 NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
867 abort()
868 }
869 }
870 }
871 }
872}
873
874extension AppDelegate : MessagingDelegate {
875
876 // @available(iOS 10.0, *)
877 public func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage){
878 }
879
880 func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
881 print("fcm token \(fcmToken)")
882 let oldFCM = UserDefaults.standard.string(forKey: defaultsKeys.tokenIdNew)
883 mpiosapp.shared.fcm_token = fcmToken
884 if oldFCM != mpiosapp.shared.fcm_token {
885 mpiosapp.shared.isFCMTokenChanged = true
886 } else {
887 mpiosapp.shared.isFCMTokenChanged = false
888 }
889 UserDefaults.standard.set(fcmToken, forKey: defaultsKeys.tokenIdNew)
890 }
891
892 func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String){
893 if let oldFcmToken = UserDefaults.standard.string(forKey: defaultsKeys.tokenOld) {
894 UserDefaults.standard.set(fcmToken, forKey: defaultsKeys.tokenIdNew)
895 UserDefaults.standard.set(oldFcmToken, forKey: defaultsKeys.tokenOld)
896 }else{
897 UserDefaults.standard.set(fcmToken, forKey: defaultsKeys.tokenIdNew)
898 }
899 }
900
901 func logout() {
902
903 let network = NetworkCall()
904 network.apicall(api: API.LOGOUT, parameters: nil, completion: { response in
905
906 //self.showLoader()
907 if network.is_success{
908 self.removeAppSession()
909
910 let storyboard = UIStoryboard(name: "Login", bundle: nil)
911 let enterRegisteredNumberVC = storyboard.instantiateViewController(withIdentifier :"EnterRegisteredNumberVC") as! EnterRegisteredNumberVC
912
913 enterRegisteredNumberVC.alertID = AlertType.ACCESS_LEVEL_DENIED
914
915 if let window = self.window, let rootViewController = window.rootViewController {
916 var currentController = rootViewController
917 while let presentedController = currentController.presentedViewController {
918 currentController = presentedController
919 }
920 if currentController.isKind(of: UINavigationController.self) {
921 let navVC = currentController as! UINavigationController
922 navVC.pushViewController(enterRegisteredNumberVC, animated: true)
923 } else {
924 currentController.present(enterRegisteredNumberVC, animated: true, completion: nil)
925 }
926 }
927 }
928 else {
929 apppresentWindow!.makeToast(message: network.response_message)
930 }
931 })
932 }
933
934 func campaignResponse(responseValue: Int, notificationId: String?) {
935
936 self.registerBackgroundTask()
937
938 if notificationId != nil {
939
940 let parameters = [
941 "response": responseValue,
942 "noti_id": notificationId!
943 ] as [String : Any]
944 let network = NetworkCall()
945 network.apicall(api: API.CAMPAIGN_RESPONSE, parameters: parameters, completion: { response in
946 if network.is_success {
947
948 self.endBackgroundTask()
949 }
950 else {
951 apppresentWindow!.makeToast(message: network.response_message)
952 self.endBackgroundTask()
953 }
954 })
955 }
956 }
957
958 func removeAppSession(){
959
960 let userdefaults = UserDefaults.standard
961 userdefaults.removeObject(forKey: defaultsKeys.userOld)
962 userdefaults.removeObject(forKey: defaultsKeys.tokenOld)
963 userdefaults.removeObject(forKey: defaultsKeys.userIdNew)
964 userdefaults.removeObject(forKey: defaultsKeys.tokenIdNew)
965 userdefaults.removeObject(forKey: defaultsKeys.authorizationToken)
966 userdefaults.removeObject(forKey: defaultsKeys.customerName)
967 userdefaults.removeObject(forKey: defaultsKeys.isAuthUser)
968 userdefaults.removeObject(forKey: defaultsKeys.setupCompleted)
969 userdefaults.removeObject(forKey: defaultsKeys.accessRequestSent)
970 userdefaults.removeObject(forKey: defaultsKeys.ownerName)
971 userdefaults.removeObject(forKey: defaultsKeys.isAlreadyLoggedIn)
972 userdefaults.removeObject(forKey: defaultsKeys.numberAuthorizedRequest)
973 userdefaults.removeObject(forKey: defaultsKeys.nameAuthorizedRequest)
974 userdefaults.removeObject(forKey: defaultsKeys.isOnboardingDone)
975 userdefaults.removeObject(forKey: defaultsKeys.timeSession)
976 userdefaults.removeObject(forKey: defaultsKeys.accessToken)
977 userdefaults.removeObject(forKey: defaultsKeys.checkSetupStatus)
978 userdefaults.removeObject(forKey: defaultsKeys.videoLangIDSelected)
979 userdefaults.removeObject(forKey: defaultsKeys.userPreferredLang)
980 userdefaults.removeObject(forKey: defaultsKeys.currentLanguageCode)
981 userdefaults.removeObject(forKey: defaultsKeys.lastPopupShownDate)
982 userdefaults.removeObject(forKey: defaultsKeys.modeFrom)
983 userdefaults.removeObject(forKey: "TimeSessionDisconnect")
984
985 UIApplication.shared.applicationIconBadgeNumber = 0
986 UIApplication.shared.cancelAllLocalNotifications()
987 UIApplication.shared.shortcutItems?.removeAll()
988
989 setCurrentLanguageCode(selectedLanguageCode: "en")
990
991 mpiosapp.shared.isHomeNotificationObserverAdded = false
992 mpiosapp.shared.isLaunchNotificationObserverAdded = false
993 if appDelegate.isCastingStarted {
994 appDelegate.disConnect()
995 }
996 appDelegate.isCastingStarted = false
997 appDelegate.isCSASessionStarted = false
998 }
999
1000 func callLogout(code : Int) {
1001 // apppresentWindow?.makeToast(message: "call logout")
1002 if !isLoggedOut() {
1003 appDelegate.removeAppSession()
1004 let storyboard = UIStoryboard(name: "Login", bundle: nil)
1005 let enterRegisteredNumberVC = storyboard.instantiateViewController(withIdentifier :"EnterRegisteredNumberVC") as! EnterRegisteredNumberVC
1006
1007 enterRegisteredNumberVC.alertID = AlertType.ACCESS_LEVEL_DENIED
1008 enterRegisteredNumberVC.responseCodeLogout = code
1009
1010 if let window = self.window, let rootViewController = window.rootViewController {
1011 var currentController = rootViewController
1012 while let presentedController = currentController.presentedViewController {
1013 currentController = presentedController
1014 }
1015 if currentController.isKind(of: UINavigationController.self) {
1016 let navVC = currentController as! UINavigationController
1017 navVC.pushViewController(enterRegisteredNumberVC, animated: true)
1018 } else {
1019 currentController.present(enterRegisteredNumberVC, animated: true, completion: nil)
1020 }
1021 }
1022 }
1023 }
1024
1025 func sendAnalyticsData(){
1026
1027 print(Database.fetchCollectedData().count,"FETCH COLECTED DATA")
1028 // print("Background time remaining = \(UIApplication.shared.backgroundTimeRemaining) seconds")
1029
1030 let data = Database.fetchCollectedData()
1031
1032 if !data.isEmpty {
1033 var parameter: Parameters = [:]
1034 var analyticsList: [[String:Any]] = []
1035
1036 for analytics in data{
1037 var col: Parameters = [:]
1038 if let eventId = analytics.eventId{
1039 col["event_id"] = Int(eventId)
1040 }
1041 if let uniqueId = analytics.uniqueId {
1042 col["unique_id"] = uniqueId
1043 }
1044
1045 col["model_name"] = UIDevice.modelName
1046
1047 var innerCol: Parameters = [:]
1048
1049 if let eventTime = analytics.eventTime{
1050 innerCol["event_time"] = eventTime
1051 }
1052 if let startTime = analytics.startTime{
1053 innerCol["start_time"] = startTime
1054 }
1055 if let endTime = analytics.endTime{
1056 innerCol["end_time"] = endTime
1057 }
1058 if let serialNumber = analytics.serialNumber{
1059 innerCol["serial_number"] = serialNumber
1060 }
1061 if !innerCol.isEmpty {
1062 col["value"] = innerCol
1063 }
1064 analyticsList.append(col)
1065 }
1066
1067 parameter["data"] = analyticsList
1068 //print("Parameter is ",parameter)
1069 CollectData(parameter: parameter)
1070 }
1071 }
1072
1073 //Database.deleteCollectedData()
1074 func CollectData(parameter:Parameters){
1075
1076 var headers = Alamofire.SessionManager.defaultHTTPHeaders
1077 headers["user"] = UserDefaults.standard.string(forKey: defaultsKeys.analyticsUserId)
1078 headers["AUTHORIZATION"] = UserDefaults.standard.string(forKey: defaultsKeys.analyticsAuthorizationToken)
1079 headers["osType"] = String(os_type)
1080 headers["versionCode"] = Miscellaneous.getVersionCode()
1081 headers["timeZone"] = UserDefaults.standard.string(forKey: defaultsKeys.timezone)
1082 headers["Content-Type"] = "application/json"
1083 let parameters = parameter
1084
1085 print("DATA IS ",parameters)
1086
1087 Alamofire.request("\(NetworkCall.BaseURL)v3/track/collect_analytics/",method: .post, parameters: parameters,encoding: JSONEncoding.default,headers: headers)
1088 .responseData { response in
1089
1090 if response.response?.statusCode == 200 {
1091 print("DATA SUCCESSFULLY SUBMITTED TO APP SERVER")
1092
1093 Database.deleteCollectedData()
1094 self.sendAnalyticsData()
1095 }
1096 }
1097 }
1098}
1099
1100
1101//PUSH NOTIFICATION FUNCTION
1102extension AppDelegate{
1103
1104 // Notification part from old app
1105 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
1106 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
1107
1108 if let dataString = userInfo["data"] as? String{
1109 if let data = convertToDictionarys(text: dataString){
1110 if let alertType = data["alertType"] as? Int{
1111 if isLoggedOut(){return}
1112 if #available(iOS 10.0, *) {
1113 if let serialNumber = data["serial_number"] as? String {
1114 if alertType == AlertType.IMMOBILIZE_ACTIVATED || alertType == AlertType.IMMOBILIZATION_REQUEST || alertType == AlertType.IMMOBILIZE_TRACKER_OUT_OF_NETWORK || alertType == AlertType.MOBILIZE_ACTIVATED || alertType == AlertType.MOBILIZE_REQUEST || alertType == AlertType.MOBILIZE_TRACKER_OUT_OF_NETWORK {
1115
1116 if serialNumber == mpiosapp.shared.activeVehicleResponse?.strSerial_no {
1117 let dict = ["alertType":alertType]
1118 NotificationCenter.default.post(name: Notification.Name(rawValue: IMMOBILIZATION_ALERT), object: nil,userInfo: dict)
1119 }
1120 }
1121 }
1122 return
1123 } else {
1124 print("**** didRecieveRemoteNotification with handler ****** \(userInfo)")
1125 if(application.applicationState == .active){
1126 print("Application in foreground state")
1127 if let aps = userInfo["aps"] as? NSDictionary {
1128 if let message = aps["alert"] as? NSDictionary{
1129 if let body=message["body"] as? String{
1130 if let title=message["title"] as? String{
1131 self.showNotification(title, message: body,remoteNotification: userInfo)
1132 }
1133 }
1134 }
1135 }
1136 NotificationCenter.default.post(name: Notification.Name(rawValue: NOTIFICATION_UPDATE), object: nil)
1137 }else if(application.applicationState == .inactive){
1138 print("Application was in inactive state with userinfo\(userInfo)")
1139 NotificationCenter.default.post(name: Notification.Name(rawValue: "Notification Recieved"), object: nil,userInfo: userInfo)
1140
1141 } else if application.applicationState == .background {
1142 print("Application in background state")
1143 if let aps = userInfo["aps"] as? NSDictionary {
1144 if let message = aps["alert"] as? NSDictionary {
1145 if let body=message["body"] as? String {
1146
1147 if let title=message["title"] as? String {
1148 self.showNotification(title, message: body,remoteNotification: userInfo)
1149 }
1150 }
1151 }
1152 }
1153 NotificationCenter.default.post(name: Notification.Name(rawValue: NOTIFICATION_UPDATE), object: nil)
1154 }
1155 completionHandler(UIBackgroundFetchResult.newData)
1156 }
1157
1158 }else{
1159 pinpoint!.notificationManager.interceptDidReceiveRemoteNotification(userInfo, fetchCompletionHandler: completionHandler)
1160 }
1161 }
1162 }
1163 }
1164
1165 // Firebase notification received
1166 @available(iOS 10.0, *)
1167 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
1168
1169 if let dataString = notification.request.content.userInfo["data"] as? String{
1170 if let data = convertToDictionarys(text: dataString){
1171 if let _ = data["alertType"] as? Int{
1172 if isLoggedOut(){return}
1173 var dicUserInfo : [AnyHashable : Any] = notification.request.content.userInfo
1174 dicUserInfo["notificationType"] = NotificationType.foreground
1175 print("Handle push from foreground\(notification.request.content.userInfo)")
1176 let presentNotification = doWithNotification(userInfo: notification.request.content.userInfo, notificationType: .foreground)
1177 if presentNotification {
1178 completionHandler(UNNotificationPresentationOptions.alert)
1179 } else {
1180 NotificationCenter.default.post(name: Notification.Name(rawValue: "Notification Recieved"), object: nil,userInfo: dicUserInfo)
1181 }
1182 }else{
1183 pinpoint!.notificationManager.interceptDidReceiveRemoteNotification(notification.request.content.userInfo, fetchCompletionHandler: {(UIBackgroundFetchResult) in })
1184 }
1185 }
1186 }
1187 }
1188
1189 @available(iOS 10.0, *)
1190 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
1191 if let dataString = response.notification.request.content.userInfo["data"] as? String{
1192 if let data = convertToDictionarys(text: dataString){
1193 if let _ = data["alertType"] as? Int{
1194 mpiosapp.shared.isNotificationFromKillState = true
1195 print("Handle push from background or closed\(response.notification.request.content.userInfo)")
1196 var dicUserInfo : [AnyHashable : Any] = response.notification.request.content.userInfo
1197 dicUserInfo["notificationType"] = NotificationType.background
1198 dicUserInfo["action_type"] = response.actionIdentifier
1199 print("Action idetifier \(dicUserInfo["action_type"] as? String)")
1200 mpiosapp.shared.userInfo = dicUserInfo
1201 NotificationCenter.default.post(name: Notification.Name(rawValue: "Notification Recieved"), object: nil,userInfo: dicUserInfo)
1202 completionHandler()
1203 }else{
1204 pinpoint!.notificationManager.interceptDidReceiveRemoteNotification(response.notification.request.content.userInfo, fetchCompletionHandler: {(UIBackgroundFetchResult) in })
1205 }
1206 }
1207 }
1208
1209
1210
1211 }
1212
1213}
1214
1215extension AppDelegate : CLLocationManagerDelegate {
1216 func initUserLocation(){
1217 self.locationManager.delegate = self
1218 self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
1219 self.locationManager.requestWhenInUseAuthorization()
1220 self.locationManager.startUpdatingLocation()
1221 }
1222
1223 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
1224 guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
1225 // print("locations = \(locValue.latitude) \(locValue.longitude)")
1226 mpiosapp.shared.currentLocation = locValue
1227 }
1228}
1229
1230extension UIApplication {
1231 class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
1232 if let navigationController = controller as? UINavigationController {
1233 return topViewController(controller: navigationController.visibleViewController)
1234 }
1235 if let tabController = controller as? UITabBarController {
1236 if let selected = tabController.selectedViewController {
1237 return topViewController(controller: selected)
1238 }
1239 }
1240 if let presented = controller?.presentedViewController {
1241 return topViewController(controller: presented)
1242 }
1243 return controller
1244 }
1245}