gpt4 book ai didi

ios - 在 AFNETWORKING 中返回响应

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

我正在关注 this在 IOS 中学习 AfNetworking 的教程我正在使用以下函数从服务器获取响应:

{
// 1
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 2
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
// 3
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//Success
}
// 4
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}];

// 5
[operation start];
}

我想要的是编写一个函数,在获得响应后将响应作为 NSString 返回。我不知道语法。有人可以帮助我吗?

最佳答案

Try this


- (void)getResponse:(void (^)(id result, NSError *error))block {
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 2
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
// 3
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//Success
block(JSON,nil); //call block here
}
// 4
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}];

// 5
[operation start];

}

打电话

[self getResponse:^(id result, NSError *error) {
//use result here
}];

希望对你有帮助

关于ios - 在 AFNETWORKING 中返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18146215/

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