AddFriendTableViewController.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. //
  2. // AddFriendTableViewController.swift
  3. // Qmera
  4. //
  5. // Created by Yayan Dwi on 23/09/21.
  6. //
  7. import UIKit
  8. class AddFriendTableViewController: UITableViewController {
  9. var searchController: UISearchController!
  10. var data: [User] = []
  11. var fillteredData: [User] = []
  12. var isSearchBarEmpty: Bool {
  13. return searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  14. }
  15. var isFilltering: Bool {
  16. return searchController.isActive && !isSearchBarEmpty
  17. }
  18. var isDismiss: (() -> ())?
  19. var timerSearch: Timer?
  20. func filterContentForSearchText(_ searchText: String) {
  21. fillteredData = data.filter{ $0.fullName.lowercased().contains(searchText.lowercased()) }
  22. getDataSearch(searchText: searchText) { data in
  23. let r = data.filter { $0.fullName.lowercased().contains(searchText.lowercased()) }
  24. self.fillteredData.append(contentsOf: r.filter { !self.fillteredData.contains($0) })
  25. DispatchQueue.main.async {
  26. self.tableView.reloadData()
  27. }
  28. }
  29. tableView.reloadData()
  30. }
  31. override func viewDidDisappear(_ animated: Bool) {
  32. isDismiss?()
  33. }
  34. override func viewDidLoad() {
  35. super.viewDidLoad()
  36. title = "Add Friends".localized()
  37. navigationController?.navigationBar.backgroundColor = .mainColor
  38. navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
  39. navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
  40. navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(cancel(sender:)))
  41. searchController = UISearchController(searchResultsController: nil)
  42. searchController.delegate = self
  43. searchController.searchResultsUpdater = self
  44. searchController.searchBar.autocapitalizationType = .none
  45. searchController.searchBar.delegate = self
  46. searchController.searchBar.barTintColor = .secondaryColor
  47. searchController.searchBar.searchTextField.backgroundColor = .secondaryColor
  48. searchController.obscuresBackgroundDuringPresentation = false
  49. searchController.searchBar.placeholder = "Search".localized()
  50. searchController.searchBar.setMagnifyingGlassColorTo(color: .mainColor)
  51. searchController.searchBar.tintColor = .mainColor
  52. definesPresentationContext = true
  53. navigationItem.searchController = searchController
  54. navigationItem.hidesSearchBarWhenScrolling = false
  55. tableView.tableFooterView = UIView()
  56. self.data.removeAll()
  57. getData { d in
  58. self.data = d
  59. DispatchQueue.main.async {
  60. self.tableView.reloadData()
  61. }
  62. }
  63. }
  64. @objc func cancel(sender: Any) {
  65. navigationController?.dismiss(animated: true, completion: nil)
  66. }
  67. // MARK: - Data source
  68. func getData(completion: @escaping ([User])->()) {
  69. DispatchQueue.global().async {
  70. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getPersonSuggestion(p_last_seq: "0")),
  71. response.isOk() {
  72. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  73. guard !data.isEmpty else {
  74. return
  75. }
  76. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: .utf8)!, options: []) as? [[String: String?]] {
  77. var users = jsonArray.map { json in
  78. User(pin: (json[CoreMessage_TMessageKey.F_PIN] ?? "") ?? "",
  79. firstName: (json[CoreMessage_TMessageKey.FIRST_NAME] ?? "") ?? "",
  80. lastName: (json[CoreMessage_TMessageKey.LAST_NAME] ?? "") ?? "",
  81. thumb: (json[CoreMessage_TMessageKey.THUMB_ID] ?? "") ?? "")
  82. }
  83. users = users.filter({ $0.fullName != "USR\($0.pin)" })
  84. completion(users)
  85. }
  86. }
  87. }
  88. }
  89. func getDataSearch(searchText: String, completion: @escaping ([User]) -> ()) {
  90. DispatchQueue.global().async {
  91. if let response = Nexilis.writeSync(message: CoreMessage_TMessageBank.getSearchFriend(search_keyword: searchText, limit: "10")), response.isOk() {
  92. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  93. guard !data.isEmpty else {
  94. return
  95. }
  96. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: .utf8)!, options: []) as? [[String: String?]] {
  97. var users = jsonArray.map { json in
  98. User(pin: (json[CoreMessage_TMessageKey.F_PIN] ?? "") ?? "",
  99. firstName: (json[CoreMessage_TMessageKey.FIRST_NAME] ?? "") ?? "",
  100. lastName: (json[CoreMessage_TMessageKey.LAST_NAME] ?? "") ?? "",
  101. thumb: (json[CoreMessage_TMessageKey.THUMB_ID] ?? "") ?? "")
  102. }
  103. users = users.filter({ $0.fullName != "USR\($0.pin)" })
  104. completion(users)
  105. }
  106. }
  107. }
  108. }
  109. // MARK: - Table view data source
  110. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  111. return "Suggestions".localized()
  112. }
  113. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  114. let user: User
  115. if isFilltering {
  116. user = fillteredData[indexPath.row]
  117. } else {
  118. user = data[indexPath.row]
  119. }
  120. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  121. controller.flag = .invite
  122. controller.data = user.pin
  123. controller.name = user.fullName
  124. controller.picture = user.thumb
  125. controller.isDismiss = {
  126. self.data.removeAll(where: {$0.pin == user.pin})
  127. if self.isFilltering {
  128. self.fillteredData.removeAll(where: {$0.pin == user.pin})
  129. }
  130. self.tableView.reloadData()
  131. // self.getData { d in
  132. // self.data = d
  133. // DispatchQueue.main.async {
  134. // self.tableView.reloadData()
  135. // }
  136. // }
  137. }
  138. navigationController?.show(controller, sender: nil)
  139. }
  140. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  141. if isFilltering {
  142. return fillteredData.count
  143. }
  144. return data.count
  145. }
  146. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  147. let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
  148. var content = cell.defaultContentConfiguration()
  149. let user: User
  150. if isFilltering {
  151. user = fillteredData[indexPath.row]
  152. } else {
  153. user = data[indexPath.row]
  154. }
  155. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  156. getImage(name: user.thumb, placeholderImage: UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
  157. content.image = image
  158. })
  159. content.text = user.fullName
  160. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  161. cell.contentConfiguration = content
  162. return cell
  163. }
  164. }
  165. // MARK: - Extension
  166. extension AddFriendTableViewController: UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
  167. func updateSearchResults(for searchController: UISearchController) {
  168. timerSearch?.invalidate()
  169. let currentText = searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines)
  170. if currentText.count >= 2 || currentText.isEmpty {
  171. timerSearch = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: {_ in
  172. self.filterContentForSearchText(currentText)
  173. })
  174. }
  175. }
  176. }