Guest User

Untitled

a guest
Sep 18th, 2018
460
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.18 KB | None | 0 0
  1. //
  2. // AppDelegate.swift
  3. // myRaceTracker
  4. //
  5. // Created by Thoughts2Binary on 10/5/17.
  6. // Copyright Ā© 2017 Thoughts2Binary. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import Fabric
  11. import Crashlytics
  12. import IQKeyboardManagerSwift
  13. import UserNotifications
  14. import Bugsee
  15. import RealmSwift
  16.  
  17. @UIApplicationMain
  18. class AppDelegate: UIResponder, UIApplicationDelegate{
  19.  
  20. var window: UIWindow?
  21. var iridiumUtils = IridiumUtils()
  22.  
  23. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  24. // Override point for customization after application launch.
  25.  
  26. Bugsee.launch(token:"f8ec2647-caec-4d08-9588-c90110242a60")
  27.  
  28. print(Realm.Configuration.defaultConfiguration.fileURL)
  29.  
  30. UserDefaults.standard.setValue(0, forKey: "badge_count")
  31. Fabric.with([Crashlytics.self])
  32. if let token = UserDefaults.standard.value(forKey: "auth_token") {
  33. print("Auth Token \(token)")
  34. Store.User.shared.setAccessToken(token as! String)
  35. if let iridium_username = UserDefaults.standard.value(forKey: "iridium_username") {
  36. Store.User.shared.setUsername(iridium_username as! String)
  37. }
  38. if let iridium_password = UserDefaults.standard.value(forKey: "iridium_password") {
  39. Store.User.shared.setUsername(iridium_password as! String)
  40. }
  41. }
  42.  
  43. //GMSServices.provideAPIKey("AIzaSyBsJqje8jgWPJh4a9mUEHq2tGf_WokdwMI")
  44. UIApplication.shared.setMinimumBackgroundFetchInterval(1.0)
  45. IQKeyboardManager.sharedManager().enable = true
  46. UNUserNotificationCenter.current().delegate = self
  47.  
  48. // if (launchOptions != nil){
  49. // let dictionary = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as! [AnyHashable : Any]
  50. // print("userInfo: \(dictionary)")
  51. // openInvitesViewController(userInfo: dictionary)
  52. // }else{
  53. // print("launchOptions: nil")
  54. // }
  55.  
  56. return true
  57. }
  58.  
  59. func navigateToSavedScreen() {
  60.  
  61. if let mainController = UIApplication.shared.keyWindow?.rootViewController as? MainViewController {
  62.  
  63. if let navigationContoller = mainController.rootViewController as? UINavigationController {
  64.  
  65. let storyboard = UIStoryboard(name: "Main", bundle: .main)
  66.  
  67. if navigationContoller.viewControllers.last is SavedEventsView {
  68. // Do Nothing
  69. }
  70. else {
  71. navigationContoller.show(storyboard.instantiateViewController(withIdentifier: "SavedEventsView"), sender: self)
  72. }
  73. }
  74. }
  75. }
  76.  
  77. func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  78. print("Background Execution 111")
  79. completionHandler(UIBackgroundFetchResult.newData)
  80. }
  81.  
  82. func applicationWillResignActive(_ application: UIApplication) {
  83. // 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.
  84. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
  85. }
  86.  
  87. func applicationDidEnterBackground(_ application: UIApplication) {
  88. // 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.
  89. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  90. // UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
  91. }
  92.  
  93. func applicationWillEnterForeground(_ application: UIApplication) {
  94. // 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.
  95. }
  96.  
  97. func applicationDidBecomeActive(_ application: UIApplication) {
  98. // 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.
  99. }
  100.  
  101. func applicationWillTerminate(_ application: UIApplication) {
  102. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  103. // Saves changes in the application's managed object context before the application terminates.
  104. }
  105.  
  106. func registerToken(token: String){
  107. let parameters = ["name" : "", "registration_id" : token]
  108. UserService.sendDeviceToken(parameters: parameters
  109. , success: {
  110. UserDefaults.standard.set(token, forKey: "DEVICE_TOKEN")
  111. }) { [unowned self] (error) in
  112. }
  113. }
  114.  
  115. // [END receive_message]
  116. func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  117. print("Unable to register for remote notifications: \(error.localizedDescription)")
  118. }
  119.  
  120. // This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
  121. // If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
  122. // the FCM registration token.
  123. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  124. let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
  125. print("APNs token retrieved: \(deviceTokenString)")
  126. if let _ = UserDefaults.standard.string(forKey: "DEVICE_TOKEN") {
  127. return
  128. }
  129. self.registerToken(token: deviceTokenString)
  130. // With swizzling disabled you must set the APNs token here.
  131. // Messaging.messaging().apnsToken = deviceToken
  132. }
  133. }
  134.  
  135. // [START ios_10_message_handling]
  136. @available(iOS 10, *)
  137. extension AppDelegate : UNUserNotificationCenterDelegate {
  138.  
  139. // Receive displayed notifications for iOS 10 devices.
  140. func userNotificationCenter(_ center: UNUserNotificationCenter,
  141. willPresent notification: UNNotification,
  142. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  143.  
  144. if let userInfo = notification.request.content.userInfo as? [String : AnyObject]{
  145.  
  146. guard Store.User.shared.isDownloadingOfflineMap() == false else {return}
  147.  
  148. print("App in foreground")
  149.  
  150. // let notificationModel = NotificationModel()
  151. // let notificationViewModel = NotificationViewModel()
  152.  
  153. var senderId = 0
  154. var username = ""
  155. if let senderData = userInfo["sender_data"] as? NSDictionary {
  156. let userPublicModel = UserPublicModel()
  157. if let email = senderData["email"] as? String {
  158. userPublicModel.email = email
  159. }
  160. if let first_name = senderData["first_name"] as? String {
  161. userPublicModel.firstName = first_name
  162. }
  163. if let full_name = senderData["full_name"] as? String {
  164. userPublicModel.full_name = full_name
  165.  
  166. // notificationModel.senderName = full_name
  167. username = full_name
  168. }
  169.  
  170. if let id = senderData["id"] as? Int {
  171. userPublicModel.id = id
  172. senderId = id
  173. // notificationModel.senderId = id
  174.  
  175. }
  176.  
  177. if let is_active = senderData["is_active"] as? Bool {
  178. userPublicModel.is_active = is_active
  179. }
  180. if let phone = senderData["phone"] as? String {
  181. userPublicModel.phone = phone
  182. }
  183. if let username = senderData["username"] as? String {
  184. userPublicModel.username = username
  185. }
  186. if let last_name = senderData["last_name"] as? String {
  187. userPublicModel.lastName = last_name
  188. }
  189. if let profileInfo = senderData["profile"] as? NSDictionary {
  190. let profile = UserPublicProfileModel()
  191. if let _ = profileInfo["profile_picture"] as? String {
  192. profile.profilePicUrl = (profileInfo["profile_picture"] as? String)!
  193. }
  194. if let _ = profileInfo["title"] as? String {
  195. profile.title = (profileInfo["title"] as? String)!
  196. }
  197. userPublicModel.userProfile = profile
  198. }
  199. userPublicModel.save()
  200. }
  201.  
  202.  
  203. let logViewModel = LogViewModel()
  204. let type = userInfo["type"] as? String ?? ""
  205. let cID = userInfo["conversation_id"] as? Int ?? 0
  206. let currentCid = Store.User.shared.getConversationId()
  207. let currentUser = Store.User.shared.getConversationName()
  208.  
  209. if type == "enrollment" {
  210. let action = userInfo["action"] as? String ?? ""
  211. if action == "accept" {
  212. toPostNotificationToUpdateView(name: "toUpdateSubscribedView")
  213. }
  214. }
  215.  
  216. if type == "add_participant" {
  217. toPostNotificationToUpdateView(name: "toUpdateSubscribedView")
  218. }
  219.  
  220. if type == "delete_participant" {
  221. toPostNotificationToUpdateView(name: "toUpdateSubscribedView")
  222. }
  223.  
  224. if type == "invitation" {
  225. let action = userInfo["action"] as? String ?? ""
  226. if action.isEmpty {
  227. toPostNotificationToUpdateView(name: "toUpdateReceivedInvitesView")
  228. }
  229. }
  230.  
  231.  
  232. if let chatsVC = (UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.first as? UINavigationController)?.visibleViewController, chatsVC is ChatsView {
  233.  
  234. if let _:ChatsView = chatsVC as? ChatsView {
  235.  
  236. if currentCid == cID || currentUser == username {
  237. ChatsService.getUnreadMessageFromNotification(cID, success: { /*[weak self]*/ (messages) in
  238. (chatsVC as! ChatsView).dataSource.insertIncomingMessage(messages)
  239. logViewModel.add("REFRESHED_CHATS_VIA_NOTIFICATION", "Success: \(messages)")
  240. })
  241. { /*[weak self]*/ (error) in
  242. DispatchQueue.main.async {
  243. logViewModel.add("ERROR_REFRESHING_CHATS_VIA_NOTIFICATION", "Error: \(error)")
  244. }
  245. }
  246.  
  247. }
  248. else {
  249.  
  250. completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
  251.  
  252. toUpdateEventBadgeCountByOne()
  253. toUpdateChatUnreadCount(userInfo: userInfo)
  254. //toPostNotificationsToUpdateBadge(senderId: senderId,conversationId: cID)
  255. //toPostNotificationToUpdateEventBadgeCount()
  256.  
  257. }
  258. }
  259. }else{
  260. print("User is on another screen")
  261. completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
  262.  
  263. toUpdateEventBadgeCountByOne()
  264. toUpdateChatUnreadCount(userInfo: userInfo)
  265.  
  266. }
  267. print("userNotificationCenter: willPresent")
  268. debugPrint(userInfo)
  269. }
  270. }
  271.  
  272. func userNotificationCenter(_ center: UNUserNotificationCenter,
  273. didReceive response: UNNotificationResponse,
  274. withCompletionHandler completionHandler: @escaping () -> Void) {
  275.  
  276. if let userInfo = response.notification.request.content.userInfo as? [String : AnyObject]{
  277. print("App in background or closed")
  278. print(userInfo)
  279.  
  280. guard Store.User.shared.isDownloadingOfflineMap() == false else {return}
  281.  
  282. if let senderData = userInfo["sender_data"] as? NSDictionary {
  283. let userPublicModel = UserPublicModel()
  284. if let email = senderData["email"] as? String {
  285. userPublicModel.email = email
  286. }
  287. if let first_name = senderData["first_name"] as? String {
  288. userPublicModel.firstName = first_name
  289. }
  290. if let full_name = senderData["full_name"] as? String {
  291. userPublicModel.full_name = full_name
  292. // notificationModel.senderName = full_name
  293.  
  294. }
  295.  
  296. if let id = senderData["id"] as? Int {
  297. userPublicModel.id = id
  298. // notificationModel.senderId = id
  299.  
  300. }
  301.  
  302. if let is_active = senderData["is_active"] as? Bool {
  303. userPublicModel.is_active = is_active
  304. }
  305. if let phone = senderData["phone"] as? String {
  306. userPublicModel.phone = phone
  307. }
  308. if let username = senderData["username"] as? String {
  309. userPublicModel.username = username
  310. }
  311. if let last_name = senderData["last_name"] as? String {
  312. userPublicModel.lastName = last_name
  313. }
  314. if let profileInfo = senderData["profile"] as? NSDictionary {
  315. let profile = UserPublicProfileModel()
  316. if let _ = profileInfo["profile_picture"] as? String {
  317. profile.profilePicUrl = (profileInfo["profile_picture"] as? String)!
  318. }
  319. if let _ = profileInfo["title"] as? String {
  320. profile.title = (profileInfo["title"] as? String)!
  321. }
  322. userPublicModel.userProfile = profile
  323. }
  324. userPublicModel.save()
  325. }
  326.  
  327. if userInfo["type"] != nil {
  328. openInvitesViewController(userInfo: userInfo)
  329. }
  330. if userInfo.count == 0 {
  331. let cId = UserDefaults.standard.object(forKey: "conversation") as! Int
  332. var messages = MessagesModel.getMessagesForConversation(cId)
  333. messages = messages.sorted(by: {$0.create_date > $1.create_date})
  334. var messagesArray = [DemoTextMessageModel]()
  335. messages.forEach{ message in
  336. 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)
  337. }
  338.  
  339. let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
  340. let datasource = DemoChatDataSource(messages: messagesArray, pageSize: 100)
  341. let cv = storyboard.instantiateViewController(withIdentifier: "ChatsView") as! ChatsView
  342. cv.dataSource = datasource
  343. cv.messageSender = datasource.messageSender
  344.  
  345. let nv = UINavigationController(rootViewController: cv)
  346. if let vc = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.last as? UINavigationController {
  347.  
  348. if let currentVC = vc.visibleViewController {
  349. currentVC.present(nv, animated: true, completion: nil)
  350. self.window?.makeKeyAndVisible()
  351. }
  352. }
  353.  
  354. }
  355. }
  356. //completionHandler()
  357. }
  358.  
  359. func openInvitesViewController(userInfo: [AnyHashable: Any]){
  360. let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
  361. let apptVC = storyboard.instantiateViewController(withIdentifier: "eventsDashboard") as! MainViewController
  362.  
  363. let type = userInfo["type"] as? String ?? ""
  364. switch type {
  365.  
  366. case "team" :
  367. print("Added in Team")
  368.  
  369. let teamVc = storyboard.instantiateViewController(withIdentifier: "addTeam") as! TeamsListView
  370. teamVc.selectedName = userInfo["team_name"] as? String ?? ""
  371. teamVc.is_admin = false
  372. teamVc.isComingFromPushNotification = true
  373. TeamsListView.selectedTeamId = userInfo["team_id"] as? Int ?? 0
  374.  
  375.  
  376. (apptVC.rootViewController as? UINavigationController)?.show(teamVc, sender: self)
  377. self.window?.rootViewController = apptVC
  378. break
  379.  
  380. case "invitation" :
  381. print("case: invitation")
  382. (apptVC.rootViewController as? UINavigationController)?.show(storyboard.instantiateViewController(withIdentifier: "ReceivedInvitesView"), sender: self)
  383. self.window?.rootViewController = apptVC
  384. //self.window?.makeKeyAndVisible()
  385. break
  386. case "chat" :
  387. print("case: chat")
  388. // if let nv = apptVC.rootViewController as? UINavigationController {
  389. // print(nv.childViewControllers)
  390. // if (nv.viewControllers.first as? ChatsView) == nil {
  391.  
  392. //TODO
  393. if let chatsVC = (UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.first as? UINavigationController)?.visibleViewController {
  394.  
  395. if chatsVC is ChatsView {
  396.  
  397. }
  398. else {
  399.  
  400.  
  401. let conversationId = userInfo["conversation_id"] as? Int ?? 0
  402. var senderId = 0
  403. if let senderData = userInfo["sender_data"] as? NSDictionary, let id = senderData["id"] as? Int {
  404. senderId = id
  405. }
  406.  
  407. // Update Badge Count
  408. if let info = userInfo as? [String : AnyObject] {
  409. toUpdateEventBadgeCountByOne()
  410. toUpdateChatUnreadCount(userInfo: info)
  411. }
  412.  
  413. fetchConversationsMessages(withId: conversationId, apptVC: apptVC, storyboard: storyboard)
  414. }
  415. }
  416. else if let chatsVC = (UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.last as? UINavigationController)?.visibleViewController {
  417.  
  418. if chatsVC is ChatsView {
  419.  
  420. }
  421. else {
  422. let cID = userInfo["conversation_id"] as? Int ?? 0
  423. fetchConversationsMessages(withId: cID, apptVC: apptVC, storyboard: storyboard)
  424. }
  425. }
  426. break
  427. case "enrollment" :
  428. // If Rejected - Upcoming Event
  429. // If Approved - Open Subscribed List
  430.  
  431. if let enrollmentAction = userInfo["action"] as? String {
  432. Store.User.shared.setEnrollmentSubscribedScreen(value: enrollmentAction == "accept" ? true : false)
  433. }
  434.  
  435. self.window?.rootViewController = apptVC
  436. break
  437.  
  438. case "add_participant":
  439.  
  440. print(userInfo)
  441. // I'm assuming there is only two child vs. Refactor it.
  442. if let vcs = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers {
  443.  
  444. if let nv = vcs.first as? UINavigationController {
  445. if let tabVc = nv.visibleViewController as? EventTabView {
  446.  
  447. if let subcribedView = ((apptVC.rootViewController as? UINavigationController)?.viewControllers.first as? EventTabView)?.viewControllers?.first as? SubscribedEventsView {
  448.  
  449. subcribedView.isComingFromPushNotification = true
  450. subcribedView.eventID = userInfo["event_id"] as? Int ?? 0
  451.  
  452. self.window?.rootViewController = apptVC
  453. }
  454.  
  455. }
  456. }
  457.  
  458. if let nv = vcs.last as? UINavigationController {
  459. if let tabVc = nv.visibleViewController as? EventTabView {
  460.  
  461. if let subcribedView = ((apptVC.rootViewController as? UINavigationController)?.viewControllers.first as? EventTabView)?.viewControllers?.first as? SubscribedEventsView {
  462.  
  463. subcribedView.isComingFromPushNotification = true
  464. subcribedView.eventID = userInfo["event_id"] as? Int ?? 0
  465.  
  466. self.window?.rootViewController = apptVC
  467. }
  468.  
  469. }
  470. }
  471. }
  472.  
  473. break
  474.  
  475. case "delete_participant":
  476.  
  477. // I'm assuming there is only two child vs. Refactor it.
  478. if let vcs = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers {
  479.  
  480. if let nv = vcs.first as? UINavigationController {
  481. if let tabVc = nv.visibleViewController as? EventTabView {
  482.  
  483. if let subcribedView = ((apptVC.rootViewController as? UINavigationController)?.viewControllers.first as? EventTabView)?.viewControllers?.first as? SubscribedEventsView {
  484.  
  485. self.window?.rootViewController = apptVC
  486. }
  487. }
  488. }
  489.  
  490. if let nv = vcs.last as? UINavigationController {
  491. if let tabVc = nv.visibleViewController as? EventTabView {
  492.  
  493. if let subcribedView = ((apptVC.rootViewController as? UINavigationController)?.viewControllers.first as? EventTabView)?.viewControllers?.first as? SubscribedEventsView {
  494.  
  495. self.window?.rootViewController = apptVC
  496. }
  497. }
  498. }
  499. }
  500.  
  501. break
  502.  
  503. default:
  504. break
  505. }
  506. }
  507.  
  508. func fetchConversationsMessages(withId id: Int, apptVC: MainViewController?, storyboard: UIStoryboard) {
  509.  
  510. ChatsService.getConversationsMessages(withUserId: String(id), success: { [weak self] (messages) in
  511. DispatchQueue.main.async {
  512. let datasource = DemoChatDataSource(messages: messages, pageSize: 100)
  513. let cv = storyboard.instantiateViewController(withIdentifier: "ChatsView") as! ChatsView
  514. cv.dataSource = datasource
  515. cv.messageSender = datasource.messageSender
  516. cv.conversationId = id
  517. let nv = UINavigationController(rootViewController: cv)
  518.  
  519. if let vc = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.last as? UINavigationController {
  520. if let currentVC = vc.visibleViewController as? UIViewController {
  521. currentVC.present(nv, animated: true, completion: nil)
  522. self?.window?.makeKeyAndVisible()
  523. }
  524.  
  525. }
  526. else if let vc = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.first as? UINavigationController{
  527.  
  528. if let currentVC = vc.visibleViewController as? UIViewController {
  529. currentVC.present(nv, animated: true, completion: nil)
  530. self?.window?.makeKeyAndVisible()
  531. }
  532. }
  533.  
  534. }
  535. }) { [weak self] (error) in
  536.  
  537. DispatchQueue.main.async {
  538. print("Error while getting Conversation: \(error)")
  539. }
  540.  
  541. // self?.iridiumUtils.activateIridiumNetwork(
  542. // success: { [weak self] (response) in
  543. // DispatchQueue.main.async {
  544. // ChatsService.getConversationsMessages(withUserId: String(id), success: { [weak self] (messages) in
  545. // DispatchQueue.main.async {
  546. // let datasource = DemoChatDataSource(messages: messages, pageSize: 100)
  547. // let cv = storyboard.instantiateViewController(withIdentifier: "ChatsView") as! ChatsView
  548. // cv.dataSource = datasource
  549. // cv.messageSender = datasource.messageSender
  550. // cv.conversationId = id
  551. // let nv = UINavigationController(rootViewController: cv)
  552. //
  553. // if let vc = UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.last as? UINavigationController {
  554. // if let currentVC = vc.visibleViewController as? UIViewController {
  555. // currentVC.present(nv, animated: true, completion: nil)
  556. // self?.window?.makeKeyAndVisible()
  557. // }
  558. // }
  559. //
  560. // }
  561. // }) { [weak self] (error) in
  562. // DispatchQueue.main.async {
  563. //
  564. // }
  565. // }
  566. // }
  567. // })
  568. // { [weak self] (error) in
  569. // DispatchQueue.main.async {
  570. //
  571. // }
  572. // }
  573. }
  574. }
  575.  
  576. //badge update methods
  577.  
  578. func toUpdateEventBadgeCountByOne(){
  579. if var badgeCount = UserDefaults.standard.value(forKey: "badge_count") as? Int {
  580. badgeCount = badgeCount + 1
  581. UserDefaults.standard.set(badgeCount, forKey: "badge_count")
  582. }
  583. }
  584.  
  585. func toUpdateChatUnreadCount(userInfo : [String : AnyObject]){
  586. if let conversationId = userInfo["conversation_id"] as? Int {
  587.  
  588. DispatchQueue.main.async {
  589.  
  590. let filteredConversation = ConversationListModel.getConversations().filter { (model) -> Bool in
  591. return model.conversationId == conversationId ? true : false
  592. }
  593.  
  594. let newValue = filteredConversation.count + 1
  595. print("Count : \(newValue)")
  596.  
  597. ConversationListModel.toUpdateNotReadCountsByConversationId(conversationId: conversationId, notReadCount: newValue)
  598.  
  599. // Create a Conversation
  600. let model = ConversationListModel()
  601. model.conversationId = conversationId
  602. model.id = Int(arc4random())
  603. model.name = userInfo["sender_name"] as? String ?? ""
  604. model.badgeCount = newValue
  605. model.save()
  606.  
  607. print("Total Count : \(ConversationListModel.get().count)")
  608.  
  609. self.postNotificationsToUpdateBadge(conversationId: conversationId)
  610. }
  611.  
  612. }
  613. }
  614.  
  615. func postNotificationsToUpdateBadge(conversationId:Int){
  616. let senderIdDict : [String : Int] = ["senderId" : 0, "conversationId":conversationId]
  617.  
  618. NotificationCenter.default.post(name: NSNotification.Name(rawValue : "toUpdateChatBadgeCount"),object : nil, userInfo: senderIdDict)
  619. }
  620.  
  621. func toPostNotificationToUpdateEventBadgeCount(){
  622. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "toUpdateBadgeCount"), object: nil)
  623. }
  624.  
  625. func toPostNotificationToUpdateView(name: String){
  626. NotificationCenter.default.post(name: NSNotification.Name(rawValue:name),object:nil)
  627. }
  628.  
  629. }
  630. // [END ios_10_message_handling]
Add Comment
Please, Sign In to add comment