Reputation: 185
I'm calling a Swift method from an Objective C class. It is supposed to run the Swift code, wait for it to complete and only then continue to the next line in the Objective C class. Right now it's running a few lines of the Swift code, and then going to the line AFTER the completion handler, before the completion handler is ever hit. When the Swift code has finished running, it hits the completion handler as it should, but how do I stop it jumping ahead of the completion handler beforehand?
Swift Class (TwitterRequest.swift)
@objc func startRequest(withUsername username: String, completion: @escaping (Bool) -> Void) {
requestToken() { token in
self.getUserTimeline(bearerToken: token, username: username) { timeline in
// Get user twitter feed
completion(true)
}
}
}
Calling above method from Objective C class
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"showTwitterTimeline"]) {
[[TwitterRequest new] startRequestWithUsername:_usernameTextField.text completion:^(BOOL completion) {
// Completion handler for startRequest.
}];
// Code is jumping here before above completion handler is hit. Why?
}
}
func getUserTimeline(bearerToken: BearerToken, username: String, completion: (UserTimeline) -> Void) {
var test = UserTimeline()
completion(test)
}
Upvotes: 0
Views: 207
Reputation: 41
This is the intended behaviour of completion handlers. Your code continues to execute, but when your request finishes its job, the completion handler for this request is called.
Upvotes: 1