我无法显示从REST API获得的数据。我可以毫无问题地检索数据,但tableview没有显示数据。如何在tableview的tableview单元内获取数据?
class SearchBSViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
lazy var tapRecognizer: UITapGestureRecognizer = {
var recognizer = UITapGestureRecognizer(target:self, action: #selector(dismissKeyBoard))
return recognizer
}()
var searchResults: [Service] = []
let busStop = BusStop(odataMetadata: "", busStopCode: "", services: [])
let queryService = QueryService()
override func viewDidLoad() {
super.viewDidLoad()
alterLayout()
searchBar.delegate = self
}
func alterLayout() {
tableView.tableHeaderView = UIView()
tableView.estimatedSectionHeaderHeight = 50
navigationItem.titleView = searchBar
searchBar.showsScopeBar = false
searchBar.placeholder = "Search for bus stop by bus code"
}
}
extension SearchBSViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: BusCell = tableView.dequeueReusableCell(withIdentifier: "BusCell", for: indexPath) as? BusCell else {
return UITableViewCell()
}
let bus = searchResults[indexPath.row]
cell.busNoLbl.text = bus.serviceNo
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexpath: IndexPath) -> CGFloat {
return 100
}
}
extension SearchBSViewController: UISearchBarDelegate {
@objc func dismissKeyBoard() {
searchBar.resignFirstResponder()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
dismissKeyBoard()
print("Something")
guard let searchText = searchBar.text, !searchText.isEmpty else { return }
UIApplication.shared.isNetworkActivityIndicatorVisible = true
guard let searchNumber: Int = Int(searchText) else { return }
queryService.GetBusStop(BusNo: searchNumber) {
results in
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let results = results {
print(results.services?[1].nextBus?.estimatedArrival ?? 0)
self.searchResults = results.services!
self.tableView.reloadData()
self.tableView.setContentOffset(CGPoint.zero, animated: false)
}
}
}
func position(for bar: UIBarPositioning) -> UIBarPosition {
return .topAttached
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
view.addGestureRecognizer(tapRecognizer)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
view.removeGestureRecognizer(tapRecognizer)
}
}
class BusCell: UITableViewCell {
@IBOutlet weak var busNoLbl: UILabel!
@IBOutlet weak var firstBusLbl: UILabel!
@IBOutlet weak var secBusLbl: UILabel!
@IBOutlet weak var thirdBusLbl: UILabel!
@IBOutlet weak var firstPrg: UIProgressView!
@IBOutlet weak var secPrg: UIProgressView!
@IBOutlet weak var thirdPrg: UIProgressView!
@IBOutlet weak var firstType: UILabel!
@IBOutlet weak var secType: UILabel!
@IBOutlet weak var thirdType: UILabel!
func configure(services: Service) {
busNoLbl.text = services.serviceNo
firstBusLbl.text = services.nextBus?.estimatedArrival
secBusLbl.text = services.nextBus2?.estimatedArrival
thirdBusLbl.text = services.nextBus3?.estimatedArrival
}
}
class QueryService {
typealias QueryResult = (BusStop?) -> ()
var buses: BusStop = BusStop(odataMetadata: "", busStopCode: "", services: [])
let defaultSession = URLSession(configuration: .default)
var dataTask: URLSessionDataTask?
func GetBusStop(BusNo: Int, completionBlock: @escaping QueryResult){
dataTask?.cancel()
var urlComponents = URLComponents(string: "http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2")!
urlComponents.queryItems = [URLQueryItem(name: "BusStopCode", value: String(BusNo))]
guard let url = urlComponents.url else { return}
let urlRequest = Header(url: url) //input the header for authorization
dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
let BusStopData = try
JSONDecoder().decode(BusStop.self, from: data)
DispatchQueue.main.async {
print("Queue")
completionBlock(BusStopData)
}
} catch let jsonError {
print(jsonError)
}
}
dataTask?.resume()
}
}
答案 0 :(得分:3)
第一件事是您需要为表视图设置委托和数据源方法。在您的视图中设置它确实加载了方法
tableView.delegate = self
tableView.datasource = self
第二个是您需要在点击API调用后重新加载表格视图
tableView.reloadData()
答案 1 :(得分:0)
请在delegate
函数中设置表视图的datasoruce
和alterLayout()
,例如
tableView.delegate = self
tableView.datasource = self