SWIFT:UIRefreshControl()和tableView.reload()无效

时间:2018-02-03 00:30:38

标签: json iphone swift uitableview uirefreshcontrol

我正在从我使用的预订服务中提取JSON数据。我在ViewController中显示它很好但我似乎无法使UIRefreshControl()工作并使用JSON数据刷新表。

这是我获取JSON数据的代码。

let urlToRequest = "https://api.bookeo.com/v2/availability/slots?secretKey=<secretKey>&type=fixed&apiKey=<apiKey>&startTime=2018-02-03T09:30:00-05:00&endTime=2018-02-03T22:00:00-05:00"
    func dataRequest() {
        let url4 = URL(string: urlToRequest)!
        let session4 = URLSession.shared
        let request = NSMutableURLRequest(url: url4)
        request.httpMethod = "GET"
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
        let paramString = "data=Hello"
        request.httpBody = paramString.data(using: String.Encoding.utf8)
        let task = session4.dataTask(with: request as URLRequest) { (data, response, error) in
            guard let _: Data = data, let _: URLResponse = response, error == nil else {
                print("*****error")
                return
            }
            let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("*****This is the data 4: \(String(describing: dataString))") //JSONSerialization
        }
        task.resume()
        DispatchQueue.main.async{
            self.tableView.reloadData()
        }
    }
    dataRequest()


   if let url = URL(string: urlToRequest) {

        if let data = try? String(contentsOf: url) {
            let json = JSON(parseJSON: data)

            if json["info"]["totalItems"].intValue == 50 {
                parse(json: json)
                return
            }
        }
    }

    showError()
}

以下是解析JSON的方法。

func parse(json: JSON) {
    for result in json["data"].arrayValue {
        let productId = result["productId"].stringValue
        let startTime = result["startTime"].stringValue
        let numSeatsAvailable = result["numSeatsAvailable"].stringValue
        let obj = ["productId": productId, "startTime": startTime, "numSeatsAvailable": numSeatsAvailable]
        petitions.append(obj)

    }
    //tableView.reloadData()
    DispatchQueue.main.async{
        self.tableView.reloadData()
    }

}

这是我的UIRefreshControl()

的代码
class ViewController: UITableViewController {
var petitions = [[String: String]]()
var refresh = UIRefreshControl()


override func viewDidLoad() {
    super.viewDidLoad()


    refresh = UIRefreshControl()
    refresh.tintColor = UIColor.darkGray
    refresh.addTarget(self, action: #selector(ViewController.refreshData), for: UIControlEvents.valueChanged)
    tableView.refreshControl = refresh
    tableView.addSubview(refresh)

然后刷新的功能......

@objc func refreshData() {
    DispatchQueue.main.async{
        self.tableView.reloadData()
    }
    refresh.endRefreshing()
}

请帮我找出我做错了什么。谢谢!

0 个答案:

没有答案