1

I'm not experienced with iOS and Swift, but have been given a project which utilizes NSURLConnection.sendSynchronousRequest to send a JSON request to a webservice. I know that the synchronous request is a blocking one, but is there anyway I can cancel said request?

For example user presses a button and cancels the request?

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
  • I strongly recommend you to read this post http://stackoverflow.com/questions/31557688/synchronous-url-request-on-swift-2 , and definitely you should try not use synchronous request , try to avoid it. – Victor Sigler Oct 15 '15 at 14:49

2 Answers2

0

You could wrap your requests into NSOpertations, and add your operations into a NSOperationsQueue.

On NSOperations you can call cancel at any time.

Further information of nsoperations and queues: http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues

dirtydanee
  • 6,081
  • 2
  • 27
  • 43
-2

Just Use the cancel() swift 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.
jlngdt
  • 1,350
  • 9
  • 14
  • I'm looking to cancel an SynchronousRequest not an aSynchronousRequest. –  Oct 15 '15 at 12:32
  • `dataTaskWithRequest` is async, then your code not make sense as I can see with the line of code `NSURLSession.sharedSession().invalidateAndCancel()` just after the request. – Victor Sigler Oct 15 '15 at 14:44
  • @jlngdt I think you misunderstand the concept the first one has no one completionHandler, callback and the second one it has, but like most networking APIs, the NSURLSession API is highly asynchronous. Please read more about it https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/#//apple_ref/occ/instm/NSURLSession/dataTaskWithRequest:completionHandler: – Victor Sigler Oct 15 '15 at 14:51
  • @VictorSigler, i know what it is, just missreading correctly. My reply is not correct I know. Dont need to read NSURLSession doc, i know it – jlngdt Oct 15 '15 at 14:53