使用AFnetworking 2(或其他一些框架)登录用户
-
21-12-2019 - |
题
我正在尝试编写一些代码来拥有用户输入他们的用户名和密码,然后使用基本的HTTP身份验证对服务器进行身份验证。我可以使用AFnetworking 2进行它,但我希望能够返回该请求是否成功。下面的代码有效,但我如何重构它,以便我可以调用该方法,然后返回bool true或false ??它让我疯狂,我不能这样做。
- (void)authenticateWithUserEmail:(NSString *)pUserEmail
withUserPassword:(NSString *)pUserPassword {
NSString *loginURL =
@"https://mydomain/login";
AFHTTPRequestOperationManager *manager =
[AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer
setAuthorizationHeaderFieldWithUsername:pUserEmail
password:pUserPassword];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
AFHTTPRequestOperation *operation = [manager GET:loginURL
parameters:[self jsonDict]
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure");
}];
[operation start];
}
- (IBAction)btnAuthenticate:(id)sender {
[self authenticateWithUserEmail:self.userEmail.text
withUserPassword:self.userPassword.text];
}
. 解决方案
因为网络调用是异步执行的,您不能简单地返回BOOL,因为方法一旦呼叫生成的手机返回,那么该网络呼叫尚未完成。您需要做的是将一个块参数添加到您在[operation start];
的完成或失败块中调用的方法,以便您的方法签名将如下所示:
- (void)authenticateWithUserEmail:(NSString *)pUserEmail
withUserPassword:(NSString *)pUserPassword
completion:(void (^)(BOOL success))completionBlock;
.
在此方法中,添加到您的成功/失败块以调用您的新块参数。如:
AFHTTPRequestOperation *operation = [manager GET:loginURL
parameters:[self jsonDict]
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (completionBlock) {
completionBlock(YES);
}
NSLog(@"Success");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (completionBlock) {
completionBlock(NO);
}
NSLog(@"Failure");
}];
.
和您对此方法的调用现在如下所示:
- (IBAction)btnAuthenticate:(id)sender {
[self authenticateWithUserEmail:self.userEmail.text
withUserPassword:self.userPassword.text
completion:^(BOOL success) {
if (success) {
//login successful, do stuff
} else {
//login failed, do other stuff
}
}];
}
.
这通常如何处理响应异步事件,因为您无法返回尚未确定的东西。
不隶属于 StackOverflow