异步获取JSON数据

时间:2011-08-12 21:40:04

标签: iphone json asynchronous

我想异步获取JSON数据。数据的设置方式是一个请求只能带来8条记录。我需要重复发送请求,直到响应变空或返回少于8条记录。

目前,我在myviewcontroller.m类中有这些方法:

(void)myCallback:(id)sender {

    MyDataRequest *objMyDataRequest = [[[MyDataRequest alloc] init] autorelease];
    objMyDataRequest.myRequiredVariableToGetAuthTokenDataResponse = classOfMyCallBack.someVariable;

    // Initiate getAuthToken request
    [objWishListRequest initiateGetAuthTokenRequest:self requestSelector:@selector(getAuthTokenDataResponse:)];
}

现在这里是getAuthTokenDataResponse的定义:

(void) getAuthTokenDataResponse:(NSData *)data {

    NSString *stringResponse = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    SBJsonParser *parser=[[SBJsonParser alloc]init];
    NSDictionary *objDictionaryForStringResponse = [parser objectWithString:stringResponse];
    [stringResponse release];
    [parser release];
    MyListRequest *objMyListRequest = [[[MyListRequest alloc] init] autorelease];
    objMyListRequest.myRequiredValueToGetMyDataResponse = [objDictionaryForStringResponse objectForKey:@"Data"]; 

    // Initiate GetMyDataResponse request
    [objMyListRequest initiateGetMyDataRequest:self requestSelector:@selector(getMyDataResponse:)]; 

}


(void) getMyDataResponse:(NSData *)data {

    NSString *stringResponse = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    SBJsonParser *parser=[[SBJsonParser alloc]init];
    NSDictionary *objGetMyDataRootDictionary = [parser objectWithString:stringResponse];
    [stringResponse release];
    [parser release];
    NSDictionary *dataElements=[objGetMyDataRootDictionary objectForKey:@"Data"];
    Wish *objMyData; 

    for (NSDictionary* objGetMyDataRootDictionary in dataElements) {
        objMyData = [[Wish alloc]init];
        //add different elements from dataElements into member variables of object objWish
        [self.myDataArray addObject:objMyData];
        [objMyData release];
    }
    [self.myDataTableView reloadData];
}

此方法位于MyDataRequest类:

(void)initiateGetMyDataRequest:(id)requestDelegate requestSelector:(SEL)requestSelector{

    // Set the delegate and selector
    self.delegate = requestDelegate;
    self.callback = requestSelector;

    NSString* unescapedUrlString = [NSString stringWithFormat:@"http://test.mytesturl.com/core.svc/alldata/My/get/All/?token=%@&search=&page=1",myRequiredtokenparameter];  
    [self request:url];
}

我需要向同一个url发送多个请求(具有不同的参数值,即页码的值)以获取结果。鉴于上述情况,我怎样才能实现呢?调用必须是异步的。

我应该如何在所有这些电话之间进行实际流程?如何异步获取“所有页面”的数据?

1 个答案:

答案 0 :(得分:0)

我认为你正在寻找一个操作队列。我在我的应用中使用ASIHTTPRequests并且它们有效。

如果您想使用此库,请点击以下链接:Show UIActivityIndicatorView when loading NSString from Web