Advertisement
Guest User

Untitled

a guest
Dec 21st, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 17.31 KB | None | 0 0
  1. //
  2. //  AppDelegate.swift
  3. //  Annanow Postman
  4. //
  5. //  Created by Boris Nikolic on 10/21/16.
  6. //  Copyright © 2016 Annanow Group AG. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import IQKeyboardManagerSwift
  11. import Hue
  12. import GoogleMaps
  13. import RealmSwift
  14. import Fabric
  15. import Crashlytics
  16. import UserNotifications
  17. import FirebaseCore
  18. import FirebaseDatabase
  19. import FirebaseMessaging
  20. import FirebaseInstanceID
  21. import PKHUD
  22. import SwiftyBeaver
  23. import SwiftMessages
  24. import AudioToolbox
  25. import Localize_Swift
  26. import Kingfisher
  27. import AlamofireNetworkActivityIndicator
  28.  
  29. let app = UIApplication.shared.delegate as! AppDelegate
  30. let log = SwiftyBeaver.self
  31. let cache = KingfisherManager.shared.cache
  32.  
  33. @UIApplicationMain
  34. class AppDelegate: UIResponder, UIApplicationDelegate {
  35.    
  36.     var window: UIWindow?
  37.     public var currentLocation: CLLocation?
  38.     var updateAlertIsNotCurrentlyShown = true
  39.     let gcmMessageIDKey = "gcm.message_id"
  40.     let tokenManager = TokenManager()
  41.  
  42.     lazy var dateFormatter: DateFormatter = {
  43.         let formatter = DateFormatter()
  44.         formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
  45.         formatter.timeZone = TimeZone(abbreviation: "UTC")
  46.         return formatter
  47.     }()
  48.  
  49.     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  50.         try? Reachability.shared?.startNotifier()
  51.         NetworkActivityIndicatorManager.shared.isEnabled = true
  52.         setupGoogleServices()
  53.         FirebaseApp.configure()
  54.         registerForNotifications(application: application)
  55.         Database.database().isPersistenceEnabled = true
  56.         setupIQKeyboard()
  57.         Fabric.with([Crashlytics.self])
  58.         setupLogging()
  59.         Localize.resetCurrentLanguageToDefault()
  60.         addObservers()
  61.         return true
  62.     }
  63.    
  64.     func applicationDidBecomeActive(_ application: UIApplication) {
  65.         NotificationCenter.default.post(name: .loopVideo, object: nil)
  66.     }
  67.  
  68.     deinit {
  69.         NotificationCenter.default.removeObserver(self)
  70.     }
  71.  
  72.     fileprivate func addObservers() {
  73.         NotificationCenter.default.addObserver(self, selector: #selector(didTapReturnToPreviousView(_:)), name: .returnToPreviousViewAction, object: nil)
  74.         NotificationCenter.default.addObserver(self, selector: #selector(didReceiveMessagesDeleted(_:)), name: .MessagingMessagesDeleted, object: nil)
  75.     }
  76.  
  77.     fileprivate func setupGoogleServices() {
  78.         var configuration = Configuration()
  79.         GMSServices.provideAPIKey(configuration.environment.googleAPIKey)
  80.     }
  81.    
  82.     fileprivate func setupIQKeyboard() {
  83.         IQKeyboardManager.sharedManager().enable = true
  84.         IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
  85.         IQKeyboardManager.sharedManager().disabledToolbarClasses = [TextFieldViewController.self]
  86.         IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses = [TextFieldViewController.self]
  87.         IQKeyboardManager.sharedManager().disabledTouchResignedClasses = [TextFieldViewController.self]
  88.     }
  89.    
  90.     func changePresentedViewController(to controller: UIViewController.Type, from parent: UIViewController?) {
  91.         let desiredViewController = controller.storyboardViewController
  92.         let snapshot:UIView = (self.window?.snapshotView(afterScreenUpdates: true))!
  93.         let controller = desiredViewController()
  94.         controller.view.addSubview(snapshot)
  95.         configure(controller, from: parent)
  96.         self.window?.rootViewController = controller
  97.         UIView.animate(withDuration: 0.5, animations: {() in
  98.             snapshot.layer.opacity = 0
  99.             snapshot.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
  100.         }, completion: {
  101.             (value: Bool) in
  102.             snapshot.removeFromSuperview()
  103.         })
  104.     }
  105.  
  106.     private func configure(_ controller: UIViewController, from parent: UIViewController?) {
  107.         if let vc = controller as? UserPhoneNumberRegistrationViewController {
  108.             if let parent = parent as? LoginBaseContainerViewController {
  109.                 vc.countryCallingCodeService = parent.countryCallingCodeService
  110.                 vc.userService = parent.userService
  111.                 vc.newUserDataProvider = NewUserDataProvider()
  112.             } else if let parent = parent as? UserPhoneNumberRegistrationCodeVerificationViewController {
  113.                 vc.countryCallingCodeService = parent.countryCallingCodeService
  114.                 vc.userService = parent.userService
  115.                 vc.newUserDataProvider = parent.newUserDataProvider
  116.             }
  117.             return
  118.         }        
  119.         if let vc = controller as? UserPhoneNumberRegistrationCodeVerificationViewController {
  120.             if let parent = parent as? UserPhoneNumberRegistrationViewController {
  121.                 vc.countryCallingCodeService = parent.countryCallingCodeService
  122.                 vc.userService = parent.userService
  123.                 vc.newUserDataProvider = parent.newUserDataProvider
  124.             }
  125.             return
  126.         }
  127.         if let vc = controller as? UserCredentialsRegistrationViewController {
  128.             if let parent = parent as? UserPhoneNumberRegistrationCodeVerificationViewController {
  129.                 vc.countryCallingCodeService = parent.countryCallingCodeService
  130.                 vc.userService = parent.userService
  131.                 vc.newUserDataProvider = parent.newUserDataProvider
  132.             } else if let parent = parent as? UserProfileRegistrationViewController {
  133.                 vc.countryCallingCodeService = parent.countryCallingCodeService
  134.                 vc.userService = parent.userService
  135.                 vc.newUserDataProvider = parent.newUserDataProvider
  136.             }
  137.         }
  138.         if let vc = controller as? UserProfileRegistrationViewController {
  139.             if let parent = parent as? UserCredentialsRegistrationViewController {
  140.                 vc.countryCallingCodeService = parent.countryCallingCodeService
  141.                 vc.userService = parent.userService
  142.                 vc.newUserDataProvider = parent.newUserDataProvider
  143.                 vc.photoService = PhotoService(presenter: vc)
  144.             }
  145.             if let parent = parent as? UserModeOfTransportationRegistrationViewController {
  146.                 vc.countryCallingCodeService = parent.countryCallingCodeService
  147.                 vc.userService = parent.userService
  148.                 vc.newUserDataProvider = parent.newUserDataProvider
  149.                 vc.photoService = PhotoService(presenter: vc)
  150.             }
  151.         }
  152.         if let vc = controller as? UserModeOfTransportationRegistrationViewController {
  153.             if let parent = parent as? UserProfileRegistrationViewController {
  154.                 vc.newUserDataProvider = parent.newUserDataProvider
  155.                 vc.userService = parent.userService
  156.                 vc.countryCallingCodeService = parent.countryCallingCodeService
  157.             }
  158.         }
  159.         if let vc = controller as? MainBaseViewController {
  160.             if let _ = parent as? UserModeOfTransportationRegistrationViewController {
  161.                 //TODO: provide services
  162.             } else if let parent = parent as? LoginContentViewController {
  163.                 vc.userService = parent.userService
  164.             }
  165.         }
  166.     }
  167.  
  168.     @objc private func didTapReturnToPreviousView(_ notification: Notification) {
  169.         guard let userInfo = notification.userInfo, let returningViewPolicy = userInfo["returningViewPolicy"] as? ReturningViewPolicy else {
  170.             return
  171.         }
  172.         returnToPreviousView(policy: returningViewPolicy)
  173.     }
  174.  
  175.     @objc private func didReceiveMessagesDeleted(_ notification: Notification) {
  176.         //Notification sent when the Firebase messaging server deletes pending messages due to exceeded storage limits.
  177.         //This may occur, for example, when the device cannot be reached for an extended period of time.
  178.         //It is recommended to retrieve any missing messages directly from the server.
  179.         guard let userInfo = notification.userInfo else {
  180.             return
  181.         }
  182.         log.debug("[DEBUG] FCM deletes messages : \(userInfo)")
  183.     }
  184.  
  185.     fileprivate func returnToPreviousView(policy returningViewPolicy: ReturningViewPolicy) {
  186.         switch returningViewPolicy {
  187.         case .login:
  188.             break
  189.         case .forgotPassword:
  190.             break
  191.         case .registrationLogin:
  192.             changePresentedViewController(to: LoginBaseContainerViewController.self, from: self.window?.rootViewController)
  193.         case .createAccountPhoneNumber:
  194.             changePresentedViewController(to: UserPhoneNumberRegistrationViewController.self, from: self.window?.rootViewController)
  195.         case .createAccountCredentials:
  196.             changePresentedViewController(to: UserCredentialsRegistrationViewController.self, from: self.window?.rootViewController)
  197.         case .createAccountProfile:
  198.             changePresentedViewController(to: UserProfileRegistrationViewController.self, from: self.window?.rootViewController)
  199.         }
  200.     }
  201.    
  202. }
  203.  
  204. extension AppDelegate{
  205.    
  206.     fileprivate func registerForNotifications(application: UIApplication){
  207.         if #available(iOS 10.0, *) {
  208.             // For iOS 10 display notification (sent via APNS)
  209.             UNUserNotificationCenter.current().delegate = self
  210.             // For iOS 10 data message (sent via FCM)
  211.             Messaging.messaging().delegate = self
  212.             let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
  213.             UNUserNotificationCenter.current().requestAuthorization(options: authOptions,completionHandler: {_, _ in})
  214.         } else {
  215.             let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  216.             application.registerUserNotificationSettings(settings)
  217.         }
  218.         application.registerForRemoteNotifications()
  219.         // Add observer for InstanceID token refresh callback.
  220.         NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: .InstanceIDTokenRefresh, object: nil)
  221.     }
  222.  
  223.     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  224.         log.debug("[DEBUG] APNs token retrieved: \(deviceToken.description), \(#function)")
  225. //        Messaging.messaging().apnsToken = deviceToken
  226.     }
  227.  
  228.     func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
  229.         // If you are receiving a notification message while your app is in the background,
  230.         // this callback will not be fired till the user taps on the notification launching the application.
  231.         // TODO: Handle data of notification
  232.         log.debug("[DEBUG] REMOTE NOTIFICATION: \(userInfo), \(#function)")
  233.         handleNotification(userInfo: userInfo)
  234.         // With swizzling disabled you must let Messaging know about the message, for Analytics
  235.         Messaging.messaging().appDidReceiveMessage(userInfo)
  236.         if let messageID = userInfo[gcmMessageIDKey] {
  237.             log.debug("[DEBUG] REMOTE NOTIFICATION MESSAGE ID: \(messageID)")
  238.         }
  239.     }
  240.    
  241.     func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
  242.                      fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  243.         log.debug("[DEBUG] REMOTE NOTIFICATION: \(userInfo), \(#function)")
  244.         handleNotification(userInfo: userInfo)
  245.         //TODO: With swizzling disabled you must let Messaging know about the message, for Analytics
  246.         Messaging.messaging().appDidReceiveMessage(userInfo)
  247.         if let messageID = userInfo[gcmMessageIDKey] {
  248.             log.debug("[DEBUG] REMOTE NOTIFICATION MESSAGE ID: \(messageID)")
  249.         }
  250.         completionHandler(.newData)
  251.     }
  252.    
  253.     func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  254.         log.error("[ERROR] Unable to register for remote notifications: \(error.localizedDescription) ")
  255.     }
  256.    
  257.     @objc func tokenRefreshNotification(_ notification: Notification) {
  258.         sendFirebaseTokenToBackend()
  259.     }
  260.    
  261.     public func sendFirebaseTokenToBackend(){
  262.         if tokenManager.hasToken() {
  263.             if let token = InstanceID.instanceID().token(){
  264.                 let userService = UserService()
  265.                 userService.update(token: token) { (success, error) in
  266.                     if success {
  267.                         log.debug("[DEBUG] Server updated with Firebase token")
  268.                     }else{
  269.                         if let error = error {
  270.                             log.error("[ERROR] Update server with Firebase token failed - error : \(error.localizedDescription)")
  271.                         }
  272.                     }
  273.                 }
  274.             }
  275.         }
  276.     }
  277.    
  278.     fileprivate func handleNotification(userInfo: [AnyHashable: Any]) {
  279.         log.debug("HANDLING NOTIFICATION: \(userInfo)")
  280.         if let notificationType = userInfo["notification"] as? String {
  281.             if let type = RemoteNotificationType(rawValue: notificationType) {
  282.                 let handler = notificationHandler(of: type)
  283.                 handler?.handleNotification()
  284.             }
  285.         }
  286.     }
  287.    
  288.     fileprivate func notificationHandler(of type: RemoteNotificationType) -> NotificationHandler? {
  289.         var handler: NotificationHandler?
  290.         switch type {
  291.         case RemoteNotificationType.postmanAccepted:
  292.             handler = NotificationHandlerPostmanAccepted()
  293.         case RemoteNotificationType.postmanRejected:
  294.             handler = NotificationHandlerPostmanRejected()
  295.         case RemoteNotificationType.postmanBanned:
  296.             handler = NotificationHandlerPostmanBanned()
  297.         case RemoteNotificationType.newOrderAddedOnMap:
  298.             handler = NotificationHandlerNewOrder()
  299.         case RemoteNotificationType.refreshMap:
  300.             handler = NotificationHandlerRefreshMap()
  301.         case RemoteNotificationType.logoutUser:
  302.             handler = NotificationHandlerLogOut()
  303.         case RemoteNotificationType.deliveryFinishedByAdmin:
  304.             handler = NotificationHandlerDeliveryFinished()
  305.         case RemoteNotificationType.orderCanceledByAdmin:
  306.             handler = NotificationHandlerOrderCancelled()
  307.         }
  308.         return handler
  309.     }
  310.    
  311.    
  312.     fileprivate func setupLogging(){
  313.         if let bundleID = Bundle.main.bundleIdentifier, bundleID != "com.annanow.Annanow-Postman" {
  314.             let console = ConsoleDestination()
  315.             log.addDestination(console)
  316.         }
  317.         let cloud = SBPlatformDestination(appID: "E9QrqL", appSecret: "axrqjS2ipmiungzehpshoqHlk28bmeor", encryptionKey: "rM7gKpca5sdsVAodmkR7RpbgionwtgSt")
  318.         log.addDestination(cloud)
  319.     }
  320. }
  321.  
  322. // [START ios_10_message_handling]
  323. @available(iOS 10, *)
  324. extension AppDelegate : UNUserNotificationCenterDelegate {
  325.    
  326.     // Receive displayed notifications for iOS 10 devices.
  327.     func userNotificationCenter(_ center: UNUserNotificationCenter,
  328.                                 willPresent notification: UNNotification,
  329.                                 withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  330.         let userInfo = notification.request.content.userInfo
  331.         // With swizzling disabled you must let Messaging know about the message, for Analytics
  332.         Messaging.messaging().appDidReceiveMessage(userInfo)
  333.  
  334.         if let messageID = userInfo[gcmMessageIDKey] {
  335.             log.debug("[DEBUG] REMOTE NOTIFICATION MESSAGE ID: \(messageID)")
  336.         }
  337.        
  338.         // Print full message.
  339.         log.debug("[DEBUG] REMOTE NOTIFICATION: \(userInfo), \(#function)")
  340.         handleNotification(userInfo: userInfo)
  341.         //TODO: Change this to your preferred presentation option
  342.         completionHandler([])
  343.     }
  344.  
  345.     func userNotificationCenter(_ center: UNUserNotificationCenter,
  346.                                 didReceive response: UNNotificationResponse,
  347.                                 withCompletionHandler completionHandler: @escaping () -> Void) {
  348.         let userInfo = response.notification.request.content.userInfo
  349.         // Print message ID.
  350.         if let messageID = userInfo[gcmMessageIDKey] {
  351.             log.debug("[DEBUG] REMOTE NOTIFICATION MESSAGE ID: \(messageID)")
  352.         }
  353.         // Print full message.
  354.         log.debug("[DEBUG] REMOTE NOTIFICATION: \(userInfo), \(#function)")
  355.         handleNotification(userInfo: userInfo)
  356.         completionHandler()
  357.     }
  358. }
  359.  
  360. extension AppDelegate : MessagingDelegate {
  361.     // Receive data message on iOS 10 devices.
  362.     func application(received remoteMessage: MessagingRemoteMessage) {
  363.         let userInfo = remoteMessage.appData
  364.         handleNotification(userInfo: userInfo)
  365.     }
  366.    
  367.     func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
  368.         log.debug("[DEBUG] REMOTE-MSG: \(remoteMessage.appData)")
  369.     }
  370.    
  371.     func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  372.         //TODO: here backend should be updated with token
  373.         // FCM provides a registration token via this func
  374.         log.debug("[DEBUG] FCM-TOKEN: \(fcmToken)")
  375.         sendFirebaseTokenToBackend()
  376.     }
  377. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement