You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

314 lines
10 KiB

//
// 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 LGSideMenuController
import Localize_Swift
import ChannelIO
let server: Server = .kftcTest
var overlayView: UIView?
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
) -> Bool {
UIApplication.shared.applicationIconBadgeNumber = 0
NetworkActivityLogger.shared.startLogging()
NetworkActivityLogger.shared.level = .debug
IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
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]) { (_, _) in}
application.registerForRemoteNotifications()
print("FCM Token: \(Messaging.messaging().fcmToken ?? "nil")")
// Initialize ChannelIO
ChannelIO.initialize()
setUUID()
setupNavBar()
setEntryPoint()
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 store = UserDefaults.standard
let language = Localize.currentLanguage()
store.set(language, forKey: AppConstants.currentLanguage)
let viewcontroller = UIViewController()
viewcontroller.view.backgroundColor = AppConstants.themeRedColor
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?.bringSubview(toFront: view)
}
func applicationWillEnterForeground(_ application: UIApplication) {
if let language = UserDefaults.standard.string(forKey: AppConstants.currentLanguage) {
Localize.setCurrentLanguage(language)
}
overlayView?.removeFromSuperview()
}
}
// MARK: - Other Functions
extension AppDelegate {
private func setUUID() {
if UserDefaults.standard.string(forKey: AppConstants.uuid) == nil {
let uuid = UUID().uuidString
UserDefaults.standard.set(uuid, forKey: AppConstants.uuid)
}
}
private func setupNavBar() {
let appearance = UINavigationBar.appearance()
appearance.backIndicatorImage = #imageLiteral(resourceName: "backIconBlack")
appearance.backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "backIconBlack")
appearance.tintColor = UIColor.black
}
private func setEntryPoint() {
guard let _ = KeyChain.shared.get(key: .email),
(KeyChain.shared.get(key: .login) ?? "1") == "1" ? true : false else {
self.goSplashScreen()
return
}
let biometricAuthenticationWireframe = BiometricAuthenticationWireframe()
biometricAuthenticationWireframe.openWithDelegate(
on: self.window!,
delegate: self
)
}
private func doLogin(){
self.window?.rootViewController?.showProgressHud()
let loginService = LoginService()
guard let userID = KeyChain.shared.get(key: .email),
let password = KeyChain.shared.get(key: .password) else {
self.goSplashScreen()
return
}
loginService._login(
userId: userID,
password: password,
success: { (user) in
let accessCode = user?.accessCode ?? ""
let accessCodeBase64 = accessCode
Utility.save(user: user, accessCodeBase64: accessCodeBase64, password: password, login: true)
let mainWireFrame = MainWireframe.shared
let tabBarViewController = mainWireFrame?.getMainView()
let sidemenuVc = UIStoryboard(name: "SideMenu", bundle: nil).instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController
let sideMenuController = LGSideMenuController(rootViewController: tabBarViewController, leftViewController: sidemenuVc, rightViewController: nil)
sideMenuController.rootViewLayerShadowColor = UIColor(white: 0.9, alpha: 0.6)
sideMenuController.rootViewLayerShadowRadius = 8.0
sideMenuController.leftViewPresentationStyle = .scaleFromBig
sideMenuController.leftViewWidth = UIScreen.main.bounds.width - 70.0
if #available(iOS 10.0, *) {
sideMenuController.leftViewBackgroundBlurEffect = UIBlurEffect(style: .regular)
} else {
// Fallback on earlier versions
}
self.window?.rootViewController?.hideProgressHud()
self.window?.backgroundColor = sidemenuVc.view.backgroundColor
self.window?.rootViewController = sideMenuController
}) { (error) in
self.window?.rootViewController?.hideProgressHud()
self.window?.rootViewController?.alert(type: .error, message: error.localizedDescription, title: "Warning"){
// if failed login, remove all in keychain, change logout status and then go splash screen
KeyChain.shared.removeAll()
self.goSplashScreen()
}
}
}
private func goSplashScreen() {
let splashWireframe = SplashScreenWireframe()
let nav = UINavigationController.init(rootViewController: splashWireframe.getMainView())
self.window?.rootViewController = nav
}
}
// 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")")
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)
}
print(userInfo)
completionHandler()
}
}
// 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)")
}
}
// MARK: - BiometricAuthenticationViewControllerDelegate
extension AppDelegate: BiometricAuthenticationViewControllerDelegate{
func viewController(_ viewController: BiometricAuthenticationViewController, informationTitleLabel titleLabel: UILabel, authenticationButton button: UIButton) {
titleLabel.text = "bio_login_intro_text".localized()
button.setTitle("login_text".localized(), for: .normal)
}
func didComplete(_ viewController: BiometricAuthenticationViewController) {
self.doLogin()
}
func viewController(
_ viewController: BiometricAuthenticationViewController,
didFailWithError error: BiometricAuthenticationError,
errorMessage: String?
) {
print("BiometricAuthenticationWireframe Error: \(errorMessage ?? "")")
// if don't use biometric authentication or user press password
DispatchQueue.main.async {
switch error {
case .biometryNotAvailable, .userFallback:
let secureKeypad = SecureKeypad(target: viewController)
secureKeypad.delegate = self
secureKeypad.present(animated: true)
case .notBeConfigured, .biometryNotEnrolled:
viewController.alert(type: .error, message: error.message)
default:
break
}
}
}
func doSelectLocalAuthenticationPolicy(_ viewController: BiometricAuthenticationViewController) -> BiometricAuthenticationPolicy {
return .deviceOwnerAuthenticationWithBiometrics
}
}
// MARK: - SecureKeypadDelegate
extension AppDelegate: SecureKeypadDelegate {
func didComplete(_ encryptedString: String) {
if encryptedString != "" {
KeyChain.shared.save(data: encryptedString, key: .password)
self.doLogin()
}
}
}