Posts Tagged ‘communication’
If you’re an iPhone, iPod Touch or iPad developer you will sooner or later have to communicate with a webserver. Maybe you want to download some kinda data or just submit highscore to a database.
In case your project heavily depends on device <—> webservice communication, I can highly recommend taking a look at ASIHTTPRequest.
However, the following example will show us a very easy way of communicating with a webserver.
In order to get things done properly, we need to use NSURLConnection. The bad news is, that NSURLConnection seems to create memory leaks every time we use it and if you already did some research, you probably found tons of threads dealing with this issue. If I’m not mistaken, Apple has been aware of this problem since 2008! Unfortunately, they haven’t fixed it yet.
So, it’s time for some mojo
First, we need to create the request and have it call our server. We can do that in a custom method or wherever we want to:
- (void)callOurWebserver {
NSString* dataString = @"http://www.ourserver.com/ourScript.php"; //change this to something meaningful
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:dataString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
//the following two lines of code are our mojo
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (connection) { //do something or just NSLog(@"yay, we got a connection");}
}
Now, we successfully allocated our NSURLConnection object and made it contact the URL we put inside our dataString.
Final step is to actually make use of the data and most importantly RELEASE the NSURLConnection object.
We do this inside the following method:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//do stuff with the data object if you like
[connection release];
connection = nil;
NSLog(@"Request successful");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
connection = nil;
NSLog(@"Request failed!");
}
That’s it! No more leaks.
