Swift 2上的同步URL请求 [英] Synchronous URL request on Swift 2

查看:141
本文介绍了Swift 2上的同步URL请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这里获取此代码,以便在Swift 2上对URL进行同步请求。

I have this code from here to do synchronous request of a URL on Swift 2.

  func send(url: String, f: (String)-> ()) {
    var request = NSURLRequest(URL: NSURL(string: url)!)
    var response: NSURLResponse?
    var error: NSErrorPointer = nil
    var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: error)
    var reply = NSString(data: data, encoding: NSUTF8StringEncoding)
    f(reply)
  }

但函数不推荐使用NSURLConnection.sendSynchronousRequest(request,returningResponse:& response,error:error),我不知道如何在Swift上执行同步请求,因为替代方法是异步的。显然苹果公司不赞成可以同步执行的唯一功能。

but the function NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: error) was deprecated and I don't see how one can do synchronous requests on Swift, cause the alternative is asynchronous. Apparently Apple deprecated the only function that can do it synchronously.

我该怎么做?

推荐答案

弃用背后有一个原因 - 它没有用处。您应该避免同步网络请求作为瘟疫。它有两个主要问题,只有一个优点(它易于使用..但也不是异步?):

There is a reason behind deprecation - there is just no use for it. You should avoid synchronous network requests as a plague. It has two main problems and only one advantage (it is easy to use.. but isn't async as well?):


  • 如果没有从不同的线程调用,请求会阻止你的UI,但是如果你这样做,为什么不立即使用异步处理程序呢?

  • 除了它之外,没有办法取消该请求错误本身

而不是这样,只需使用异步请求:

Instead of this, just use asynchronous request:

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

    // Handle incoming data like you would in synchronous request
    var reply = NSString(data: data, encoding: NSUTF8StringEncoding)
    f(reply)
})

iOS9弃用

因为在iOS9这个方法正在被弃用,我建议你改为使用NSURLSession:

Since in iOS9 this method is being deprecated, I suggest you to use NSURLSession instead:

let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request) { (data, response, error) -> Void in

    // Handle incoming data like you would in synchronous request
    var reply = NSString(data: data, encoding: NSUTF8StringEncoding)
    f(reply)
}

这篇关于Swift 2上的同步URL请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆