AFNetworking请求返回nil

时间:2014-04-14 18:08:08

标签: ios objective-c afnetworking

我有一个从php Web服务返回信息的请求。我将此添加到可以在我的UICollectionView中使用的数组时遇到问题。似乎无论我做什么我都无法返回数据。我认为这是因为我在添加任何对象之前返回了数组。我试过把NSLog放在好几个地方,但没有运气。我做错了什么?

当我放置这个NSLog时(@"%d",imagesArray.count);超出请求它返回0.

ViewDidAppear:

-(void)viewDidAppear:(BOOL)animated {
    imagesArray = [[NSMutableArray alloc] init];

    [self getImages];


}

getImages方法:

-(void)getImages {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://URL.COM" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {


    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseObject options:kNilOptions error:nil];

    NSString *theTitle = [[json objectForKey:@"response"] valueForKey:@"title"];
    NSString *theUrl = [[json objectForKey:@"response"] valueForKey:@"imageUrl"];


    [imagesArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:
                            theTitle, @"title",
                            theUrl, @"url",
                            nil]];



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

NSLog(@"%d", imagesArray.count);



}

1 个答案:

答案 0 :(得分:1)

AFNetworking是异步的,您必须将日志放在成功块中。否则,数组将始终为空。

一个好的解决方案是将块传递给你的getImages函数

-(void) getImages:(void (^)(BOOL result))callback {
   // your code here then you call callback(YES or NO) inside your success or failure block.
}

[self getImages:^(BOOL result){
  if(result)
    //we got the images, we can now display them etc.
}];