【问题标题】:JSON Webservice calling repeatedly iphone sdkJSON Webservice重复调用iphone sdk
【发布时间】:2011-09-22 12:37:11
【问题描述】:

我有两个 web 服务 (JSON),一个在 ViewDidLoad 处调用,它返回一个值数组并加载到 Array1 中。我需要通过解析 Array1 的每个值来调用另一个 web 服务。我尝试过这样的事情:

for (pointer=0; pointer<=[Array1 count]; pointer++) {
    NSString *test = [Array1 objectAtIndex:pointer];
    NSString *urlString2 = [NSString stringWithFormat:@"http://service=%@",test];
    NSURLRequest *request2 = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString2]];
    connection2 = [[NSURLConnection alloc] initWithRequest:request2 delegate:self]; 
}

如何调用此函数将输出加载到数组中? 非常感谢您的帮助.. 谢谢

【问题讨论】:

    标签: iphone json web-services for-loop nsmutablearray


    【解决方案1】:

    您还没有展示如何执行您在循环中创建的 NSURLRequests 请求。如果您尝试同步调用它们,那么您可以执行以下操作:

    NSMutableArray *result = [[NSMutableArray alloc] init];
    for (pointer=0; pointer<=[Array1 count]; pointer++) {
        NSString *test = [Array1 objectAtIndex:pointer];
        NSString *urlString2 = [NSString stringWithFormat:@"http://service=%@",test];
        NSURLRequest *request2 = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString2]];
        NSURLResponse *response = nil;
        NSError *error = nil;
        NSData *currentResult = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&response error:&error];
        [result addObject:currentResult];
    }
    return result;
    

    如果您尝试使用 self 作为委托来异步调用请求,那么您将不得不在这里做一些更棘手的工作,因为您对所有请求的所有响应都将进入同一个委托。这是可能的,但在这种情况下,您可能希望定义一个专用对象作为每个单独请求的委托...

    【讨论】:

    • 嗨蒂姆,感谢您的回复。我正在使用委托方法 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { }, - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {}, - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {} 和 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { } 我尝试使用您的代码,但它返回了不同的输出,例如“7b224765 74446561 6c446574 61696c73 52657375”,那么我怎样才能得到我的数据呢?有什么想法吗?
    • 我添加的代码示例将结果作为 NSData 对象返回。为了使它有用,您需要为返回的数据适当地“解码”它。例如,如果数据是 UTF-8 编码的 JSON 字符串,您将执行 NSString *jsonData = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2012-09-29
    • 2017-08-22
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多