I’m using the following code to connect to a web service and get the response. The code works just fine, I’m using the connection delegate connectionDidFinishLoading to parse the result and take some action.
- (IBAction)signInTouchUpInside:(id)sender {
if (r == NO) {
if ([Utility internet]) {
[self.connection cancel];
self.json = [[NSMutableData alloc] init];
NSString* urlString = [NSString stringWithFormat:@"http://www.domain.com/signin?email=%@&password=%@", self.email.text, self.password.text];
NSURL* url = [NSURL URLWithString:urlString];
NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"GET"];
[urlRequest addValue:@"iphonekey" forHTTPHeaderField:@"key"];
self.connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
[self.connection start];
} else {
}
}
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
NSString* jsonString = [[NSString alloc] initWithData:self.json encoding:NSUTF8StringEncoding];
SBJsonParser* parser = [[SBJsonParser alloc] init];
NSDictionary* holder = [parser objectWithString:jsonString error:nil];
if ([[holder valueForKey: @"result"] boolValue]) {
} else {
}
}
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
[self.json setLength:0];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
[self.json appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error {
NSLog(@"error %@", error);
}
Now I’m facing a few problems and I’m not sure what to do. I will need to do the same connection in several view controllers, so instead of repeating myself all the time I think it’s better to create a class to manage the connection. Besides, the action I take in the connectionDidFinishLoading is different for each web service, so I need to configure a callback for each call. How can I do that?
ps: I don’t have concurrent calls.
Yes, you should create a class to manage the connections. For each connection, create an instance of it –
In the view controller –
In the new class, assign the connection –
Then in connectionDidFinishLoading –
This way, you can do operations targeted for that connection.