AFNetworking的iOS Block问题

时间:2015-07-03 14:02:41

标签: ios objective-c syntax afnetworking

我正在学习块,我想将它们与AFNetworking一起使用。我在Singletone中制作了方法:

- (void)getAllPlayers:(void (^)(NSArray *playerz, bool succeed))blockPlayers {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"https://api.myjson.com/bins/530re" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {



    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

}

我在viewDidLoad中调用了这个方法:

[[Manager sharedInstance]getAllPlayers:^(NSArray *playerz, bool succeed) {
            if (succeed == YES) {
                self.allClubs = playerz;
                [self.tableView reloadData];
            }
        }];

但没有下载任何内容。

2 个答案:

答案 0 :(得分:1)

哟忘了调用blockPlayers完成处理程序。

- (void)getAllPlayers:(void (^)(NSArray *playerz, bool succeed))blockPlayers {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"https://api.myjson.com/bins/530re" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSarray *returnedPLayerz = [NSArray array];
        //Here treat operation and response Object to extract playerz and assing it to returnedPlayerz
        blockPLayers(returnedPlayerz, YES);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        blockPlayers(nil, NO);
        NSLog(@"Error: %@", error);
    }];

}

答案 1 :(得分:1)

您从响应对象的服务器获取数据。之后你需要解析它并在块中返回:

- (void)getAllPlayers:(void (^)(NSArray *playerz, bool succeed))blockPlayers {
  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  [manager GET:@"https://api.myjson.com/bins/530re" parameters:nil 
  success:^(AFHTTPRequestOperation *operation, id responseObject) {

     NSArray* players = [self getPlayersFromJson:responseObject];
     blockPlayers(players, YES); 

  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     blockPlayers(nil, NO);
  }];

}

所以你需要创建解析器方法getPlayersFromJson