Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active January 31, 2019 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/3eb1bf3f484b3d0b865628503ddeb452 to your computer and use it in GitHub Desktop.
Save robertmryan/3eb1bf3f484b3d0b865628503ddeb452 to your computer and use it in GitHub Desktop.
- (void)verifyCode:(NSString*)code {
NSString *identifier = self.potentialPerson[@"ID"];
NSString *urlString = [[inputModel api] stringByAppendingFormat:@"action=validate&code=%@&inputID=%@",
code, identifier];
[self validateInputFrom:urlString completionHandler:^(NSDictionary *dictionary) {
self.codeResponse = dictionary;
NSLog(@"message %@", dictionary);
// use `dictionary` here, but ...
}];
// ... do not try to use `dictionary` or `codeResponse` here
}
- (NSURLSessionDataTask *)validateInputFrom:(NSString *)url completionHandler:(void (^)(NSDictionary *))completionHandler {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if (completionHandler) {
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(result);
});
}
}];
[task resume];
return task;
}
@robertmryan
Copy link
Author

Also note that verifyCode now is a void return type. You cannot return a value that is set asynchronously later. Remember, you return from validateInputFrom immediately, but the completionHandler block is called later (for a network request, it may be a few seconds later).

@itsXqtard
Copy link

Sorry about that my variable for codeResponse was originally camelcase from the original code. I made modifications so that I can post it on stack. Okay, that makes sense. I can only make changes to the dictionary after it has completed it's task so when verifyCode completes is when codeResponse gets updated. I apologize for any inconvenience, but I do appreciate the help you have provided. Still learning about async calls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment