我正在尝试将数据从json文件加载到表视图单元格中,但问题是它加载了一个空单元格,因为检索的数据尚未完成加载。我假设我必须使呼叫同步,但我不确定如何。请帮忙!
class func getTopAppsDataFromItunesWithSuccess(success: ((iTunesData: NSData) -> Void)) {
//1
loadDataFromURL(NSURL(string: TopAppURL)!, completion:{(data, error) -> Void in
//2
if ((data) != nil) {
if let urlData = data {
//3
success(iTunesData: urlData)
}
}
})
}
class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) {
var session = NSURLSession.sharedSession()
// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if let responseError = error {
println("error")
completion(data: nil, error: responseError)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
var statusError = NSError(domain:"com.raywenderlich", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(data: nil, error: statusError)
} else {
completion(data: data, error: nil)
}
}
})
loadDataTask.resume()
}
这是我提出请求的地方
class func allCats() -> Array<Animal> {
var animalArray = Array<Animal>()
DataManager.getTopAppsDataFromItunesWithSuccess { (iTunesData) -> Void in
...