【问题标题】:Swift - Cancel a SynchronousRequest?Swift - 取消同步请求?
【发布时间】:2015-10-15 12:21:05
【问题描述】:

我没有使用 iOS 和 Swift 的经验,但我得到了一个项目,它利用 NSURLConnection.sendSynchronousRequest 向 Web 服务发送 JSON 请求。我知道同步请求是一个阻塞请求,但无论如何我可以取消所述请求吗?

例如用户按下按钮并取消请求?

【问题讨论】:

标签: ios swift http request synchronous


【解决方案1】:

您可以将您的请求包装到 NSOperations 中,并将您的操作添加到 NSOperationsQueue 中。

在 NSOperations 上,您可以随时调用取消。

nsoperations 和 queues 的更多信息: http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues

【讨论】:

  • 使用 NSOperation 运气好吗?
【解决方案2】:

只需使用 cancel() 快速函数:

Apple Documentation - NSURLConnection.cancel()

Cancels an asynchronous load of a request.

Declaration
 SWIFT
     func cancel()
 OBJECTIVE-C
     - (void)cancel

Discussion
 After this method is called, the connection makes no further delegate method calls. If you want to reattempt the connection, you should create a new connection object.

Availability
 Available in OS X v10.2 and later.

【讨论】:

  • 我希望取消 SynchronousRequest 而不是 aSynchronousRequest。
  • @jlngdt 我想你误解了第一个没有completionHandler,回调和第二个的概念,但是像大多数网络API一样,NSURLSession API是高度异步的。请阅读更多相关信息developer.apple.com/library/ios/documentation/Foundation/…:
  • @VictorSigler,我知道它是什么,只是看错了。我知道我的回答不正确。不需要阅读 NSURLSession 文档,我知道
猜你喜欢
  • 2015-11-21
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-23
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
相关资源
最近更新 更多