objective-c - 将 block 传递给 AFNetworking 方法?

标签 objective-c afnetworking objective-c-blocks

-(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 个不同位置使用上述代码。确切的代码块在我的 7 个 ViewControllers 中重复。我通常做的是把我想使用的方法放在一个 NSObject 类中,并在我需要的时候分配和使用它,但是因为上面是异步的并且使用 block 我不能只将 JSON 返回到 调用它的 ViewController 并且必须将上述方法复制并粘贴到我需要它的每个 ViewController 中。

我的目标是在我的应用程序中仅将上述内容放在一个位置,并且仍然能够从我的应用程序周围的不同 ViewControllers 调用它并获取我需要的数据。 我想避免使用诸如 NSNotificationKVO 之类的观察器,并寻找更优雅的解决方案。 经过一番阅读后,我注意到可以传递方 block 。以上是可能的解决方案吗?一个代码示例将不胜感激。

最佳答案

将 API 调用分解为类似的东西

+ (void)getDataFromServerWithParameters:(NSMutableDictionary *)params completion:(void (^)(id JSON))completion failure:(void (^)(NSError * error))failure {
     NSString * path = @"resources/123";
     NSMutableURLRequest *request = [self.httpClient requestWithMethod:@"POST" path:path parameters:params];
     AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        if (completion)
            completion(JSON);
     } failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON) {
        if (failure)
            failure(error);
     }];

     [httpClient enqueueHTTPRequestOperation:operation];
 }

您可以将此方法放在实用程序类中,例如 XYAPI,然后从您的 Controller 中调用它

 [XYAPI getDataFromServer:params completion:^(id JSON){
     // do something, for instance reload the table with a new data source
     _myArray = JSON;
     [_myTableView reloadData];
 } failure:^(NSError * error) {
    // do something
 }];

此外,您不需要在每次请求时都生成一个新的 AFHTTPClient。在 XYAPI 类中配置和使用一个共享的。有点像

+ (AFHTTPClient *)httpClient {
    static AFHTTPClient * client = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://foo.com/api/v1/"]];
        [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    });
    return client;
}

请注意,此实现已在上面的示例中使用。
self 在类方法的上下文中是类本身,因此 self.httpClient 确实在运行时解析为 [XYAPI httpClient]

关于objective-c - 将 block 传递给 AFNetworking 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18549979/

相关文章:

ios - 使用 AFNetworking 上传多个图像或文件,

ios - 在 AFNetworking 中处理 304 响应

objective-c - iOS 中的 Storyboard 关系

ios - 加密plist文件方法

objective-c - NSImage : Change brightness

ios - 如何编写 Objective-C 完成 block

objective-c - 有什么方法可以序列化/反序列化 Objective-C block 吗?

ios - UIProgressView 一直重置为 0.0

ios - 从 AFHTTPSessionManager 获取数据

objective-c - 如何在主队列或线程上分派(dispatch)带有参数的 block