// // AppDelegate.swift // Sirani // // Created by Anhar Solehudin on 24/03/19. // Copyright © 2019 Anhar Solehudin. All rights reserved. // import UIKit import GoogleMaps import UserNotifications import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? /// set orientations you want to be allowed in this property by default var orientationLock = UIInterfaceOrientationMask.all func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { return self.orientationLock } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. GMSServices.provideAPIKey("AIzaSyC8OxBL_ADTFubfkmZ2I81-IXx4O7t6Tog") // AIzaSyDOdr-zkd6oLhHRE-prsu23-u7rnSh5WCY // id.go.postel.sirani // Init Firebase Messaging FirebaseApp.configure() Messaging.messaging().delegate = self 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() Messaging.messaging().token { token, error in if let error = error { print("Error fetching FCM registration token: \(error)") } else if let token = token { print("FCM registration token: \(token)") self.postFcmToken(fcmToken: token) } } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // [START receive_message] 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 // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. // if let messageID = userInfo[gcmMessageIDKey] { // print("Message ID: \(messageID)") // } // Print full message. print(userInfo) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // 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 // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) // Print message ID. // if let messageID = userInfo[gcmMessageIDKey] { // print("Message ID: \(messageID)") // } // Print full message. print(userInfo) completionHandler(UIBackgroundFetchResult.newData) } // [END receive_message] func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Unable to register for remote notifications: \(error.localizedDescription)") } // This function is added here only for debugging purposes, and can be removed if swizzling is enabled. // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to // the FCM registration token. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { print("APNs token retrieved: \(deviceToken)") // With swizzling disabled you must set the APNs token here. // Messaging.messaging().apnsToken = deviceToken } } // [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) // Print message ID. // if let messageID = userInfo[gcmMessageIDKey] { // print("Message ID: \(messageID)") // } // Print full message. print(userInfo) // Change this to your preferred presentation option completionHandler([[.alert, .sound]]) } 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] { // print("Message ID: \(messageID)") // } // With swizzling disabled you must let Messaging know about the message, for Analytics // Messaging.messaging().appDidReceiveMessage(userInfo) // Print full message. print(userInfo) // notif handler : open noti list page if let tabBarController = self.window?.rootViewController as? UITabBarController { tabBarController.selectedViewController?.performSegue(withIdentifier: "NotifListSegueId", sender: tabBarController.selectedViewController.self) } // tell the app that we have finished processing the user’s action / response completionHandler() } } // [END ios_10_message_handling] extension AppDelegate : MessagingDelegate { // [START refresh_token] func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { print("Firebase registration token: \(String(describing: fcmToken))") if let token = fcmToken { self.postFcmToken(fcmToken: token) } let dataDict:[String: String] = ["token": fcmToken ?? ""] NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict) // TODO: If necessary send token to application server. // Note: This callback is fired at each app startup and whenever a new token is generated. } // [END refresh_token] } extension AppDelegate { private func postFcmToken(fcmToken: String) { let isLogin = UserState.instance.isLoggedIn() if isLogin { let userId = UserState.instance.getUserId() let roleId = UserState.instance.getRoleId() SiraniApiServices().postFcmToken(user_id: userId, role_id: roleId, fcmToken: fcmToken).responseJSON { response in if response.error == nil { print("FCM User Token Updated To Server : \(fcmToken)") } } } } }