// // AppDelegate.swift // GMERemittance // // Created by Fm-user on 11/30/17. // Copyright © 2017 Gobal Money Express Co. Ltd. All rights reserved. // import UIKit import Firebase import FirebaseAuth import UserNotifications import FirebaseInstanceID import FirebaseMessaging import BRYXBanner import Fabric import Crashlytics import AlamofireNetworkActivityLogger import IQKeyboardManagerSwift import Localize_Swift import ChannelIO import LGSideMenuController #if DEBUG var server: Server = .live #else let server: Server = .live #endif var destination: PushNotificationDestination? = nil var overlayView: UIView? enum PushNotificationDestination: String { case trasactionHistory = "TransactionHistory" case rechargeHistory = "RechargeHistory" } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { UIApplication.shared.applicationIconBadgeNumber = 0 #if DEBUG NetworkActivityLogger.shared.startLogging() NetworkActivityLogger.shared.level = .debug #endif IQKeyboardManager.shared.enable = true IQKeyboardManager.shared.shouldResignOnTouchOutside = true IQKeyboardManager.shared.toolbarTintColor = .black FirebaseApp.configure() Fabric.with([Crashlytics.self]) Fabric.sharedSDK().debug = true Messaging.messaging().delegate = self let center = UNUserNotificationCenter.current() center.delegate = self center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, _) in guard granted else { return } center.getNotificationSettings { settings in print("Notification settings: \(settings)") DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } // Move push notification's destination let useInfo = launchOptions?[.remoteNotification] as? [String: AnyObject] destination = extractDestination(userInfo: useInfo) self.window?.rootViewController = LauncherScreenWireframe().getMainView() ChannelIO.initialize() GMEDB .shared .app .remove([.isOpenedTokenRenwalAlert, .isOpenedPopupNotification]) StoreReviewHelper.shared.incrementAppOpenedCount() return true } func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any] ) { } func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) { ChannelIO.handlePushNotification(userInfo) { completionHandler(.noData) } } func application( _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error ) { } func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) print("APNs device token: \(deviceTokenString)") Messaging.messaging().apnsToken = deviceToken ChannelIO.initPushToken(deviceToken: deviceToken) } func applicationDidEnterBackground(_ application: UIApplication) { let taskID = application.beginBackgroundTask(expirationHandler: nil) let language = Localize.currentLanguage() GMEDB.shared.app.set(language, .currentLanguage) let viewcontroller = UIViewController() viewcontroller.view.backgroundColor = .themeRed viewcontroller.view.frame = UIScreen.main.bounds overlayView = viewcontroller.view guard let view = overlayView else {return} let topView = UIApplication.shared.keyWindow?.subviews.last topView?.addSubview(view) topView?.bringSubviewToFront(view) if taskID != UIBackgroundTaskIdentifier.invalid { UIApplication.shared.endBackgroundTask(taskID) } } func applicationWillEnterForeground(_ application: UIApplication) { if let language = GMEDB.shared.app.string(.currentLanguage) { Localize.setCurrentLanguage(language) } overlayView?.removeFromSuperview() } func application( _ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:] ) -> Bool { return true } } // MARK: - UNUserNotificationCenterDelegate extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void ) { let userInfo = notification.request.content.userInfo print("Message ID: \(userInfo["gcm_message_id"] ?? "nil")") print(userInfo) completionHandler([ UNNotificationPresentationOptions.alert, UNNotificationPresentationOptions.sound, UNNotificationPresentationOptions.badge ]) } func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { let userInfo = response.notification.request.content.userInfo print("Message ID: \(userInfo["gcm_message_id"] ?? "nil")") if ChannelIO.isChannelPushNotification(userInfo) { ChannelIO.handlePushNotification(userInfo) } // open push notification's destination guard window?.rootViewController is LGSideMenuController, let destination = extractDestination(userInfo: userInfo as? [String: AnyObject]) else { completionHandler() return } let baseVC = window?.rootViewController?.presentedViewController ?? window?.rootViewController DispatchQueue.main.async { switch destination { case .trasactionHistory: TransactionHistoryGroupWireframe().open(overseasType: .inbound, on: baseVC) case .rechargeHistory: RechargeHistoryWireframe().open(on: baseVC) } } completionHandler() } } extension AppDelegate { private func extractDestination(userInfo: [String : AnyObject]?) -> PushNotificationDestination? { guard let destination = userInfo?["destination"] as? String, let destinationType = PushNotificationDestination(rawValue: destination) else { return nil } return destinationType } } // MARK: - MessagingDelegate extension AppDelegate: MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print("Firebase registration token: \(fcmToken)") let userInfo = ["token": fcmToken] NotificationCenter.default.post( name: Notification.Name("FCMToken"), object: nil, userInfo: userInfo ) } func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { print("Received data message: \(remoteMessage.appData)") } }