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.