我正在使用 AFNetworking,并且我读过不鼓励同步响应。但是我需要检查用户是否已经存在于在线数据库中,然后该用户才能进入应用程序的下一阶段。是的,一个典型的注册过程。
我的代码现在返回 NO,因为它是异步的。我需要找到一种方法来检查成功调用并返回YES
或NO
取决于此回调。
谁能指出我如何编写等待成功调用的应用程序的正确方向,以便我知道尚未设置用户?
-(BOOL)doesTheUserExistAlreadyOnServer:(NSString *)parsedEmail
{
BOOL *methodResponse = NO;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.myurl.co.uk/"]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
path:@"http://www.myurl.co.uk/igym.php"
parameters:@{@"myvar2":@"piggy"}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
// NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
if ([[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] isEqualToString:@"piggy"]) {
__block methodResponse = YES;
NSLog(@"%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[operation start];
return (BOOL)methodResponse;
}
编辑:
我使用以下逻辑解决了这个问题。
用户点击注册按钮。main 方法执行所有初步的非 Web 检查,然后调用[self doesTheUserExistAlreadyOnServer:_email.text];
该方法代码现在是
-(void)doesTheUserExistAlreadyOnServer:(NSString *)parsedEmail
{
if(![_spinner isAnimating])
{
[_spinner startAnimating];
}
__block RegistrationViewController* me = self;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.myurl.co.uk/"]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
path:@"http://www.myurl.co.uk/igym.php"
parameters:@{@"myvar2":@"piggy"}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
if ([[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] isEqualToString:@"piggy"]) {
NSLog(@"%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
[me registrationPartTwo:YES];
} else
{
[me registrationPartTwo:NO];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[operation start];
}
然后,一旦该块/回调成功,它就会调用
-(void)registrationPartTwo:(BOOL)doesItExistOnServer
{
[_spinner stopAnimating];
NSString *emailAlreadyInUseMessage = [NSString stringWithFormat:@"This email is already in use"];
if (doesItExistOnServer)
{
self.screenMsg.text = emailAlreadyInUseMessage;
//here more code to send the user the the next step
}
}
基本上我使用依赖于回调的 2method 注册过程解决了这个问题,不知道那是最好还是最有效的方法。但这就是我可以自己解决的方法。