0
我正在使用AFNetworking,我讀過同步響應不鼓勵。但是我需要檢查用戶是否已經存在於在線數據庫中,然後用戶才能進入應用程序的下一個階段。是的,一個典型的註冊過程。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;
}
編輯:
我使用以下邏輯解決了這個問題。
用戶點擊註冊按鈕。主要的方法完成了所有前期非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
}
}
基本上我解決了這個使用2方法註冊過程依賴於回調,不知道這是否是最好的或最有效的方式。但那就是我可以自己解決的方式。
我對此很新。你能提供一個例子或鏈接到一個例子嗎? –