1
我的iOS應用程序出現問題。問題是導致我的代碼的一部分下載一個「頻道列表」(JSON),我需要這個任務結束之前執行下一行。我試着用dispatch_async,但是我沒有一個好的結果,因爲下一行總是在下載任務結束之前執行。在執行下一個代碼行之前等待任務結束
class RemoteAPI {
var remoteUrl = ""
func getData(completionHandler: ((JSON!, NSError!) -> Void)!) -> Void {
//let url: NSURL = NSURL(string: "https://api.cxntv.com/api/v1/videos/?type=canales&ordering=-id")
let url: NSURL = NSURL(string: remoteUrl)!
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
//[mutableRequest addValue:@"x32dsds-223" forHTTPHeaderField:@"X_ROKU_ID"];
println(request.HTTPBody)
//request.addValue("xxx", forHTTPHeaderField: "yyy")
request.addValue("xxx" ,forHTTPHeaderField: "zzz")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
/* All my code for the httppetition ....*/
我所說的getgadata功能:
api.remoteUrl = "example"
api.getData({data, error -> Void in
if (data != nil){
// Fix possible error if no "results" key
if let results = data["results"].array {
self.items = results
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.viewUtils.hideActivityIndicator(self.view)
}
println("Data reloaded")
} else {
println("api.getData failed")
println(error)
}
})
/* next line code for execute....
I need these code lines to wait so that the getdata function ends before it can be executed.
*/
您需要將加載完成後要執行的代碼放入getData函數的完成處理程序中 –