iPhone: Asynchronous HEAD method - iphone

I am very new here. I am trying to update the content of a file from a webserver only if it has changed. I found an example of code here using a synchronous connection in NSURLconnection.
Is it possible to do asynchronously?

NSURLConnection has the method sendSynchronousRequest:returningResponse:error: for synchronous connection. It also has a method sendAsynchronousRequest:queue:completionHandler: for async connection. You need to create a block for completionHandler parameter, which handles the response from web server.
Also:
initWithRequest:delegate:
initWithRequest:delegate:startImmediately:
start
are available for async use. You gonna need to implement some methods of NSURLConnectionDelegate to handle the async response.
Please refer to NSURLConnection Class Reference and NSURLConnectionDelegate Protocol Reference.

i think ASIHTTPRequest is the easiest solution:
set the request Method for your ASIHTTPRequest
// HTTP method to use (eg: GET / POST / PUT / DELETE / HEAD etc). Defaults to GET
NSString *requestMethod;
or you can use a download cache
ASIHTTPRequest can automatically store downloaded data in a cache for use later. This can be helpful in many situations...

Related

How to wait for a certain status of a NSURLConnection

Sorry to bother with yet another NSURLConnection question, adding to the over one thousand already here.
The scenario is as follows. In an iPhone app using dynamically loaded augmented reality features, the user is prompted to download new AR models as these are made available. The models can be several MB large, so the user should be given an indication of the total size of all models to be downloaded before deciding to do so.
To find out how large each file is I want to use an asynchronous NSURLConnection but then to stop the download once I have got the response ([NSURLResponse expectedContentLength]). I can do this in the delegate's connection:didReceiveResponse: method.
My question is, how can I wait until this condition arises? How can I setup the NSURLConnection, let it start asynchronously and then wait until the connection:didReceiveResponse: method is called? I have tried using a NSCondition, letting this wait after setting up the NSURLConnection and in the connection:didReceiveResponse: method signalling the condition. But all this did was to freeze the main thread. Any ideas?
Maybe you could send a HEAD request instead of GET. This may depend on your server set up, but that should get you just the headers, including Content-Length. You ought to be able to use a NSMutableURLRequest so you can change the request method, and then read expectedContentLength on the response as usual.

How can I chain asynchronous NSURLConnections?

What would be the most appropriate way to chain asynchronous NSURLConnections? For example, I need to register a user with a web service. The workflow would be as follows:
Get Register Token => Use token to Register => Get Login Token => Use token to Login.
I know how to create an asynchronous NSURLConnection, but I'm unsure how to make sure the previous connection has finished before moving on. I know I can achieve this using NSURLConnection sendSynchronousRequest but I don't like my main thread being blocked while these chained requests happen.
We did EXACTLYA this when we built our first version of SignMeOut for iPhone. We created a subclass of NSUrlconnection and gave it an identifying tag do in the connectionDidFinish you would be able to use a simple switch/case with an enum. Works great - you can see the whole flow and example and code in our blog
http://www.isignmeout.com/multiple-nsurlconnections-viewcontroller/
UPDATE
I've modified the NSURLConnection subclass into a much simpler Category. Most of the usage is the same but cleaner using the same class
https://github.com/Shein/Categories
You can look at connectionDidFinishLoading to start another asynchronous connection. For the conditions as to which connection ended, you can keep references to the connections in case other connections are also expected to finish(probably not needed in your case). Make your class follow the NSURLConnectionDelegate and fire the appropriate connections in the connectionDidFinishLoading delegate method. You can also use the connectionDidReceiveData: method to check for credentials, etc received from the service. Go through the documentation too.
You have different options:
create a queue using a mutable array or dictionary
create an NSOperationQueue kind of easy if you use it in combination
with the new only ios5 API for NSUrlConnection
third parties lib such as AFNetworking
Block GCD grouping them (hard for NSRunLoop reasons, pay attention in wich thread the connection is running in)

NSData / Retrieving content from a page

I have a page that displays one string on a blank page. I need to retrieve that string. How would I do it if I wanted to do it both, synchronously and asynchronously? (I would appreciate if someone gave me the method names for both synch and asynch).
Thank you,
You can use NSString's stringWithContentsOfURL:encoding:error: method to get the HTML page synchronously and later parse it using NSXMLParser.
Since stringWithContentsOfURL:encoding:error: is a blocking call, you should put it in a method and invoke the method using performSelectorInBackground:withObject:. This will retrieve the HTML page in the background.
Once you have the string, create an instance of NSXMLParser and get the string. This one is asynchronous process.
Few examples on how to use NSXMLParser - Make NSXMLParser your friend and BNR - Parsing XML in Cocoa.
Have a look at the NSURLConnection reference. The methods you want are there. Also, read the URL Loading guide, it has some code examples for both synchronous and asynchronous loading.
The body data of the repsonse will be the string you want. You'll need to be a bit careful about which encoding was used by the web site. If not specified in the response at all, it will be ISO-8859-1, otherwise it will probably be specified in the Content-Type header of the response. You then need to convert the data to an NSString with initWithData:encoding:
NB if you are not on the main thread, you can use NSStering's stringWithContentsOfURL:usedEncoding:error:. You shouldn't use this on the main thread because it is a synchronous method.

Thread Vs Async call

I wanted to know the best between Spawning a Thread or making a async call using NSURLConnection class.
See the documentation.
An NSURLConnection object provides
support to perform the loading of a
URL request. The interface for
NSURLConnection is sparse, providing
only the controls to start and cancel
asynchronous loads of a URL request.
i.e. NSURLConnection only supports asynchronous loading of content. Even the sendSynchronousRequest:returningResponse:error: method is really just a wrapper around async loading that blocks until done.
That class reference has links to both the programming guide and numerous examples.

NSURLConnection and keep-alive

I have a small bug in my client app that uses NSURLConnection. I have tracked it down to an unexpected connection keep-alive that seems to confuse the web server (probably a bug on the server side). The workaround would be to force-close all outstanding connections at a certain point. Can I do this somehow with NSURLConnection, i.e. something like
[NSURLConnection closeAllIdleConnections];
ASIHTTPRequest has an expirePersistentConnections method. It may do what you're looking for.
It's not a drop-in replacement for NSURLConnection, but it's not too hard to port code from NSURLConnection to ASIHTTPRequest.
I think you might want to look at the following method defined for NSURLConnections. This assumes that you made the call asynchronously. If it isn't an async call, then it probably should be.
cancel Cancels an asynchronous load of
a request.
(void)cancel
Discussion Once this method is called,
the receiver’s delegate will no longer
receive any messages for this
NSURLConnection.
Hope this helps. Andrew.