Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // AppDelegate.swift
- // Annanow Postman
- //
- // Created by Boris Nikolic on 10/21/16.
- // Copyright © 2016 Annanow Group AG. All rights reserved.
- //
- import UIKit
- import IQKeyboardManagerSwift
- import Hue
- import GoogleMaps
- import RealmSwift
- import Fabric
- import Crashlytics
- import UserNotifications
- import FirebaseCore
- import FirebaseDatabase
- import FirebaseMessaging
- import FirebaseInstanceID
- import PKHUD
- import SwiftyBeaver
- import SwiftMessages
- import AudioToolbox
- import Localize_Swift
- import Kingfisher
- import AlamofireNetworkActivityIndicator
- let app = UIApplication.shared.delegate as! AppDelegate
- let log = SwiftyBeaver.self
- let cache = KingfisherManager.shared.cache
- @UIApplicationMain
- class AppDelegate: UIResponder, UIApplicationDelegate {
- var window: UIWindow?
- public var currentLocation: CLLocation?
- var updateAlertIsNotCurrentlyShown = true
- let gcmMessageIDKey = "gcm.message_id"
- let tokenManager = TokenManager()
- lazy var dateFormatter: DateFormatter = {
- let formatter = DateFormatter()
- formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
- formatter.timeZone = TimeZone(abbreviation: "UTC")
- return formatter
- }()
- func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
- try? Reachability.shared?.startNotifier()
- NetworkActivityIndicatorManager.shared.isEnabled = true
- setupGoogleServices()
- FirebaseApp.configure()
- registerForNotifications(application: application)
- Database.database().isPersistenceEnabled = true
- setupIQKeyboard()
- Fabric.with([Crashlytics.self])
- setupLogging()
- Localize.resetCurrentLanguageToDefault()
- addObservers()
- return true
- }
- func applicationDidBecomeActive(_ application: UIApplication) {
- NotificationCenter.default.post(name: .loopVideo, object: nil)
- }
- deinit {
- NotificationCenter.default.removeObserver(self)
- }
- fileprivate func addObservers() {
- NotificationCenter.default.addObserver(self, selector: #selector(didTapReturnToPreviousView(_:)), name: .returnToPreviousViewAction, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(didReceiveMessagesDeleted(_:)), name: .MessagingMessagesDeleted, object: nil)
- }
- fileprivate func setupGoogleServices() {
- var configuration = Configuration()
- GMSServices.provideAPIKey(configuration.environment.googleAPIKey)
- }
- fileprivate func setupIQKeyboard() {
- IQKeyboardManager.sharedManager().enable = true
- IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
- IQKeyboardManager.sharedManager().disabledToolbarClasses = [TextFieldViewController.self]
- IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses = [TextFieldViewController.self]
- IQKeyboardManager.sharedManager().disabledTouchResignedClasses = [TextFieldViewController.self]
- }
- func changePresentedViewController(to controller: UIViewController.Type, from parent: UIViewController?) {
- let desiredViewController = controller.storyboardViewController
- let snapshot:UIView = (self.window?.snapshotView(afterScreenUpdates: true))!
- let controller = desiredViewController()
- controller.view.addSubview(snapshot)
- configure(controller, from: parent)
- self.window?.rootViewController = controller
- UIView.animate(withDuration: 0.5, animations: {() in
- snapshot.layer.opacity = 0
- snapshot.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5)
- }, completion: {
- (value: Bool) in
- snapshot.removeFromSuperview()
- })
- }
- private func configure(_ controller: UIViewController, from parent: UIViewController?) {
- if let vc = controller as? UserPhoneNumberRegistrationViewController {
- if let parent = parent as? LoginBaseContainerViewController {
- vc.countryCallingCodeService = parent.countryCallingCodeService
- vc.userService = parent.userService
- vc.newUserDataProvider = NewUserDataProvider()
- } else if let parent = parent as? UserPhoneNumberRegistrationCodeVerificationViewController {
- vc.countryCallingCodeService = parent.countryCallingCodeService
- vc.userService = parent.userService
- vc.newUserDataProvider = parent.newUserDataProvider
- }
- return
- }
- if let vc = controller as? UserPhoneNumberRegistrationCodeVerificationViewController {
- if let parent = parent as? UserPhoneNumberRegistrationViewController {
- vc.countryCallingCodeService = parent.countryCallingCodeService
- vc.userService = parent.userService
- vc.newUserDataProvider = parent.newUserDataProvider
- }
- return
- }
- if let vc = controller as? UserCredentialsRegistrationViewController {
- if let parent = parent as? UserPhoneNumberRegistrationCodeVerificationViewController {
- vc.countryCallingCodeService = parent.countryCallingCodeService
- vc.userService = parent.userService
- vc.newUserDataProvider = parent.newUserDataProvider
- } else if let parent = parent as? UserProfileRegistrationViewController {
- vc.countryCallingCodeService = parent.countryCallingCodeService
- vc.userService = parent.userService
- vc.newUserDataProvider = parent.newUserDataProvider
- }
- }
- if let vc = controller as? UserProfileRegistrationViewController {
- if let parent = parent as? UserCredentialsRegistrationViewController {
- vc.countryCallingCodeService = parent.countryCallingCodeService
- vc.userService = parent.userService
- vc.newUserDataProvider = parent.newUserDataProvider
- vc.photoService = PhotoService(presenter: vc)
- }
- if let parent = parent as? UserModeOfTransportationRegistrationViewController {
- vc.countryCallingCodeService = parent.countryCallingCodeService
- vc.userService = parent.userService
- vc.newUserDataProvider = parent.newUserDataProvider
- vc.photoService = PhotoService(presenter: vc)
- }
- }
- if let vc = controller as? UserModeOfTransportationRegistrationViewController {
- if let parent = parent as? UserProfileRegistrationViewController {
- vc.newUserDataProvider = parent.newUserDataProvider
- vc.userService = parent.userService
- vc.countryCallingCodeService = parent.countryCallingCodeService
- }
- }
- if let vc = controller as? MainBaseViewController {
- if let _ = parent as? UserModeOfTransportationRegistrationViewController {
- //TODO: provide services
- } else if let parent = parent as? LoginContentViewController {
- vc.userService = parent.userService
- }
- }
- }
- @objc private func didTapReturnToPreviousView(_ notification: Notification) {
- guard let userInfo = notification.userInfo, let returningViewPolicy = userInfo["returningViewPolicy"] as? ReturningViewPolicy else {
- return
- }
- returnToPreviousView(policy: returningViewPolicy)
- }
- @objc private func didReceiveMessagesDeleted(_ notification: Notification) {
- //Notification sent when the Firebase messaging server deletes pending messages due to exceeded storage limits.
- //This may occur, for example, when the device cannot be reached for an extended period of time.
- //It is recommended to retrieve any missing messages directly from the server.
- guard let userInfo = notification.userInfo else {
- return
- }
- log.debug("[DEBUG] FCM deletes messages : \(userInfo)")
- }
- fileprivate func returnToPreviousView(policy returningViewPolicy: ReturningViewPolicy) {
- switch returningViewPolicy {
- case .login:
- break
- case .forgotPassword:
- break
- case .registrationLogin:
- changePresentedViewController(to: LoginBaseContainerViewController.self, from: self.window?.rootViewController)
- case .createAccountPhoneNumber:
- changePresentedViewController(to: UserPhoneNumberRegistrationViewController.self, from: self.window?.rootViewController)
- case .createAccountCredentials:
- changePresentedViewController(to: UserCredentialsRegistrationViewController.self, from: self.window?.rootViewController)
- case .createAccountProfile:
- changePresentedViewController(to: UserProfileRegistrationViewController.self, from: self.window?.rootViewController)
- }
- }
- }
- extension AppDelegate{
- fileprivate func registerForNotifications(application: UIApplication){
- if #available(iOS 10.0, *) {
- // For iOS 10 display notification (sent via APNS)
- UNUserNotificationCenter.current().delegate = self
- // For iOS 10 data message (sent via FCM)
- Messaging.messaging().delegate = self
- let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
- UNUserNotificationCenter.current().requestAuthorization(options: authOptions,completionHandler: {_, _ in})
- } else {
- let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
- application.registerUserNotificationSettings(settings)
- }
- application.registerForRemoteNotifications()
- // Add observer for InstanceID token refresh callback.
- NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: .InstanceIDTokenRefresh, object: nil)
- }
- func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
- log.debug("[DEBUG] APNs token retrieved: \(deviceToken.description), \(#function)")
- // Messaging.messaging().apnsToken = deviceToken
- }
- func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
- // If you are receiving a notification message while your app is in the background,
- // this callback will not be fired till the user taps on the notification launching the application.
- // TODO: Handle data of notification
- log.debug("[DEBUG] REMOTE NOTIFICATION: \(userInfo), \(#function)")
- handleNotification(userInfo: userInfo)
- // With swizzling disabled you must let Messaging know about the message, for Analytics
- Messaging.messaging().appDidReceiveMessage(userInfo)
- if let messageID = userInfo[gcmMessageIDKey] {
- log.debug("[DEBUG] REMOTE NOTIFICATION MESSAGE ID: \(messageID)")
- }
- }
- func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
- fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
- log.debug("[DEBUG] REMOTE NOTIFICATION: \(userInfo), \(#function)")
- handleNotification(userInfo: userInfo)
- //TODO: With swizzling disabled you must let Messaging know about the message, for Analytics
- Messaging.messaging().appDidReceiveMessage(userInfo)
- if let messageID = userInfo[gcmMessageIDKey] {
- log.debug("[DEBUG] REMOTE NOTIFICATION MESSAGE ID: \(messageID)")
- }
- completionHandler(.newData)
- }
- func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
- log.error("[ERROR] Unable to register for remote notifications: \(error.localizedDescription) ")
- }
- @objc func tokenRefreshNotification(_ notification: Notification) {
- sendFirebaseTokenToBackend()
- }
- public func sendFirebaseTokenToBackend(){
- if tokenManager.hasToken() {
- if let token = InstanceID.instanceID().token(){
- let userService = UserService()
- userService.update(token: token) { (success, error) in
- if success {
- log.debug("[DEBUG] Server updated with Firebase token")
- }else{
- if let error = error {
- log.error("[ERROR] Update server with Firebase token failed - error : \(error.localizedDescription)")
- }
- }
- }
- }
- }
- }
- fileprivate func handleNotification(userInfo: [AnyHashable: Any]) {
- log.debug("HANDLING NOTIFICATION: \(userInfo)")
- if let notificationType = userInfo["notification"] as? String {
- if let type = RemoteNotificationType(rawValue: notificationType) {
- let handler = notificationHandler(of: type)
- handler?.handleNotification()
- }
- }
- }
- fileprivate func notificationHandler(of type: RemoteNotificationType) -> NotificationHandler? {
- var handler: NotificationHandler?
- switch type {
- case RemoteNotificationType.postmanAccepted:
- handler = NotificationHandlerPostmanAccepted()
- case RemoteNotificationType.postmanRejected:
- handler = NotificationHandlerPostmanRejected()
- case RemoteNotificationType.postmanBanned:
- handler = NotificationHandlerPostmanBanned()
- case RemoteNotificationType.newOrderAddedOnMap:
- handler = NotificationHandlerNewOrder()
- case RemoteNotificationType.refreshMap:
- handler = NotificationHandlerRefreshMap()
- case RemoteNotificationType.logoutUser:
- handler = NotificationHandlerLogOut()
- case RemoteNotificationType.deliveryFinishedByAdmin:
- handler = NotificationHandlerDeliveryFinished()
- case RemoteNotificationType.orderCanceledByAdmin:
- handler = NotificationHandlerOrderCancelled()
- }
- return handler
- }
- fileprivate func setupLogging(){
- if let bundleID = Bundle.main.bundleIdentifier, bundleID != "com.annanow.Annanow-Postman" {
- let console = ConsoleDestination()
- log.addDestination(console)
- }
- let cloud = SBPlatformDestination(appID: "E9QrqL", appSecret: "axrqjS2ipmiungzehpshoqHlk28bmeor", encryptionKey: "rM7gKpca5sdsVAodmkR7RpbgionwtgSt")
- log.addDestination(cloud)
- }
- }
- // [START ios_10_message_handling]
- @available(iOS 10, *)
- extension AppDelegate : UNUserNotificationCenterDelegate {
- // Receive displayed notifications for iOS 10 devices.
- func userNotificationCenter(_ center: UNUserNotificationCenter,
- willPresent notification: UNNotification,
- withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
- let userInfo = notification.request.content.userInfo
- // With swizzling disabled you must let Messaging know about the message, for Analytics
- Messaging.messaging().appDidReceiveMessage(userInfo)
- if let messageID = userInfo[gcmMessageIDKey] {
- log.debug("[DEBUG] REMOTE NOTIFICATION MESSAGE ID: \(messageID)")
- }
- // Print full message.
- log.debug("[DEBUG] REMOTE NOTIFICATION: \(userInfo), \(#function)")
- handleNotification(userInfo: userInfo)
- //TODO: Change this to your preferred presentation option
- completionHandler([])
- }
- func userNotificationCenter(_ center: UNUserNotificationCenter,
- didReceive response: UNNotificationResponse,
- withCompletionHandler completionHandler: @escaping () -> Void) {
- let userInfo = response.notification.request.content.userInfo
- // Print message ID.
- if let messageID = userInfo[gcmMessageIDKey] {
- log.debug("[DEBUG] REMOTE NOTIFICATION MESSAGE ID: \(messageID)")
- }
- // Print full message.
- log.debug("[DEBUG] REMOTE NOTIFICATION: \(userInfo), \(#function)")
- handleNotification(userInfo: userInfo)
- completionHandler()
- }
- }
- extension AppDelegate : MessagingDelegate {
- // Receive data message on iOS 10 devices.
- func application(received remoteMessage: MessagingRemoteMessage) {
- let userInfo = remoteMessage.appData
- handleNotification(userInfo: userInfo)
- }
- func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
- log.debug("[DEBUG] REMOTE-MSG: \(remoteMessage.appData)")
- }
- func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
- //TODO: here backend should be updated with token
- // FCM provides a registration token via this func
- log.debug("[DEBUG] FCM-TOKEN: \(fcmToken)")
- sendFirebaseTokenToBackend()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement