Question

i have a request which returns information from a php web service. I'm having trouble adding this to a array which can be used in my UICollectionView. It seems like whatever i do i cant return the data. I think it is because i'm returning the array before i've added any objects. I've tried placing the NSLog several places, but without luck. What am i doing wrong?

When i place this NSLog(@"%d", imagesArray.count); beyond the request it returns 0.

ViewDidAppear:

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

    [self getImages];


}

getImages method:

-(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);



}
Was it helpful?

Solution

AFNetworking is Asynchronous, you have to place the log inside the success block. Otherwise the array will always be empty.

One good solution would be to pass a block to your getImages function like that

-(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.
}];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top