mstranieri

AppDelegate.swift

May 14th, 2020
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 21.45 KB | None | 0 0
  1. //
  2. //  AppDelegate.swift
  3. //  Foodomia
  4. //
  5. //  Created by Rao Mudassar on 9/20/17.
  6. //  Copyright © 2017 dinosoftlabs. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import IQKeyboardManagerSwift
  11. import GooglePlaces
  12. import GoogleMaps
  13. import GooglePlacePicker
  14. import GoogleSignIn
  15. import FBSDKCoreKit
  16. import FBSDKLoginKit
  17. import Stripe
  18. import SDWebImage
  19. import Firebase
  20. import CoreData
  21. import Alamofire
  22. import UserNotifications
  23. import FirebaseMessaging
  24. import AVFoundation
  25. import UserNotifications
  26. import Firebase
  27. import FirebaseInstanceID
  28.  
  29. //import GoogleSignIn
  30.  
  31. @UIApplicationMain
  32. class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate,GIDSignInDelegate, FIRMessagingDelegate{
  33.  
  34.     var window: UIWindow?
  35.     var container: UIView = UIView()
  36.     var loadingView: UIView = UIView()
  37.    
  38.     var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
  39. //    let baseUrl:String = "http://domain/api"
  40. //    let ImagebaseUrl:String = "http://domain/"
  41.     let baseUrl = "https://api.bakeryitalia.com/api"
  42.     let ImagebaseUrl = "https://api.bakeryitalia.com/"
  43.     let registerUser:String = "/registerUser"
  44.     let loginUser:String = "/login"
  45.     let addPaymentMethod:String = "/addPaymentMethod"
  46.     let addDeliveryAddress:String = "/addDeliveryAddress"
  47.     let getPaymentDetails:String = "/getPaymentDetails"
  48.     let editUserProfile:String = "/editUserProfile"
  49.     let verifyPhoneNo:String = "/verifyPhoneNo"
  50.     let forgotPassword:String = "/forgotPassword"
  51.     let changePassword:String = "/changePassword"
  52.     let showRestaurants:String = "/showRestaurants"
  53.     let getDeliveryAddresses:String = "/showDeliveryAddresses"
  54.     let showRestaurantsMenu:String = "/showRestaurantsMenu"
  55.     let showOrders:String = "/showOrders"
  56.     let restaurantRatings:String = "/showRestaurantRatings"
  57.     let placeOrder:String = "/placeOrder"
  58.     let showRiderOrders:String = "/showRiderOrders"
  59.     let updateRiderOrderStatus:String = "/updateRiderOrderStatus"
  60.     let addUserLocation:String = "/addRiderLocation"
  61.     let chat:String = "/chat"
  62.     let getConversation:String = "/getConversation"
  63.     let showMenuExtraItems:String = "/showMenuExtraItems"
  64.     let showRiderTracking:String = "/showRiderTracking"
  65.     let trackRiderStatus:String = "/trackRiderStatus"
  66.     let showRiderOrdersBasedOnDate:String = "/showRiderOrdersBasedOnDate"
  67.     let showRiderTimingBasedOnDate:String = "/showRiderTimingBasedOnDate"
  68.     let addRiderTiming:String = "/addRiderTiming"
  69.     let showOrderDetail:String = "/showOrderDetail"
  70.     let deleteRiderTiming:String = "/deleteRiderTiming"
  71.     let verifyCoupon:String = "/verifyCoupon"
  72.     let addFavouriteRestaurant:String = "/addFavouriteRestaurant"
  73.     let showFavouriteRestaurants:String = "/showFavouriteRestaurants"
  74.     let showAppSliderImages:String = "/showAppSliderImages"
  75.     let checkIn:String = "/checkIn"
  76.     let showDeals:String = "/showDeals"
  77.     let showDealBasedOnID:String = "/showDealBasedOnID"
  78.     let showUserOnlineStatus:String = "/showUserOnlineStatus"
  79.     let addRestaurantRating:String = "/addRestaurantRating"
  80.     let showCountries:String = "/showCountries"
  81.     let orderDeal:String = "/orderDeal"
  82.     let showRestaurantDeals:String = "/showRestaurantDeals"
  83.     let showOrdersBasedOnRestaurant:String = "/showOrdersBasedOnRestaurant"
  84.     let updateRestaurantOrderStatus:String = "/updateRestaurantOrderStatus"
  85.     let deletePaymentMethod:String = "/deletePaymentMethod"
  86.     let deleteDeliveryAddress:String = "/deleteDeliveryAddress"
  87.     let showRestaurantsAgainstSpeciality:String = "/showRestaurantsAgainstSpeciality"
  88.     let showRestaurantsSpecialities:String = "/showRestaurantsSpecialities"
  89.     let showRiderLocationAgainstOrder:String = "/showRiderLocationAgainstOrder"
  90.     let updateRiderShiftStatus:String = "/updateRiderShiftStatus"
  91.     let giveRatingsToRider:String = "/giveRatingsToRider"
  92.     let showUpComingRiderShifts:String = "/showUpComingRiderShifts"
  93.     let showRestaurantCompletedOrders:String = "/showRestaurantCompletedOrders"
  94.     let showRiderRatings:String = "/showRiderRatings"
  95.     let showRiderLocationAgainstOrderWithPusher:String = "/showRiderLocationAgainstOrderWithPusher"
  96.    
  97.    
  98.    
  99.     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  100.        
  101.        //Thread.sleep(forTimeInterval: 2.0)
  102.        
  103.         UIApplication.shared.statusBarStyle = .lightContent
  104.         IQKeyboardManager.sharedManager().enable = true
  105.         GMSPlacesClient.provideAPIKey("AIzaSyAUywCFEGbnsB-1v-AH_wJ-GrTviuOLAQE")
  106.         GMSServices.provideAPIKey("AIzaSyAUywCFEGbnsB-1v-AH_wJ-GrTviuOLAQE")
  107.         STPPaymentConfiguration.shared().publishableKey = "sk_live_h4CnhXJTbDt5fycM0gF4SOtg00wHzDXcNN"
  108.         if #available(iOS 10.0, *) {
  109.             // For iOS 10 display notification (sent via APNS)
  110.             UNUserNotificationCenter.current().delegate = self
  111.             let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
  112.             UNUserNotificationCenter.current().requestAuthorization(
  113.                 options: authOptions,
  114.                 completionHandler: {_, _ in })
  115.             // For iOS 10 data message (sent via FCM
  116.             FIRMessaging.messaging().remoteMessageDelegate = self
  117.         } else {
  118.             let settings: UIUserNotificationSettings =
  119.                 UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  120.             application.registerUserNotificationSettings(settings)
  121.         }
  122.        
  123.         application.registerForRemoteNotifications()
  124.         if FIRApp.defaultApp() == nil {
  125.             FIRApp.configure()
  126.         }
  127.  
  128.         UserDefaults.standard.set(UIDevice.current.identifierForVendor!.uuidString, forKey:"udid")
  129.         if(UserDefaults.standard.string(forKey:"email") == nil  || UserDefaults.standard.string(forKey:"email") == ""){
  130.  
  131.             UserDefaults.standard.set("NO", forKey:"isLogin")
  132.  
  133.             UserDefaults.standard.set("", forKey:"email")
  134.             UserDefaults.standard.set("", forKey:"pwd")
  135.             UserDefaults.standard.set("", forKey:"uid")
  136.             UserDefaults.standard.set("", forKey:"first_name")
  137.             UserDefaults.standard.set("", forKey:"last_name")
  138.             UserDefaults.standard.set("", forKey:"contactNO")
  139.             UserDefaults.standard.set("", forKey:"aid")
  140.             UserDefaults.standard.set("", forKey:"UserType")
  141.             if(UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad){
  142.                
  143.                 let storyboard = UIStoryboard(name: "StoryboardiPad", bundle: nil)
  144.                 let tabViewController = storyboard.instantiateViewController(withIdentifier: "NavLoginViewController") as? UINavigationController
  145.                 UserDefaults.standard.set("", forKey:"center")
  146.                 UserDefaults.standard.set("", forKey:"location")
  147.                
  148.                
  149.                 self.window?.rootViewController = tabViewController
  150.                 self.window?.makeKeyAndVisible()
  151.             }else{
  152.                
  153.                 let storyboard = UIStoryboard(name: "Main", bundle: nil)
  154.                 let tabViewController = storyboard.instantiateViewController(withIdentifier: "NavLogInViewController") as? UINavigationController
  155.                 UserDefaults.standard.set("", forKey:"center")
  156.                 UserDefaults.standard.set("", forKey:"location")
  157.                
  158.                
  159.                 self.window?.rootViewController = tabViewController
  160.                 self.window?.makeKeyAndVisible()
  161.                
  162.             }
  163. //            if(UserDefaults.standard.string(forKey: "location") == nil || UserDefaults.standard.string(forKey: "location") == "" ){
  164. //            }else{
  165. //                if(UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad){
  166. //                let storyboard = UIStoryboard(name: "StoryboardiPad", bundle: nil)
  167. //                let tabViewController:UITabBarController = (storyboard.instantiateViewController(withIdentifier: "TheAssignedID") as? UITabBarController)!
  168. //
  169. //                self.window?.rootViewController = tabViewController
  170. //                self.window?.makeKeyAndVisible()
  171. //                }else{
  172. //                    let storyboard = UIStoryboard(name: "Main", bundle: nil)
  173. //                    let tabViewController:UITabBarController = (storyboard.instantiateViewController(withIdentifier: "TheAssignedID") as? UITabBarController)!
  174. //
  175. //                    self.window?.rootViewController = tabViewController
  176. //                    self.window?.makeKeyAndVisible()
  177. //
  178. //                }
  179. //            }
  180.         }else{
  181.  
  182.             UserDefaults.standard.set("YES", forKey:"isLogin")
  183.            
  184.             if(UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad) {
  185.             let storyboard = UIStoryboard(name: "StoryboardiPad", bundle: nil)
  186.             let tabViewController:UITabBarController = (storyboard.instantiateViewController(withIdentifier: "TheAssignedID2") as? UITabBarController)!
  187.             self.window?.rootViewController = tabViewController
  188.             self.window?.makeKeyAndVisible()
  189.             }else{
  190.  
  191.                 let storyboard = UIStoryboard(name: "Main", bundle: nil)
  192.                 let tabViewController:UITabBarController = (storyboard.instantiateViewController(withIdentifier: "TheAssignedID2") as? UITabBarController)!
  193.                 self.window?.rootViewController = tabViewController
  194.                 self.window?.makeKeyAndVisible()
  195.             }
  196.         }
  197.      
  198.          GIDSignIn.sharedInstance().clientID = "6481736747-065qjm4h8fsf8at8738d7d41ps8kk7s3.apps.googleusercontent.com"
  199.         // return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
  200.        
  201.         return true
  202.        
  203.     }
  204.    
  205.    
  206.  
  207.    
  208.     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  209. //       let refreshedToken = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
  210. //
  211. //        // Print it to console
  212. //        //print("APNs device token: \(refreshedToken)")
  213. //        if(refreshedToken == nil){
  214. //            UserDefaults.standard.set("", forKey:"DeviceToken")
  215. //        }else{
  216. //        UserDefaults.standard.set(refreshedToken, forKey:"DeviceToken")
  217. //        }
  218.        
  219.         if let refreshedToken = FIRInstanceID.instanceID().token() {
  220.             //print("InstanceID token: \(refreshedToken)")
  221.             UserDefaults.standard.set(refreshedToken, forKey:"DeviceToken")
  222.         }else{
  223.            
  224.             UserDefaults.standard.set("", forKey:"DeviceToken")
  225.         }
  226.     }
  227.    
  228.     func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  229.         //print("Registration failed!")
  230.     }
  231.    
  232.     func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any],
  233.                      fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  234.         //print(userInfo)
  235.     }
  236.    
  237.     // Firebase notification received
  238.     @available(iOS 10.0, *)
  239.     func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
  240.         completionHandler([.alert, .badge, .sound])
  241.         // custom code to handle push while app is in the foreground
  242.         //print("Handle push from foreground, received: \n \(notification.request.content)")
  243.       //print(notification.request.content.userInfo)
  244.      
  245.         let type  = notification.request.content.userInfo[AnyHashable("gcm.notification.type")] as? String
  246.         ////print(dic!)
  247.        
  248.         if(type == nil ){
  249.            
  250.         }else
  251.         if(type == "Order has been successfully placed"){
  252.             AudioServicesPlayAlertSound(SystemSoundID(1322))
  253.         }
  254.         else
  255.         if(type == "rider_review"){
  256.            
  257.             UserDefaults.standard.set(notification.request.content.userInfo[AnyHashable("gcm.notification.rider_user_id")] as! String, forKey:"notiRider")
  258.             UserDefaults.standard.set(notification.request.content.userInfo[AnyHashable("gcm.notification.order_id")] as! String, forKey:"notiRiderOrderID")
  259.             UserDefaults.standard.set(notification.request.content.userInfo[AnyHashable("gcm.notification.rider_name")] as! String, forKey:"notiRiderName")
  260.             UserDefaults.standard.set("Yes", forKey:"RiderReview")
  261.             NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier1"), object: nil)
  262.            
  263.         }else if(type == "order_review"){
  264.             StaticData.singleton.notiRestID = notification.request.content.userInfo[AnyHashable("gcm.notification.restaurant_id")] as? String
  265.             UserDefaults.standard.set(StaticData.singleton.notiRestID!, forKey:"notiRest")
  266.             UserDefaults.standard.set(notification.request.content.userInfo[AnyHashable("gcm.notification.restaurant_name")] as! String, forKey:"notiName")
  267.             UserDefaults.standard.set(notification.request.content.userInfo[AnyHashable("gcm.notification.img")] as! String , forKey:"notiImg")
  268.             UserDefaults.standard.set("Yes", forKey:"isReview")
  269.             NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
  270.            
  271.         }
  272.        
  273.     }
  274.     @available(iOS 10.0, *)
  275.     func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
  276.                                 withCompletionHandler completionHandler: @escaping () -> Void) {
  277.         //print("Handle tapped push from background, received: \n \(response.notification.request.content)")
  278.      
  279.        
  280.        
  281.         let type  = response.notification.request.content.userInfo[AnyHashable("gcm.notification.type")] as? String
  282.      
  283.         if(type == nil){
  284.            
  285.         }else
  286.         if(type == "Order has been successfully placed"){
  287.             AudioServicesPlayAlertSound(SystemSoundID(1322))
  288.         }
  289.         else
  290.             if(type == "rider_review"){
  291.                
  292.                 UserDefaults.standard.set(response.notification.request.content.userInfo[AnyHashable("gcm.notification.rider_user_id")] as! String, forKey:"notiRider")
  293.                 UserDefaults.standard.set(response.notification.request.content.userInfo[AnyHashable("gcm.notification.order_id")] as! String, forKey:"notiRiderOrderID")
  294.                 UserDefaults.standard.set(response.notification.request.content.userInfo[AnyHashable("gcm.notification.rider_name")] as! String, forKey:"notiRiderName")
  295.                 UserDefaults.standard.set("Yes", forKey:"RiderReview")
  296.                 NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier1"), object: nil)
  297.                
  298.             }else if(type == "order_review"){
  299.                 StaticData.singleton.notiRestID = response.notification.request.content.userInfo[AnyHashable("gcm.notification.restaurant_id")] as? String
  300.                 UserDefaults.standard.set(StaticData.singleton.notiRestID!, forKey:"notiRest")
  301.                 UserDefaults.standard.set(response.notification.request.content.userInfo[AnyHashable("gcm.notification.restaurant_name")] as! String, forKey:"notiName")
  302.                 UserDefaults.standard.set(response.notification.request.content.userInfo[AnyHashable("gcm.notification.img")] as! String , forKey:"notiImg")
  303.                 UserDefaults.standard.set("Yes", forKey:"isReview")
  304.                 NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)
  305.                
  306.         }
  307.        
  308.         completionHandler()
  309.     }
  310.    
  311.     func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
  312.         //print(remoteMessage.appData)
  313.     }
  314.  
  315.  
  316.    
  317.    
  318.     func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
  319.        
  320.         //        BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
  321.         //            openURL:url
  322.         //            sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
  323.         //            annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
  324.         //        ];
  325.        
  326.         let handled=FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
  327.        
  328.         return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) || handled
  329.     }
  330.    
  331. //    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
  332. //        return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) || GIDSignIn.sharedInstance().handle(url,
  333. //                                                                                                                                                                                                sourceApplication: sourceApplication,
  334. //                                                                                                                                                                                                annotation: annotation)
  335. //    }
  336.    
  337.     func showActivityIndicatory(uiView: UIView) {
  338.  
  339.        uiView.isUserInteractionEnabled = false
  340.    
  341.     }
  342.  
  343.    
  344.    
  345.     func isValidEmail(testStr:String) -> Bool {
  346.         //print("validate emilId: \(testStr)")
  347.         let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
  348.         let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
  349.         let result = emailTest.evaluate(with: testStr)
  350.         return result
  351.     }
  352.    
  353.    
  354.     public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
  355.         if (error == nil) {
  356.             // Perform any operations on signed in user here.
  357.             let userId = user.userID                  // For client-side use only!
  358.             let idToken = user.authentication.idToken // Safe to send to the server
  359.             let fullName = user.profile.name
  360.             let givenName = user.profile.givenName
  361.             let familyName = user.profile.familyName
  362.             let email = user.profile.email
  363.             // ...
  364.         } else {
  365.             //print("\(error.localizedDescription)")
  366.         }
  367.        
  368.        
  369.     }
  370.  
  371.    
  372.    
  373.    
  374.     func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!){
  375.        
  376.        
  377.     }
  378.  
  379.     func applicationWillResignActive(_ application: UIApplication) {
  380.         // 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.
  381.         // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  382.        
  383.     }
  384.  
  385.     func applicationDidEnterBackground(_ application: UIApplication) {
  386.         // 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.
  387.         // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  388.        
  389.     }
  390.  
  391.     func applicationWillEnterForeground(_ application: UIApplication) {
  392.         // 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.
  393.         UIApplication.shared.applicationIconBadgeNumber = 0
  394.     }
  395.  
  396.     func applicationDidBecomeActive(_ application: UIApplication) {
  397.         // 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.
  398.         UIApplication.shared.applicationIconBadgeNumber = 0
  399.     }
  400.  
  401.    
  402.     func applicationWillTerminate(_ application: UIApplication) {
  403.         // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  404.         // Saves changes in the application's managed object context before the
  405.        
  406.        
  407.     }
  408.  
  409.  
  410.  
  411.  
  412. }
Add Comment
Please, Sign In to add comment