2015-10-15 43 views
1

我對iOS和Swift沒有經驗,但已經有一個項目利用NSURLConnection.sendSynchronousRequest向Web服務發送JSON請求。我知道同步請求是阻塞的,但無論如何,我可以取消所述請求嗎?Swift - 取消SynchronousRequest?

例如,用戶按下按鈕並取消請求?

+0

我強烈建議你閱讀這篇文章的http:/ /stackoverflow.com/questions/31557688/synchronous-url-request-on-swift-2,肯定你應該嘗試不使用同步請求,儘量避免它。 –

回答

-1

只使用取消()迅速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. 
+0

我正在取消一個SynchronousRequest而不是一個aSynchronousRequest。 – Snappiestjack

+0

'dataTaskWithRequest'是異步的,那麼你的代碼就沒有意義了,因爲我可以在請求後面看到代碼行'NSURLSession.sharedSession()。invalidateAndCancel()'。 –

+0

@jlngdt我認爲你誤解了第一個沒有完成處理程序,回調和它的第二個概念的概念,但是像大多數網絡API一樣,NSURLSession API是非常異步的。請閱讀更多關於它的信息https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/#//apple_ref/occ/instm/NSURLSession/dataTaskWithRequest:completionHandler: –

相關問題