views:

55

answers:

1

Hello friends.

I have a web service with a URL like this: http://webservice.com/?log=1

I would like to make a request to this URL in Objective-C such that the web service can log that fact. I don't care to pass anything on to the web service and nor do I care how it responds to the request.

What is the most effective way to achieve this?

+2  A: 

The simplest way is to use the NSURLConnection sendSynchronousRequest:returningResponse:error: method.

e.g.

NSURLResponse *response;
[NSURLConnection sendSynchronousRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @"http://webservice.com/?log=1"]] returningResponse: &response error: NULL];

The downside to using this method is that it will hang your app while it's performing the URL request. To do this request asynchronously you need to use the connectionWithRequest:delegate: method. This gets a little more complex as you need to provide a delegate (in your case, one that does nothing).

e.g.

    [[NSURLConnection connectionWithRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @"http://webservice.com/?log=1"]] delegate:self] retain];

...

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [connection release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [connection release];
}

See SimpleURLConnections for more examples of using NSURLConnection.

UPDATE: removed optional delagate methods as per David's comment.

Shane Powell
Excellent response Shane. Unfortunately it will need to be asynchronous so I'll just have to deal with a few empty delegate methods. That's fine by me. Thanks again.
David Foster
Turns out NSURLConnection uses an informal protocol, and all methods are optional, so I only needed to include `connection:didFailWithError:` and `connectionDidFinishLoading:`.
David Foster
I kind-of did know it was like that but I couldn't find any documentation on what was optional and what wasn't. Maybe I didn't look hard enough! I'll update my answer. Thanks.
Shane Powell