I have a UITableViewController, call it TableViewControllerA, that's the delegate of another object, APICallerB, that I've created to communicate with an API. Through an NSURLSessionDataTask, APICallerB is setting one of its properties, which will then be set equal to one of TableViewControllerA's properties.
Here's tableViewControllerA's viewDidLoad
method:
- (void)viewDidLoad {
[super viewDidLoad];
// init instance of APICallerB
APICallerB *acb = [[APICallerB alloc] init];
// Set TableViewControllerA as delegate
tvcA.delegate = self;
[acb makeAPICallWithArgument:self.argument];
self.property1 = acb.property2;
}
My question is: What's the best way to to wait for [acb makeAPICallWithARgument:self.argument]
to complete, so that self.property1 = acb.property2
will work? I'm assuming GCD could be used (`dispatch_sync'?) but, being new to iOS/Objective-C, I'm not sure where to use it. Or would it be better move one or both of those items elsewhere?
Here's the method from APICallerB:
- (void)makeAPICallWithArgument:(NSString *)arg
{
NSString *requestString = [NSString stringWithFormat:@"http://%@:%@@apiurl.com/json/Request?arg=%@", API_USERNAME, API_KEY, arg];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
config.HTTPAdditionalHeaders = @{@"Accept" : @"application/json"};
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *ar = [jsonObject[@"Result"] objectForKey:@"results"];
self.property2 = ar;
}];
[dataTask resume];
}