多个Web服务在同一viewController iphone上调用

| 我需要在同一视图控制器上进行多个Web服务调用的帮助。有办法吗 谢谢     
已邀请:
        有几种方法可以解决此问题,每种方法都取决于您的情况。第一种是使用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。它可以处理请求同步,使用委托异步和使用块异步。
- (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];
}
本示例向您展示如何使用块作为委托方法的回调对象来执行异步请求。请注意,由于它使用块,因此只能在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];

}
    

要回复问题请先登录注册