i have searched a lot of examples and tutorials on how to run AFNetworking 2.0 synchronously and found only solutions for AFNetworking 1.0. What i have found: Can AFNetworking return data synchronously (inside a block)?
My example:
- (User *)getUserWithUsername: (NSString *) username andPassword: (NSString *) password {
NSDictionary *params = @{@"email": username, @"password": password};
[[DCAPIClient sharedClient] POST:@"login" parameters:params success:^(NSURLSessionDataTask * __unused task, id JSONResult) {
NSLog(@"JSON %@", JSONResult);
BOOL errorCode = [JSONResult objectForKey:@"error"];
if (!errorCode) {
self.username = [JSONResult objectForKey:@"name"];
// Fill the attributes
// self.email = .. a
} else {
// error with login show alert
}
} failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
NSLog(@"error %@", error);
}];
// this does not work
//[[[DCAPIClient sharedClient] operationQueue] waitUntilAllOperationsAreFinished];
if (self.username == nil) {
return nil;
}
return self;
}
But this does not work, because if (self.username == nil)
is called first.
How can i get AFNetworking 2.0 lib run synchronously that i can return response?
DCAPIClient : AFHTTPSessionManager
+ (instancetype)sharedClient {
static DCAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[DCAPIClient alloc] initWithBaseURL:[NSURL URLWithString:DCAPIBaseURLString]];
_sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
});
return _sharedClient;
}