// // 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 AlamofireNetworkActivityLogger import IQKeyboardManagerSwift import Localize_Swift import LGSideMenuController import FirebaseCore #if DEBUG var server: Server = .testLive #else var server: Server = .live #endif var destination: PushNotificationDestination? var overlayView: UIView? enum PushNotificationDestination { case trasactionHistory case pushNotification static func getDestination(target: String) -> PushNotificationDestination? { switch target { case "TransactionHistory": return .trasactionHistory case "PushNotification": return .pushNotification default: return nil } } } enum PushNotificationAction { case notifictaion case notice case renewID case sendMoney case howToDeposit case redirect static func getAction(target: String) -> PushNotificationAction? { switch target { case "OPEN_ACTIVITY_NOTIFICATION": return .notifictaion case "OPEN_ACTIVITY_NOTICE": return .notice case "OPEN_ACTIVITY_RENEW_ID": return .renewID case "OPEN_ACTIVITY_SENDMONEY": return .sendMoney case "OPEN_ACTIVITY_HOW_TO_DEPOSIT": return .howToDeposit case "OPEN_ACTIVITY_REDIRECT": return .redirect default: return nil } } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { UIApplication.shared.applicationIconBadgeNumber = 0 #if DEBUGx2 NetworkActivityLogger.shared.startLogging() NetworkActivityLogger.shared.level = .debug #endif IQKeyboardManager.shared.enable = true IQKeyboardManager.shared.shouldResignOnTouchOutside = true IQKeyboardManager.shared.toolbarTintColor = .black FirebaseApp.configure() 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() // } // } // } if #available(iOS 15, *) { let appearance = UINavigationBarAppearance() appearance.configureWithOpaqueBackground() UINavigationBar.appearance().standardAppearance = appearance UINavigationBar.appearance().scrollEdgeAppearance = appearance } if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().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() // Move push notification's destination let useInfo = launchOptions?[.remoteNotification] as? [String: AnyObject] destination = extractDestination(userInfo: useInfo) self.window?.rootViewController = LauncherScreenWireframe().getMainView() if #available(iOS 13.0, *) { window?.overrideUserInterfaceStyle = .light } GMEDB .shared .app .remove([.isOpenedTokenRenwalAlert, .isOpenedPopupNotification]) StoreReviewHelper.shared.incrementAppOpenedCount() //Default "Back title is removed" let barButtonItemAppearance = UIBarButtonItem.appearance() barButtonItemAppearance.setBackButtonTitlePositionAdjustment(UIOffset(horizontal: -1000, vertical: 0), for:UIBarMetrics.default) return true } func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any] ) { } func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) { } 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 } 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")") print(userInfo) if let action = extractClickAction(userInfo: userInfo as? [String: AnyObject]) { let baseVC = window?.rootViewController?.presentedViewController ?? window?.rootViewController DispatchQueue.main.async { [self] in switch action { case .notifictaion: NotificationListWireframe().open(on: baseVC) case .notice: NotificationHistoryWireframe().open(on: baseVC) case .renewID: RenewIDWireframe().open(on: baseVC) case .sendMoney: RecipientsWireframe().open(on: baseVC) case .howToDeposit: HowToDepositWireframe().open(on: baseVC) case .redirect: // break self.openURL(userInfo: userInfo as? [String: AnyObject]) } } } // 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 .pushNotification: NotificationHistoryWireframe().open(on: baseVC) } } completionHandler() } func openURL(userInfo: [String : AnyObject]?) { guard let url = userInfo?["url"] as? String else { return } guard let webController = UIStoryboard(name: "Storyboard", bundle: nil) .instantiateViewController(withIdentifier: "WebLinksViewController") as? WebLinksViewController else { return } // webController.titleString = item.title ?? "Notification" webController.url = url let nav = UINavigationController.init(rootViewController: webController) // let rootViewController = self.window.rootViewController as! UINavigationController // rootViewController.pushViewController(nav, animated: true) // If this scene's self.window is nil then set a new UIWindow object to it. window = window ?? UIWindow() // Set this scene's window's background color. self.window!.backgroundColor = UIColor.red // Create a ViewController object and set it as the scene's window's root view controller. // let rootViewController = self.window!.rootViewController as! UINavigationController self.window?.rootViewController?.present(nav, animated: true) // rootViewController.pushViewController(nav, animated: true) // Make this scene's window be visible. // self.window!.makeKeyAndVisible() // guard scene is UIWindowScene else { return } // NotificationHistoryWireframe().open(on: nav) } } extension AppDelegate { private func extractDestination(userInfo: [String : AnyObject]?) -> PushNotificationDestination? { guard let destination = userInfo?["destination"] as? String, let destinationType = PushNotificationDestination.getDestination(target: destination) else { return nil } return destinationType } private func extractClickAction(userInfo: [String : AnyObject]?) -> PushNotificationAction? { guard let aps = userInfo?["aps"] as? [String: AnyObject], let destination = aps["category"] as? String, let destinationType = PushNotificationAction.getAction(target: destination) else { return nil } return destinationType } private func urlClickAction(userInfo: [String : AnyObject]?) -> PushNotificationAction? { guard let aps = userInfo?["aps"] as? [String: AnyObject], let destination = aps["category"] as? String, let destinationType = PushNotificationAction.getAction(target: 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)") } }