AddFriendTableViewController.swift 9.1 KB

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