我對iOS和Swift沒有經驗,但已經有一個項目利用NSURLConnection.sendSynchronousRequest
向Web服務發送JSON請求。我知道同步請求是阻塞的,但無論如何,我可以取消所述請求嗎?Swift - 取消SynchronousRequest?
例如,用戶按下按鈕並取消請求?
我對iOS和Swift沒有經驗,但已經有一個項目利用NSURLConnection.sendSynchronousRequest
向Web服務發送JSON請求。我知道同步請求是阻塞的,但無論如何,我可以取消所述請求嗎?Swift - 取消SynchronousRequest?
例如,用戶按下按鈕並取消請求?
您可以將您的請求包裝到NSOpertations中,並將您的操作添加到NSOperationsQueue中。
在NSOperations上,您可以隨時致電取消。
nsoperations和隊列的更多信息: http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues
現在看看,謝謝。 – Snappiestjack
任何使用NSOperation的運氣? – dirtydanee
只使用取消()迅速FUNC:
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。 – Snappiestjack
'dataTaskWithRequest'是異步的,那麼你的代碼就沒有意義了,因爲我可以在請求後面看到代碼行'NSURLSession.sharedSession()。invalidateAndCancel()'。 –
@jlngdt我認爲你誤解了第一個沒有完成處理程序,回調和它的第二個概念的概念,但是像大多數網絡API一樣,NSURLSession API是非常異步的。請閱讀更多關於它的信息https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/#//apple_ref/occ/instm/NSURLSession/dataTaskWithRequest:completionHandler: –
我強烈建議你閱讀這篇文章的http:/ /stackoverflow.com/questions/31557688/synchronous-url-request-on-swift-2,肯定你應該嘗試不使用同步請求,儘量避免它。 –