Reputation: 13
Is it possible to wait some Server Query block to end its operation? My unworking code is below;
+ (BOOL) loginQueryFromServer:(NSDictionary *)parameters{
__block BOOL loginQueryResult = NO;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation = [manager POST:@"http://domainname/login/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Response1: %@",responseObject);
loginQueryResult = YES;
NSLog(@"Response2: %@", loginQueryResult ? @"YES" : @"NO");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
loginQueryResult = NO;
}];
[operation start];
[operation waitUntilFinished];
NSLog(@"Response3: %@", loginQueryResult ? @"YES" : @"NO");
return loginQueryResult;
}
Result: (As you can see; Response3 logs first)
2014-04-09 21:11:17.072 aaa[1010:70b] Response3: NO
2014-04-09 21:11:17.073 aaa[1010:70b] Response1: {
reply = "Login successful!";
}
2014-04-09 21:11:17.081 aaa[1010:70b] Response2: YES
Upvotes: 1
Views: 131
Reputation: 4119
I know this doesn't exactly answer the question - but I would suggest you rewrite your loginQueryFromServer: method to accept a completion block itself so that it is asynchronous (I think this is ultimately what you are trying to do):
+ (void) loginQueryFromServer:(NSDictionary *)parameters completion:(void(^)(BOOL response, NSError *error))completionBlock {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation = [manager POST:@"http://domainname/login/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
completionBlock(YES, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completionBlock(NO, error);
}];
[operation start];
}
Use it like this:
[YourClass loginQueryFromServer:someDictionary completion:^(BOOL response, NSError *error) {
// do something with the response and the error if it exists
}];
Upvotes: 2
Reputation: 100632
You're using the third-party AFNetworking
library. So the question is: did the developers of that want you to be able to do something when an operation is finished?
The answer is yes:
The built-in completionBlock provided by NSOperation allows for custom behavior to be executed after the request finishes.
The class you're using is a subclass of NSOperation
. So assign a block to its completionBlock
property.
Upvotes: 1