NSURLConnection methods no more available in IOS5

Gianni Costanzi picture Gianni Costanzi · Oct 18, 2011 · Viewed 14.6k times · Source

I was looking at the NSURLConnection class which could be used to establish a sync or async connection to an URL and then retrieve its data... a lot of changes have been made to this class with IOS 5 and I've seen they introduced some formal protocols related to authentication or download, but I don't see, for example, if the connection:didReceiveResponse: message (that was previously sent to the delegate and that it is no more available) is still available in some protocols.. How do you implement an async connection and retrieve, for example, HTTP headers as soon as the Response is received? I'm sure there is a way better than using NSURLConnection along with the connection:didReceiveResponse: message.. methods like stringWithContentsOfURL do always load content synchronously? What do you use to implement async downloads in your apps avoiding deprecated methods and reacting to events such as _http response received_m etc ? Do you launch synchronous downloads in background tasks, if possible?

Answer

user557219 picture user557219 · Oct 26, 2011

NSURLConnectionDelegate has become a formal protocol (it was an informal protocol in previous versions). In this protocol, the following (non-deprecated) methods are declared:

  • connection:didFailWithError:
  • connectionShouldUseCredentialStorage:
  • connection:willSendRequestForAuthenticationChallenge:

Furthermore, there are two subprotocols that conform to NSURLConnectionDelegate:

NSURLConnectionDataDelegate is used for delegates that load data to memory, and declares the following methods, some of which I’m sure you’ll find familiar:

  • connection:willSendRequest:redirectResponse:
  • connection:didReceiveResponse:
  • connection:didReceiveData:
  • connection:needNewBodyStream:
  • connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
  • connection:willCacheResponse:
  • connectionDidFinishLoading:

NSURLConnectionDownloadDelegate is used for delegates that store data directly to a disk file, and declares the following methods:

  • connection:didWriteData:totalBytesWritten:expectedTotalBytes:
  • connectionDidResumeDownloading:totalBytesWritten:expectedTotalBytes:
  • connectionDidFinishDownloading:destinationURL:

As you can see, you can still use your previous delegates, possibly with some minor modifications.

For more information, see the iOS 4.3 to iOS 5.0 API Differences document and NSURLConnection.h in your local Xcode installation. When a new SDK version is released, it’s not uncommon for the documentation inside the header files to be more reliable than the documentation available on the developer library. It takes a while for the latter to be up-to-date.