ios - 在返回值之前等待网络调用完成

标签 ios swift network-programming

我正在尝试从网络调用中获取和返回一些 (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 中尝试过类似的东西,结果在运行时导致了无限循环。

最佳答案

如果你想从异步操作中返回值,你需要一个完成处理器。 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
}

关于ios - 在返回值之前等待网络调用完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38665139/

相关文章:

ios - 在创建时向 UITableViewCell 添加偏移量?

ios - Twilio iOS 客户端 - 在后台保持活跃

ios - 按下按钮时显示一天中的时间 ios

swift - 如何从相似名称的变量中获取值

c - 在 C 中查找主机地址范围

ios - 读/写数据 NSCoding iOS - Singelton 与否?

iphone - 如何在 iPhone 上使用 xmlparsing 解析 XML 文件?

ios - 将 UIScrollView 放在 UIPageView 中,滚动不起作用

c++ - Qt、POP3 和 SSL?

mobile - 移动应用程序使用什么网络端口