2016-07-29 55 views
0

我試圖從網絡調用中獲取並返回一些(json)數據,並且我想知道是否有更好的方法來等待網絡數據不僅僅是空循環。等待網絡調用完成後返回一個值

這裏是我的代碼:

func sendAPIRequest(endpoint:String) -> JSON? 
{ 
    var json = JSON("") 
    let request = NSMutableURLRequest(URL: NSURL(string: "https://host.com/".stringByAppendingString(endpoint))!) 
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in 
     guard error == nil && data != nil else {               // check for fundamental networking error 
      print("error=\(error)") 
      return 
     } 
     if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {   // check for http errors 
      print("statusCode should be 200, but is \(httpStatus.statusCode)") 
     } 
     json = JSON(data: data!) 
    } 
    task.resume() 
    while (json == "") { 
     // Wait 
    } 
    return json 
} 

我記得試圖在Objective-C這導致在運行時一個無限循環,類似的東西。

+0

使用回調?當請求完成時,讓它調用這個回調,然後從那裏繼續。 –

回答

3

如果要從異步操作返回值,則需要完成處理程序。 dataTaskWithRequest是一個異步過程。這樣做:

func sendAPIRequest(endpoint:String, complete: (JSON) ->()) 
{ 
    var json = JSON("") 
    let request = NSMutableURLRequest(URL: NSURL(string: "https://host.com/".stringByAppendingString(endpoint))!) 
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in 
     guard error == nil && data != nil else {               // check for fundamental networking error 
      print("error=\(error)") 
      return 
     } 
     if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {   // check for http errors 
      print("statusCode should be 200, but is \(httpStatus.statusCode)") 
json = JSON(data: data!) 
complete(json) 
     } 

    } 
    task.resume() 

} 

然後調用它像這樣:

sendAPIRequest(<your endpoint string>) { theJSON in 
//Use the Json value how u want 
}