gpt4 book ai didi

ios - AF 网络 2.0 : AFHTTPRequestOperationManager asynchronous methode invoke

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:44:45 25 4
gpt4 key购买 nike

我正在使用 AFNetworking 2.0 为我的应用程序联网,我已经实现了一种检查用户登录的方法

-(NSString *) loginWith : (NSString *) email andPassword :(NSString *) password
{
__block NSString * result ;

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSDictionary *params = @{@"email": email, @"password": password};

manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager POST:[kROOT_URL stringByAppendingString:@"auth/"] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"JSON: %@", (NSDictionary*)responseObject);

[[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:USER_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];

result = [responseObject objectForKey:@"id"];
NSLog(@"result :: %@",result);

} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Error: %@", error);

result = nil;

}];

return result;
}

我正在从其他 View Controller 调用此方法:

NSString * result = [self.user loginWith:emailCell.textField.text andPassword:passCell.textField.text];

NSLog(@"Result: %@",result);

问题是我得到“null”作为结果的对象,这是因为当执行 NSlog 时,网络进程在后台线程中进行,所以我如何更正实现,这样我才能得到结果在适当的时候,在获取之后

谢谢

最佳答案

您应该在方法签名中添加一个“回调” block 参数,并在请求完成时调用该 block 。

- (void)loginWith:(NSString *)email andPassword:(NSString *)password complete:(void(^)(id result, NSError *error))block {

// ...

[manager POST:[kROOT_URL stringByAppendingString:@"auth/"] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
{

// ...

result = [responseObject objectForKey:@"id"];

if (block) block(result, nil)

} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{

if (block) block(nil, error)

}];

}

调用该方法时,传递回调 block ,您可以在其中读取结果值:

[self.user loginWith:emailCell.textField.text andPassword:passCell.textField.text complete:^(id result, NSError *error) {
if (error)
NSLog(@"Error: %@", error);
else
NSLog(@"Result: %@", result);
}];

关于ios - AF 网络 2.0 : AFHTTPRequestOperationManager asynchronous methode invoke,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20058897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com