IOS. Is it possible that [NSData dataWithContentsOfURL: url] will only return a fraction of the content bytes?

Will it [NSData dataWithContentsOfURL:url]

return the full number of bytes on success or nil

if something goes wrong?

Is there any chance it will return maybe only half the bytes of the content ... perhaps if their internet connection fails?

If there is a chance that it will only return partial data, is there some other function I could use that would be more reliable and I could know for sure if they are receiving the full amount of data or not?

+3


source to share


2 answers


I'm not sure about the implementation of -dataWithContentsOfURL: but using an orphan method like this is not recommended anyway.

Something based on NSURLConnection is your best bet, but there are a few things you need to know. What most people don't realize is that if the server goes down when the NSURLConnection receives data, it will not fail with an error. The delegate method -connectionDidFinishLoading:

will be called as usual. Many people are wrong.

If you want to make sure you have all the data, you need to handle the delegate method -connection:didReceiveResponse:

and store the value [response expectedContentLength]

. Then in -connectionDidFinishLoading:

you can make sure you got the same number of bytes as expected and generate an error if not.



There are many free libraries based on NSURLConnection

, for example AFNetworking . However, you need to watch out for bad code. I just checked the source on AFNetworking

and it seems they also don't check for the case where the server is sending less data than the header Content-Length

. Also note that the popular ASIHTTPRequest is no longer under active development and has received some criticism regarding its implementation.

I'll leave it to others to suggest other alternative libraries, but in the NSURLConnection

right direction.

+6


source


If you are "worried" about this, I would recommend using it NSURLConnection

with the appropriate delegates.



An asynchronous approach (i.e. NSURLConnection

) is always better.

+1


source







All Articles