0

我是 iphone 开发的新手,有人可以帮我解决这个问题吗,从一周开始我就面临一个问题,那就是我有多个网址,如下所示

for (int i=0;i<=[listingAffArray];i++)
    NSString *urlStr=[NSString stringWithFormat:@"http://demo.holidayjuggle.net:7777/services/inventoryservice/%@/%@/stores/search?location=12.971598700000000000,77.594562699999980000,50",appDelegate.buyingAff,[appDelegate.listingAffArray objectAtIndex:i]];
}

在这我得到了所有 url 的响应,但是在 didfinishloading 中无法找到哪些 url 响应数据

NSURL *url=[NSURL URLWithString:urlStr];

NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url];

[req setHTTPMethod:@"GET"];

[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

connection=[NSURLConnection connectionWithRequest:req delegate:self];
if(connection){
    NSLog(@"connection is successfull "); 
}
else{
    NSLog(@"connection failed");
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{ 
    responseData=[[NSMutableData alloc]init]; 
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data]; 
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];

}

在 responsedata 中只有最后一个 url 数据我放了断点并观察到每个 url 在 didfinishloading 中调用,当第二个 url 调用时,它正在使用 secondurl 调用更新,就像在 responsedata 中最后一个 url 数据一样。如何存储每个响应数据分别

提前致谢

西瓦库马里

4

3 回答 3

0

尝试以异步方式使用 url 调用 Web 服务。即。点击第一个网址,当您收到第一个网址的结果时,点击第二个网址请求。之后,当您收到第二个 url 响应时,点击了第三个 url 请求。

这些所有请求都应该在后台线程或新线程中运行,以免影响主线程。

还采用枚举数据类型,例如

enum {
  requestOne=0,
  requestTwo,
  requestThree,
  requestFour
}currentRequest;

当你开始点击 currentRequestData 中的第一个 url 时,分配 requestOne 并作为响应检查这个 enumDataType。收到响应后,使用第二个枚举类型点击第二个 url

于 2013-01-05T13:40:53.397 回答
0

Yes it happen because all NSURLConnection share same delegate same object which is "self"

If u want to load multiple URL than you should have multiple space to store that data.

So one object of responseData is not sufficient.

There can be many way let me suggest one which I use.

  • Declare a NSMutableDictionary object
  • Store NSURLConnection object as key and NSMutableData object as value so if u have 3 URL you have 3 entery in NSMutableDictionary.
  • In every Delegate method of NSURLConnection append data only to corresponding NSMutableData object.

Tell me if u need more help....

于 2013-01-05T13:22:10.063 回答
0

在您的类中创建一个数组并将每个数组存储strResponse在您的数组中(使用addObject)。

另外,这没有意义:

for (int i=0;i<=[listingAffArray];i++)
    NSString *urlStr=[NSString stringWithFormat:@"http://demo.holidayjuggle.net:7777/services/inventoryservice/%@/%@/stores/search?location=12.971598700000000000,77.594562699999980000,50",appDelegate.buyingAff,[appDelegate.listingAffArray objectAtIndex:i]];
}

[listingAffArray]部分应该给您一个编译器错误,即使这确实有效,您每次循环时都会覆盖相同的变量。

于 2013-01-05T13:17:34.047 回答