多个web服务调用相同的viewController iphone

我想要帮助在同一个视图控制器上进行多个Web服务调用。 有没有办法我可以做到这一点。

谢谢

有几种方法来解决这个问题,每个取决于你的情况。 首先会使用多个副本+ (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error NSString的+ (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error方法。 所以,如果你想获得一些URL的内容,你可以使用下面的代码

 NSURL* url = [NSURL urlWithString:@"http://www.someUrl.com/some/path"]; NSString* urlContents = [NSString stringWithContentsOfURL:url encoding:NSUTF8Encoding error:nil]; NSURL* anotherUrl = [NSURL urlWithString:@"http://www.anotherUrl.com/some/path"]; NSString* anotherUrlContents = [NSString stringWithContentsOfURL:anotherUrl encoding:NSUTF8Encoding error:nil]; 

这种方法的问题是,它会阻止你打电话的任何线程。 所以你可以在一个线程中调用它或使用其他方法之一。

第二种方法是使用NSURLConnection。 这使用委托来以事件驱动的方式处理过程。 这里有一个很好的总结。 但是,您还需要区分委托方法中的请求。 例如

 -(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response { if(connection == connection1) { //Do something with connection 1 } else if(connection == connection2) { //Do something with connection 2 } } 

第三种方法是使用某种包装类来处理更高级别的http请求。 我个人喜欢ASIHTTPRequest 。 它可以处理请求同步,使用委托asynchronous,asynchronous使用块。

 - (IBAction)grabURLInBackground:(id)sender { NSURL *url1 = [NSURL URLWithString:@"http://example.com/path/1"]; ASIHTTPRequest *request1 = [ASIHTTPRequest requestWithURL:url1]; request1.delegate = self; request1.didFinishSelector = @selector(request1DidFinish); [request1 startAsynchronous]; NSURL *url2 = [NSURL URLWithString:@"http://example.com/path/2"]; ASIHTTPRequest *request2 = [ASIHTTPRequest requestWithURL:url2]; request2.delegate = self; request2.didFinishSelector = @selector(request2DidFinish); [reques2 startAsynchronous]; } - (void)request1DidFinish:(ASIHTTPRequest *)request { NSString *responseString = [request responseString]; } - (void)request2DidFinish:(ASIHTTPRequest *)request { NSString *responseString = [request responseString]; } 

本示例显示如何使用块作为委托方法的callbackintsead执行asynchronous请求。 请注意,这只能在iOS 4.0及更高版本中使用,因为它使用了块。 但是ASIHTTPRequest通常可以在iOS 3.0及更高版本上使用,无需使用块。

 - (IBAction)grabURLInBackground:(id)sender { NSURL *url = [NSURL URLWithString:@"http://example.com/path/1"]; __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setCompletionBlock:^{ NSString *responseString = [request responseString]; }]; [request startAsynchronous]; NSURL *url2 = [NSURL URLWithString:@"http://example.com/path/2"]; __block ASIHTTPRequest *request2 = [ASIHTTPRequest requestWithURL:url]; [request2 setCompletionBlock:^{ NSString *responseString = [request2 responseString]; }]; [request2 startAsynchronous]; }