0

I have an iOS app with a table view and I want to get the table items from an extern php file which gives me a json string. Now I try to store the data from the php file to the data variable. Here is my code:

- (NSMutableArray *)data {

    if(!_data){
        _data = [[NSMutableArray alloc] init];

        NSURLSession *session = [NSURLSession sharedSession];
        NSString *url = [NSString stringWithFormat:@"http://www.example.net/something/bla.php"];
        NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){

            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSString *errorCode = [json valueForKey:@"error"];

            if([errorCode isEqualToString:@"e0"]){

                NSArray *persons = [json objectForKey:@"persons"];

                for (int i = 0; i < [persons count]; i++) {
                    NSString *person = [[persons objectAtIndex:i] objectForKey:@"name"];
                    [_data addObject:person];
                }

            }
            NSLog(@"3.: %@", _data); // Full

        }];

        [dataTask resume];

        NSLog(@"2.: %@", _data); // Empty

    }

    NSLog(@"1.: %@", _data); // Empty

    return _data;

}

How can I return the result of the url session now? As you can see on my comments, the _data array is only filled on NSLog 3 and it is empty on 1 and 2. Would be nice if someone could tell me what I must change.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nono
  • 1,073
  • 4
  • 23
  • 46
  • the network call is asynchronous, by the time you ask for _data it may be nil as the network call may not be completed. The best way would be impelmenting a completion block. Please refer to this answer:http://stackoverflow.com/questions/20871506/how-to-get-data-to-return-from-nsurlsessiondatatask – Teja Nandamuri Jun 20 '16 at 19:52
  • 1 and 2 are executing before your data is retrieved. The completion block is the only part of your code which executes *after* the data is retrieved. You also seem to be using two separate variables, "_data" and "data". – Brett Donald Jun 20 '16 at 23:03

0 Answers0