我正在嘗試重新加載我的tableview,以便用戶可以獲取與其位置相關的刷新數據。我目前的設置已經到了當我進行「拉動刷新」時,它將開始向tableview添加重複數據,而不是清除它,並用新數據替換它。我覺得有1行代碼,將解決這個問題,但我不知道它是什麼,我覺得我以前在哪兒見過吧...Swift Firebase UIRefreshControl
var refresher: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
locationManager.delegate = self
locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
locationManager.stopUpdatingLocation()
getTableViewData()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: #selector(RegisteredLocationsTableView.handleRefresh(refreshControl:)), for: UIControlEvents.valueChanged)
tableView.addSubview(refresher)
}
func handleRefresh(refreshControl: UIRefreshControl) {
getTableViewData()
self.tableView.reloadData()
refreshControl.endRefreshing()
}
func getTableViewData() {
databaseRef.child("Businesses").queryOrdered(byChild: "businessName").observe(.childAdded, with: { (snapshot) in
let key = snapshot.key
if(key == self.loggedInUser?.uid) {
print("Same as logged in user, so don't show!")
} else {
if let locationValue = snapshot.value as? [String: AnyObject] {
let lat = Double(locationValue["businessLatitude"] as! String)
let long = Double(locationValue["businessLongitude"] as! String)
let businessLocation = CLLocation(latitude: lat!, longitude: long!)
let latitude = self.locationManager.location?.coordinate.latitude
let longitude = self.locationManager.location?.coordinate.longitude
let userLocation = CLLocation(latitude: latitude!, longitude: longitude!)
let distanceInMeters : Double = userLocation.distance(from: businessLocation)
let distanceInMiles : Double = ((distanceInMeters.description as String).doubleValue * 0.00062137)
let distanceLabelText = "\(distanceInMiles.string(2)) miles away"
var singleChildDictionary = locationValue
singleChildDictionary["distanceLabelText"] = distanceLabelText as AnyObject
singleChildDictionary["distanceInMiles"] = distanceInMiles as AnyObject
self.usersArray.append(singleChildDictionary as NSDictionary)
self.usersArray = self.usersArray.sorted {
!($0?["distanceInMiles"] as! Double > $1?["distanceInMiles"] as! Double)
}
}
//insert the rows
//self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
self.followUsersTableView.reloadData()
}
}) { (error) in
print(error.localizedDescription)
}
}
你使用'userArray'填充tableview嗎? – Amit
是的,我正在使用userArray填充tableview –
在'handleRefresh'方法中,嘗試在使用'self調用'getTableViewData'前清除數組數據。 userArray.removeAllObjects()' – Amit