tableView data source empty in viewDidLoad() - Swift

前端 未结 3 1138
北恋
北恋 2021-01-14 23:31

Below is my ViewController code. The println in GetRequest prints the correct data that it receives from the HTTP GET request. At this point, tableData has 10 key-value pair

相关标签:
3条回答
  • 2021-01-14 23:55

    Rearrange the orders of the method calls:

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        var apiInfo = GetWaitTimes()
        GetRequest(apiInfo.BorderCrossingApi+"?AccessCode="+apiInfo.AccessCode)
        tableView.reloadData()
    }
    

    Explanation: you set the delegate and dataSource before you GetRequest() so the dataSource won't be nil.

    0 讨论(0)
  • 2021-01-14 23:59

    The problem is that GetRequest runs asynchronously. So you have to reloadData inside the completionHandler of dataTaskWithURL:

    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
    
        // do all of your existing stuff here
    
        dispatch_async(dispatch_get_main_queue()) {
            self.tableData = LatestWaitTimes
            self.tableView.reloadData()
        }
    })
    task.resume()
    

    You can remove the reloadData from within viewDidLoad.

    0 讨论(0)
  • 2021-01-14 23:59

    Try this it may help you

    you can add a callback (for reload tablview) in GetRequest function and run the callback after parser json in completionHandler

    Maybe When you set the delegate with tableview, tableData still be nil (waitting for http response)

    this is my code .you can refer to

    demand.loadDataFromServer(self.view, done: { () -> Void in
         self.demands = demand.getDemandDataList()
         dispatch_async(dispatch_get_main_queue(), { () -> Void in
             self.tableView.reloadData()
         })
    })
    
    
    func loadDataFromServer(view:UIView,done:(() -> Void)!){
        var request:HttpRequest = HttpRequest(view:view)
        request.GET(getDemandListURL, parameters: nil, success: { (dict) -> Void in
            self.demandLists = dict["data"] as NSMutableArray
            done()
            }, failed: { (dict) -> Void in
    
            }) { (error) -> Void in
        }
    }
    
    0 讨论(0)
提交回复
热议问题