Will [NSData dataWithContentsOfURL:url] either return the full amount of bytes on success, or nil if something goes wrong?
Is there a chance, that it would return maybe only half of the bytes of the content… perhaps if their internet connection fails halfway through?
If there is a chance that it would return only partial data, is there some other function I could use that would be more reliable and I would be able to know definitely whether they got the full amount of data or not?
I’m not sure about the implementation of -dataWithContentsOfURL: but using a sychronous method like this is not really recommended anyway.
Something based on NSURLConnection is your best bet, but you need to be aware of a few things. Most people don’t realize that if the server disconnects while an NSURLConnection is receiving data, it will not cause the download to fail with an error. The
-connectionDidFinishLoading:delegate method will be called as normal. Many people get this wrong.If you want to be sure you have all the data, you need to handle the
-connection:didReceiveResponse:delegate method and save the value of[response expectedContentLength]. Then in-connectionDidFinishLoading:you can make sure you received the same number of bytes as expected, and generate an error if not.There are many free libraries out there based on
NSURLConnectionlike AFNetworking. However you need to beware of bad code. I’ve just checked the source toAFNetworkingand it appears they also do not check for the case where the server sends back less data than theContent-Lengthheader specifies. Also note that the popular ASIHTTPRequest is no longer being actively developed and has received some criticism over its implementation.I’ll leave it up to others to suggest other alternative libraries, but
NSURLConnectionis the right direction.