-(void)getDataFromServer: (NSMutableDictionary *)dict
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/doSomething",MainURL ]];
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:nil parameters:dict];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
_myArray = JSON;
[_myTableView reloadData]; //Or do some other stuff that are related to the current `ViewController`
}
failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
{
NSLog(@"request: %@",request);
NSLog(@"Failed: %@",[error localizedDescription]);
}];
[httpClient enqueueHTTPRequestOperation:operation];
}
我在其中一个应用程序的7个不同的地方使用上面的代码。确切的代码块在我的ViewControllers
中有7个重复。我通常用来做的是把我想用在NSObject类中的方法分配并在需要时使用它,但是因为上面是异步并且使用块,所以我不能只返回JSON到ViewController
谁打电话给谁它和必须复制&粘贴在每一个ViewController
上面的方法,我需要进去。将块传递给AFNetworking方法?
我的目标是在只有一个地方上面我的应用程序,并且仍然能够从不同ViewControllers
把它在我的应用程序,获取我需要的数据。 我想避免使用NSNotification
或KVO
等观察者,并寻找更优雅的解决方案。 经过一番阅读后,我注意到可能会传递块。这是否是上述可能的解决方案?代码示例将不胜感激。
除了下面的Gabriele的回答,您可能希望避免为每个请求启动一个新的AFHTTPClient。 –
我正在为此编辑我的答案。谢谢你的提示。 –