2013-08-16 22 views
0

我正在实现一个HTTP请求使用Objective-C使用AFJSONRequestOperation为一个移动应用程序,我不知道如何实现一个循环,直到条件满足(即JSON中的profiling_status键值为1)。按下按钮时运行该请求。在后台服务器做一些计算需要一段时间。在服务器完成之前,profiling_status值为2.当它完成时,值为1.因此,我希望保持循环,直到值更改为1,然后显示JSON。Objective-C留在一个JSONRequest循环,直到JSON返回一个特定的值

在成功块中返回JSON会给出一个指针错误。并且在方法结尾处返回JSON将返回nil。

我有这样的代码:

- (IBAction)getProfileInfo:(id)sender 
{ 

    profiling_status = 2; 
    NSDictionary *JSON; 

    while (profiling_status == 2){ 
     JSON = [self getJSON]; 
     profiling_status = [JSON objectForKey:@"profiling_status"]; 
    } 

    NSLog(@"JSON: %@", JSON); 

    } 

    - (NSDictionary*)getJSON 
    { 
     __block NSDictionary* JSONResult = nil; 


     MyAPIClient *client = [MyAPIClient sharedClient]; 

     NSString *path = [NSString stringWithFormat:@"/profile?json"]; 
     NSURLRequest *request = [client requestWithMethod:@"GET" path:path parameters:nil]; 

     AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 

      JSONResult = JSON; 
      //can’t do this ---- return JSONResult; 

     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
     NSLog(@"%@", [error userInfo]); 
     }]; 

     [operation start]; 

     return JSONResult; //will return nil 

    } 

任何帮助吗?

谢谢。

回答

1

你不能使用while循环来做这件事(而且不应该,因为它只是通过产生连接来杀死应用程序)。相反,您需要使用块构造您的方法,以便运行请求的块检查结果并递归调用检查方法(最好在短暂延迟之后)或调用完成块。

另外考虑保持迭代次数或所花费的时间,以便中止处理。