2016-07-29 59 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 
}