我在将数据加载到表格时遇到问题。在第一次点击时没有任何反应,它正在点击我的getLocations函数并且它正在完成,因为它打印(2)但表中没有显示任何内容。如果我按回然后重试,数据就在那里。我已经尝试将DispatchQueue.main.async {reload table}放在多个区域但仍然会发生。可能是我如何调用端点?昨晚我发了一篇关于它的帖子,它就在这里,它现在正在工作。这是一个愚蠢的json结构:-x Swift 4 decoding json using Codable。有没有办法预取数据?
protocol LocationListDelegate: NSObjectProtocol
{
func sendLocationList(_ controller: LocationViewController, data:
[LocationList])
}
class LocationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var locList: [LocationList] = [] //could this be giving me problems?
@IBOutlet weak var locationListTableView: UITableView!
weak var delegate: LocationListDelegate?
override func viewDidLoad() {
super.viewDidLoad()
locationListTableView.dataSource = self
locationListTableView.delegate = self
// call endpoint
locList = getLocationsFromService()
// DispatchQueue.main.async {
// self.locationListTableView.reloadData()
// }
}
//override func viewDidAppear(_ animated: Bool) {
// super.viewDidAppear(animated)
// self.locationListTableView.reloadData()
//}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = locationListTableView.dequeueReusableCell(withIdentifier: "LocationCell") as? LocationsViewCell {
let location = locList[indexPath.row]
//print(location)
cell.updateView(locations: location)
// DispatchQueue.main.async {
// self.locationListTableView.reloadData()
// }
return cell
} else {
return LocationsViewCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let location = locList[indexPath.row]
if let locDelegate = self.delegate {
locDelegate.sendLocationList(self, data: [location])
print(location)
self.dismiss(animated: true, completion: nil)
}
}
func getLocationsFromService() -> [LocationList]{
print("1")
return LocationService.instance.getLocations { (success) in
if success {
print("2")
// DispatchQueue.main.async {
// self.locationListTableView.reloadData()
// }
}
}
}
}
从我之前的线程更新了端点调用,该调用位于另一个swift服务文件中
func getLocations(completion: @escaping CompletionHandler) -> [LocationList] {
let headers: HTTPHeaders = [:]
Alamofire.request(GlobalConstants.APIURL + "/getlocationlist",
method: .get, parameters: nil, encoding: JSONEncoding.default,
headers: headers).responseJSON(completionHandler: { (response) in
if response.result.error == nil {
guard let data = response.data else { return }
do {
let locations = try
JSONDecoder().decode(Locations.self, from: data)
self.locList = locations.data.LocationList
//print(locList)
completion(true)
} catch let error {
print(error)
completion(false)
}
}
else {
completion(false)
debugPrint(response.result.error as Any)
}
})
return locList
}