Making a request to a web service for logging purposes in Objective-C
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?
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.
精彩评论