AddFriendTableViewController.swift 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. let attributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
  38. let navBarAppearance = UINavigationBarAppearance()
  39. navBarAppearance.configureWithOpaqueBackground()
  40. navBarAppearance.backgroundColor = UIColor.mainColor
  41. navBarAppearance.titleTextAttributes = attributes
  42. navigationController?.navigationBar.standardAppearance = navBarAppearance
  43. navigationController?.navigationBar.scrollEdgeAppearance = navBarAppearance
  44. navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel".localized(), style: .plain, target: self, action: #selector(cancel(sender:)))
  45. searchController = UISearchController(searchResultsController: nil)
  46. searchController.delegate = self
  47. searchController.searchResultsUpdater = self
  48. searchController.searchBar.autocapitalizationType = .none
  49. searchController.searchBar.delegate = self
  50. searchController.searchBar.barTintColor = .secondaryColor
  51. searchController.searchBar.searchTextField.backgroundColor = .secondaryColor
  52. searchController.obscuresBackgroundDuringPresentation = false
  53. searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  54. searchController.searchBar.setMagnifyingGlassColorTo(color: .mainColor)
  55. searchController.searchBar.tintColor = .mainColor
  56. definesPresentationContext = true
  57. navigationItem.searchController = searchController
  58. navigationItem.hidesSearchBarWhenScrolling = false
  59. tableView.tableFooterView = UIView()
  60. self.data.removeAll()
  61. getData { d in
  62. self.data = d
  63. DispatchQueue.main.async {
  64. self.tableView.reloadData()
  65. }
  66. }
  67. }
  68. @objc func cancel(sender: Any) {
  69. navigationController?.dismiss(animated: true, completion: nil)
  70. }
  71. // MARK: - Data source
  72. func getData(completion: @escaping ([User])->()) {
  73. DispatchQueue.global().async {
  74. if let response = DigiX.writeSync(message: CoreMessage_TMessageBank.getPersonSuggestion(p_last_seq: "0")),
  75. response.isOk() {
  76. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  77. guard !data.isEmpty else {
  78. return
  79. }
  80. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: .utf8)!, options: []) as? [[String: String?]] {
  81. var users = jsonArray.map { json in
  82. User(pin: (json[CoreMessage_TMessageKey.F_PIN] ?? "") ?? "",
  83. firstName: (json[CoreMessage_TMessageKey.FIRST_NAME] ?? "") ?? "",
  84. lastName: (json[CoreMessage_TMessageKey.LAST_NAME] ?? "") ?? "",
  85. thumb: (json[CoreMessage_TMessageKey.THUMB_ID] ?? "") ?? "")
  86. }
  87. users = users.filter({ $0.fullName != "USR\($0.pin)" })
  88. completion(users)
  89. }
  90. }
  91. }
  92. }
  93. func getDataSearch(searchText: String, completion: @escaping ([User]) -> ()) {
  94. DispatchQueue.global().async {
  95. if let response = DigiX.writeSync(message: CoreMessage_TMessageBank.getSearchFriend(search_keyword: searchText, limit: "10")), response.isOk() {
  96. let data = response.getBody(key: CoreMessage_TMessageKey.DATA)
  97. guard !data.isEmpty else {
  98. return
  99. }
  100. if let jsonArray = try! JSONSerialization.jsonObject(with: data.data(using: .utf8)!, options: []) as? [[String: String?]] {
  101. var users = jsonArray.map { json in
  102. User(pin: (json[CoreMessage_TMessageKey.F_PIN] ?? "") ?? "",
  103. firstName: (json[CoreMessage_TMessageKey.FIRST_NAME] ?? "") ?? "",
  104. lastName: (json[CoreMessage_TMessageKey.LAST_NAME] ?? "") ?? "",
  105. thumb: (json[CoreMessage_TMessageKey.THUMB_ID] ?? "") ?? "")
  106. }
  107. users = users.filter({ $0.fullName != "USR\($0.pin)" })
  108. completion(users)
  109. }
  110. }
  111. }
  112. }
  113. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  114. searchBar.showsCancelButton = true
  115. let cBtn = searchBar.value(forKey: "cancelButton") as! UIButton
  116. cBtn.setTitle("Cancel".localized(), for: .normal)
  117. }
  118. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  119. searchBar.showsCancelButton = false
  120. }
  121. // MARK: - Table view data source
  122. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  123. return "Suggestions".localized()
  124. }
  125. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  126. let user: User
  127. if isFilltering {
  128. user = fillteredData[indexPath.row]
  129. } else {
  130. user = data[indexPath.row]
  131. }
  132. let controller = AppStoryBoard.Palio.instance.instantiateViewController(withIdentifier: "profileView") as! ProfileViewController
  133. controller.flag = .invite
  134. controller.data = user.pin
  135. controller.name = user.fullName
  136. controller.picture = user.thumb
  137. controller.isDismiss = {
  138. self.data.removeAll(where: {$0.pin == user.pin})
  139. if self.isFilltering {
  140. self.fillteredData.removeAll(where: {$0.pin == user.pin})
  141. }
  142. self.tableView.reloadData()
  143. // self.getData { d in
  144. // self.data = d
  145. // DispatchQueue.main.async {
  146. // self.tableView.reloadData()
  147. // }
  148. // }
  149. }
  150. navigationController?.show(controller, sender: nil)
  151. }
  152. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  153. if isFilltering {
  154. return fillteredData.count
  155. }
  156. return data.count
  157. }
  158. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  159. let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
  160. var content = cell.defaultContentConfiguration()
  161. let user: User
  162. if isFilltering {
  163. user = fillteredData[indexPath.row]
  164. } else {
  165. user = data[indexPath.row]
  166. }
  167. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  168. getImage(name: user.thumb, placeholderImage: UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: DigiX.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
  169. content.image = image
  170. })
  171. content.text = user.fullName
  172. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  173. cell.contentConfiguration = content
  174. return cell
  175. }
  176. }
  177. // MARK: - Extension
  178. extension AddFriendTableViewController: UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
  179. func updateSearchResults(for searchController: UISearchController) {
  180. timerSearch?.invalidate()
  181. let currentText = searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines)
  182. if currentText.count >= 2 || currentText.isEmpty {
  183. timerSearch = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: {_ in
  184. self.filterContentForSearchText(currentText)
  185. })
  186. }
  187. }
  188. }