Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // AppDelegate.swift
- // myRaceTracker
- //
- // Created by Thoughts2Binary on 10/5/17.
- // Copyright © 2017 Thoughts2Binary. All rights reserved.
- //
- import UIKit
- import Fabric
- import Crashlytics
- import IQKeyboardManagerSwift
- import UserNotifications
- import Bugsee
- import RealmSwift
- @UIApplicationMain
- class AppDelegate: UIResponder, UIApplicationDelegate{
- var window: UIWindow?
- var iridiumUtils = IridiumUtils()
- func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
- // Override point for customization after application launch.
- Bugsee.launch(token:"f8ec2647-caec-4d08-9588-c90110242a60")
- print(Realm.Configuration.defaultConfiguration.fileURL)
- UserDefaults.standard.setValue(0, forKey: "badge_count")
- Fabric.with([Crashlytics.self])
- if let token = UserDefaults.standard.value(forKey: "auth_token") {
- print("Auth Token \(token)")
- Store.User.shared.setAccessToken(token as! String)
- if let iridium_username = UserDefaults.standard.value(forKey: "iridium_username") {
- Store.User.shared.setUsername(iridium_username as! String)
- }
- if let iridium_password = UserDefaults.standard.value(forKey: "iridium_password") {
- Store.User.shared.setUsername(iridium_password as! String)
- }
- }
- //GMSServices.provideAPIKey("AIzaSyBsJqje8jgWPJh4a9mUEHq2tGf_WokdwMI")
- UIApplication.shared.setMinimumBackgroundFetchInterval(1.0)
- IQKeyboardManager.sharedManager().enable = true
- UNUserNotificationCenter.current().delegate = self
- // if (launchOptions != nil){
- // let dictionary = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as! [AnyHashable : Any]
- // print("userInfo: \(dictionary)")
- // openInvitesViewController(userInfo: dictionary)
- // }else{
- // print("launchOptions: nil")
- // }
- return true
- }
- func navigateToSavedScreen() {
- if let mainController = UIApplication.shared.keyWindow?.rootViewController as? MainViewController {
- if let navigationContoller = mainController.rootViewController as? UINavigationController {
- let storyboard = UIStoryboard(name: "Main", bundle: .main)
- if navigationContoller.viewControllers.last is SavedEventsView {
- // Do Nothing
- }
- else {
- navigationContoller.show(storyboard.instantiateViewController(withIdentifier: "SavedEventsView"), sender: self)
- }
- }
- }
- }
- func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
- print("Background Execution 111")
- completionHandler(UIBackgroundFetchResult.newData)
- }
- 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.
- // UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
- }
- 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:.
- // Saves changes in the application's managed object context before the application terminates.
- }
- func registerToken(token: String){
- let parameters = ["name" : "", "registration_id" : token]
- UserService.sendDeviceToken(parameters: parameters
- , success: {
- UserDefaults.standard.set(token, forKey: "DEVICE_TOKEN")
- }) { [unowned self] (error) in
- }
- }
- // [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) {
- let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
- print("APNs token retrieved: \(deviceTokenString)")
- if let _ = UserDefaults.standard.string(forKey: "DEVICE_TOKEN") {
- return
- }
- self.registerToken(token: deviceTokenString)
- // 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) {
- if let userInfo = notification.request.content.userInfo as? [String : AnyObject]{
- guard Store.User.shared.isDownloadingOfflineMap() == false else {return}
- print("App in foreground")
- // let notificationModel = NotificationModel()
- // let notificationViewModel = NotificationViewModel()
- var senderId = 0
- var username = ""
- if let senderData = userInfo["sender_data"] as? NSDictionary {
- let userPublicModel = UserPublicModel()
- if let email = senderData["email"] as? String {
- userPublicModel.email = email
- }
- if let first_name = senderData["first_name"] as? String {
- userPublicModel.firstName = first_name
- }
- if let full_name = senderData["full_name"] as? String {
- userPublicModel.full_name = full_name
- // notificationModel.senderName = full_name
- username = full_name
- }
- if let id = senderData["id"] as? Int {
- userPublicModel.id = id
- senderId = id
- // notificationModel.senderId = id
- }
- if let is_active = senderData["is_active"] as? Bool {
- userPublicModel.is_active = is_active
- }
- if let phone = senderData["phone"] as? String {
- userPublicModel.phone = phone
- }
- if let username = senderData["username"] as? String {
- userPublicModel.username = username
- }
- if let last_name = senderData["last_name"] as? String {
- userPublicModel.lastName = last_name
- }
- if let profileInfo = senderData["profile"] as? NSDictionary {
- let profile = UserPublicProfileModel()
- if let _ = profileInfo["profile_picture"] as? String {
- profile.profilePicUrl = (profileInfo["profile_picture"] as? String)!
- }
- if let _ = profileInfo["title"] as? String {
- profile.title = (profileInfo["title"] as? String)!
- }
- userPublicModel.userProfile = profile
- }
- userPublicModel.save()
- }
- let logViewModel = LogViewModel()
- let type = userInfo["type"] as? String ?? ""
- let cID = userInfo["conversation_id"] as? Int ?? 0
- let currentCid = Store.User.shared.getConversationId()
- let currentUser = Store.User.shared.getConversationName()
- if type == "enrollment" {
- let action = userInfo["action"] as? String ?? ""
- if action == "accept" {
- toPostNotificationToUpdateView(name: "toUpdateSubscribedView")
- }
- }
- if type == "add_participant" {
- toPostNotificationToUpdateView(name: "toUpdateSubscribedView")
- }
- if type == "delete_participant" {
- toPostNotificationToUpdateView(name: "toUpdateSubscribedView")
- }
- if type == "invitation" {
- let action = userInfo["action"] as? String ?? ""
- if action.isEmpty {
- toPostNotificationToUpdateView(name: "toUpdateReceivedInvitesView")
- }
- }
- if let chatsVC = (UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.first as? UINavigationController)?.visibleViewController, chatsVC is ChatsView {
- if let _:ChatsView = chatsVC as? ChatsView {
- if currentCid == cID || currentUser == username {
- ChatsService.getUnreadMessageFromNotification(cID, success: { /*[weak self]*/ (messages) in
- (chatsVC as! ChatsView).dataSource.insertIncomingMessage(messages)
- logViewModel.add("REFRESHED_CHATS_VIA_NOTIFICATION", "Success: \(messages)")
- })
- { /*[weak self]*/ (error) in
- DispatchQueue.main.async {
- logViewModel.add("ERROR_REFRESHING_CHATS_VIA_NOTIFICATION", "Error: \(error)")
- }
- }
- }
- else {
- completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
- toUpdateEventBadgeCountByOne()
- toUpdateChatUnreadCount(userInfo: userInfo)
- //toPostNotificationsToUpdateBadge(senderId: senderId,conversationId: cID)
- //toPostNotificationToUpdateEventBadgeCount()
- }
- }
- }else{
- print("User is on another screen")
- completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
- toUpdateEventBadgeCountByOne()
- toUpdateChatUnreadCount(userInfo: userInfo)
- }
- print("userNotificationCenter: willPresent")
- debugPrint(userInfo)
- }
- }
- func userNotificationCenter(_ center: UNUserNotificationCenter,
- didReceive response: UNNotificationResponse,
- withCompletionHandler completionHandler: @escaping () -> Void) {
- if let userInfo = response.notification.request.content.userInfo as? [String : AnyObject]{
- print("App in background or closed")
- print(userInfo)
- guard Store.User.shared.isDownloadingOfflineMap() == false else {return}
- if let senderData = userInfo["sender_data"] as? NSDictionary {
- let userPublicModel = UserPublicModel()
- if let email = senderData["email"] as? String {
- userPublicModel.email = email
- }
- if let first_name = senderData["first_name"] as? String {
- userPublicModel.firstName = first_name
- }
- if let full_name = senderData["full_name"] as? String {
- userPublicModel.full_name = full_name
- // notificationModel.senderName = full_name
- }
- if let id = senderData["id"] as? Int {
- userPublicModel.id = id
- // notificationModel.senderId = id
- }
- if let is_active = senderData["is_active"] as? Bool {
- userPublicModel.is_active = is_active
- }
- if let phone = senderData["phone"] as? String {
- userPublicModel.phone = phone
- }
- if let username = senderData["username"] as? String {
- userPublicModel.username = username
- }
- if let last_name = senderData["last_name"] as? String {
- userPublicModel.lastName = last_name
- }
- if let profileInfo = senderData["profile"] as? NSDictionary {
- let profile = UserPublicProfileModel()
- if let _ = profileInfo["profile_picture"] as? String {
- profile.profilePicUrl = (profileInfo["profile_picture"] as? String)!
- }
- if let _ = profileInfo["title"] as? String {
- profile.title = (profileInfo["title"] as? String)!
- }
- userPublicModel.userProfile = profile
- }
- userPublicModel.save()
- }
- if userInfo["type"] != nil {
- openInvitesViewController(userInfo: userInfo)
- }
- if userInfo.count == 0 {
- let cId = UserDefaults.standard.object(forKey: "conversation") as! Int
- var messages = MessagesModel.getMessagesForConversation(cId)
- messages = messages.sorted(by: {$0.create_date > $1.create_date})
- var messagesArray = [DemoTextMessageModel]()
- messages.forEach{ message in
- messagesArray.insert(ChatMessageFactory.makeTextMessage(message.messageId, text: message.message, isIncoming: message.isIncoming, senderId: message.senderId, date: message.create_date, conversationId: message.conversationId, participantId: nil, teamId: nil), at: 0)
- }
- let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
- let datasource = DemoChatDataSource(messages: messagesArray, pageSize: 100)
- let cv = storyboard.instantiateViewController(withIdentifier: "ChatsView") as! ChatsView
- cv.dataSource = datasource
- cv.messageSender = datasource.messageSender
- let nv = UINavigationController(rootViewController: cv)
- if let vc = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.last as? UINavigationController {
- if let currentVC = vc.visibleViewController {
- currentVC.present(nv, animated: true, completion: nil)
- self.window?.makeKeyAndVisible()
- }
- }
- }
- }
- //completionHandler()
- }
- func openInvitesViewController(userInfo: [AnyHashable: Any]){
- let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
- let apptVC = storyboard.instantiateViewController(withIdentifier: "eventsDashboard") as! MainViewController
- let type = userInfo["type"] as? String ?? ""
- switch type {
- case "team" :
- print("Added in Team")
- let teamVc = storyboard.instantiateViewController(withIdentifier: "addTeam") as! TeamsListView
- teamVc.selectedName = userInfo["team_name"] as? String ?? ""
- teamVc.is_admin = false
- teamVc.isComingFromPushNotification = true
- TeamsListView.selectedTeamId = userInfo["team_id"] as? Int ?? 0
- (apptVC.rootViewController as? UINavigationController)?.show(teamVc, sender: self)
- self.window?.rootViewController = apptVC
- break
- case "invitation" :
- print("case: invitation")
- (apptVC.rootViewController as? UINavigationController)?.show(storyboard.instantiateViewController(withIdentifier: "ReceivedInvitesView"), sender: self)
- self.window?.rootViewController = apptVC
- //self.window?.makeKeyAndVisible()
- break
- case "chat" :
- print("case: chat")
- // if let nv = apptVC.rootViewController as? UINavigationController {
- // print(nv.childViewControllers)
- // if (nv.viewControllers.first as? ChatsView) == nil {
- //TODO
- if let chatsVC = (UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.first as? UINavigationController)?.visibleViewController {
- if chatsVC is ChatsView {
- }
- else {
- let conversationId = userInfo["conversation_id"] as? Int ?? 0
- var senderId = 0
- if let senderData = userInfo["sender_data"] as? NSDictionary, let id = senderData["id"] as? Int {
- senderId = id
- }
- // Update Badge Count
- if let info = userInfo as? [String : AnyObject] {
- toUpdateEventBadgeCountByOne()
- toUpdateChatUnreadCount(userInfo: info)
- }
- fetchConversationsMessages(withId: conversationId, apptVC: apptVC, storyboard: storyboard)
- }
- }
- else if let chatsVC = (UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.last as? UINavigationController)?.visibleViewController {
- if chatsVC is ChatsView {
- }
- else {
- let cID = userInfo["conversation_id"] as? Int ?? 0
- fetchConversationsMessages(withId: cID, apptVC: apptVC, storyboard: storyboard)
- }
- }
- break
- case "enrollment" :
- // If Rejected - Upcoming Event
- // If Approved - Open Subscribed List
- if let enrollmentAction = userInfo["action"] as? String {
- Store.User.shared.setEnrollmentSubscribedScreen(value: enrollmentAction == "accept" ? true : false)
- }
- self.window?.rootViewController = apptVC
- break
- case "add_participant":
- print(userInfo)
- // I'm assuming there is only two child vs. Refactor it.
- if let vcs = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers {
- if let nv = vcs.first as? UINavigationController {
- if let tabVc = nv.visibleViewController as? EventTabView {
- if let subcribedView = ((apptVC.rootViewController as? UINavigationController)?.viewControllers.first as? EventTabView)?.viewControllers?.first as? SubscribedEventsView {
- subcribedView.isComingFromPushNotification = true
- subcribedView.eventID = userInfo["event_id"] as? Int ?? 0
- self.window?.rootViewController = apptVC
- }
- }
- }
- if let nv = vcs.last as? UINavigationController {
- if let tabVc = nv.visibleViewController as? EventTabView {
- if let subcribedView = ((apptVC.rootViewController as? UINavigationController)?.viewControllers.first as? EventTabView)?.viewControllers?.first as? SubscribedEventsView {
- subcribedView.isComingFromPushNotification = true
- subcribedView.eventID = userInfo["event_id"] as? Int ?? 0
- self.window?.rootViewController = apptVC
- }
- }
- }
- }
- break
- case "delete_participant":
- // I'm assuming there is only two child vs. Refactor it.
- if let vcs = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers {
- if let nv = vcs.first as? UINavigationController {
- if let tabVc = nv.visibleViewController as? EventTabView {
- if let subcribedView = ((apptVC.rootViewController as? UINavigationController)?.viewControllers.first as? EventTabView)?.viewControllers?.first as? SubscribedEventsView {
- self.window?.rootViewController = apptVC
- }
- }
- }
- if let nv = vcs.last as? UINavigationController {
- if let tabVc = nv.visibleViewController as? EventTabView {
- if let subcribedView = ((apptVC.rootViewController as? UINavigationController)?.viewControllers.first as? EventTabView)?.viewControllers?.first as? SubscribedEventsView {
- self.window?.rootViewController = apptVC
- }
- }
- }
- }
- break
- default:
- break
- }
- }
- func fetchConversationsMessages(withId id: Int, apptVC: MainViewController?, storyboard: UIStoryboard) {
- ChatsService.getConversationsMessages(withUserId: String(id), success: { [weak self] (messages) in
- DispatchQueue.main.async {
- let datasource = DemoChatDataSource(messages: messages, pageSize: 100)
- let cv = storyboard.instantiateViewController(withIdentifier: "ChatsView") as! ChatsView
- cv.dataSource = datasource
- cv.messageSender = datasource.messageSender
- cv.conversationId = id
- let nv = UINavigationController(rootViewController: cv)
- if let vc = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.last as? UINavigationController {
- if let currentVC = vc.visibleViewController as? UIViewController {
- currentVC.present(nv, animated: true, completion: nil)
- self?.window?.makeKeyAndVisible()
- }
- }
- else if let vc = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.first as? UINavigationController{
- if let currentVC = vc.visibleViewController as? UIViewController {
- currentVC.present(nv, animated: true, completion: nil)
- self?.window?.makeKeyAndVisible()
- }
- }
- }
- }) { [weak self] (error) in
- DispatchQueue.main.async {
- print("Error while getting Conversation: \(error)")
- }
- // self?.iridiumUtils.activateIridiumNetwork(
- // success: { [weak self] (response) in
- // DispatchQueue.main.async {
- // ChatsService.getConversationsMessages(withUserId: String(id), success: { [weak self] (messages) in
- // DispatchQueue.main.async {
- // let datasource = DemoChatDataSource(messages: messages, pageSize: 100)
- // let cv = storyboard.instantiateViewController(withIdentifier: "ChatsView") as! ChatsView
- // cv.dataSource = datasource
- // cv.messageSender = datasource.messageSender
- // cv.conversationId = id
- // let nv = UINavigationController(rootViewController: cv)
- //
- // if let vc = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.last as? UINavigationController {
- // if let currentVC = vc.visibleViewController as? UIViewController {
- // currentVC.present(nv, animated: true, completion: nil)
- // self?.window?.makeKeyAndVisible()
- // }
- // }
- //
- // }
- // }) { [weak self] (error) in
- // DispatchQueue.main.async {
- //
- // }
- // }
- // }
- // })
- // { [weak self] (error) in
- // DispatchQueue.main.async {
- //
- // }
- // }
- }
- }
- //badge update methods
- func toUpdateEventBadgeCountByOne(){
- if var badgeCount = UserDefaults.standard.value(forKey: "badge_count") as? Int {
- badgeCount = badgeCount + 1
- UserDefaults.standard.set(badgeCount, forKey: "badge_count")
- }
- }
- func toUpdateChatUnreadCount(userInfo : [String : AnyObject]){
- if let conversationId = userInfo["conversation_id"] as? Int {
- DispatchQueue.main.async {
- let filteredConversation = ConversationListModel.getConversations().filter { (model) -> Bool in
- return model.conversationId == conversationId ? true : false
- }
- let newValue = filteredConversation.count + 1
- print("Count : \(newValue)")
- ConversationListModel.toUpdateNotReadCountsByConversationId(conversationId: conversationId, notReadCount: newValue)
- // Create a Conversation
- let model = ConversationListModel()
- model.conversationId = conversationId
- model.id = Int(arc4random())
- model.name = userInfo["sender_name"] as? String ?? ""
- model.badgeCount = newValue
- model.save()
- print("Total Count : \(ConversationListModel.get().count)")
- self.postNotificationsToUpdateBadge(conversationId: conversationId)
- }
- }
- }
- func postNotificationsToUpdateBadge(conversationId:Int){
- let senderIdDict : [String : Int] = ["senderId" : 0, "conversationId":conversationId]
- NotificationCenter.default.post(name: NSNotification.Name(rawValue : "toUpdateChatBadgeCount"),object : nil, userInfo: senderIdDict)
- }
- func toPostNotificationToUpdateEventBadgeCount(){
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "toUpdateBadgeCount"), object: nil)
- }
- func toPostNotificationToUpdateView(name: String){
- NotificationCenter.default.post(name: NSNotification.Name(rawValue:name),object:nil)
- }
- }
- // [END ios_10_message_handling]
Add Comment
Please, Sign In to add comment