我正在使用以下代码连接到 Web 服务并获取响应。代码工作得很好,我正在使用连接委托 connectionDidFinishLoading 来解析结果并采取一些措施。
- (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);
}
现在我面临一些问题,我不知道该怎么办。我需要在多个视图控制器中进行相同的连接,所以与其一直重复自己,我认为创建一个类来管理连接会更好。此外,我在connectionDidFinishLoading中采取的动作对于每个Web服务都是不同的,所以我需要为每个调用配置一个回调。我怎样才能做到这一点?
ps:我没有并发通话。