开发者

Making a request to a web service for logging purposes in Objective-C

开发者 https://www.devze.com 2023-01-14 21:56 出处:网络
I have a web service with a URL like this: http://webservice.com/?log=1 开发者_Go百科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 ca

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

开发者_Go百科

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号