我从webservice获取数据。这是我的代码
- (NSArray *)setupConnection
{
airportArray = nil;
NSString *airportCode = [NSString stringWithFormat:@"somevalue"];
NSString *authenticationCode = [NSString stringWithFormat:@"somenumber"];
NSString *baseurl = [NSString stringWithFormat:@"someurl",authenticationCode,airportCode];
// NSString *mainurlString = [NSString stringWithFormat:@""];
// NSURL *mainurl = [NSURL URLWithString:mainurlString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:baseurl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *mainArray = (NSArray *)responseObject;
airportArray = [[NSMutableArray alloc] init];
for (NSDictionary *all in mainArray) {
airports = [all objectForKey:@"something"];
[airportArray addObject:airports];
NSLog(@"%@", airports);//**this prints the value**
}
//NSLog(@"%@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
UIAlertController *mainAlert = [UIAlertController alertControllerWithTitle:@"Something Wrong!" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:mainAlert animated:YES completion:nil];
}];
return airportArray;//**this returns null**
}
我检查了这个,但它是空的
- (void)printap
{
NSArray *chk = [self setupConnection];
NSLog(@"CHK :%@", chk);
}
打印时打印值。但是当我返回时它是null。为什么这样。帮助我这个
答案 0 :(得分:0)
嘿,你需要使用回调块。
以下是您提供的代码的示例。
在头文件
中typedef void(^FailureBlock)(NSError *error);
typedef void (^SuccessBlock)(NSArray *responseArray);
在实施档案
中@implementation BSANetworkController {
FailureBlock _failureBlock;
SuccessBlock _successBlock;
}
- (void)setupConnectionWithsuccess:(SuccessBlock)success failure:(FailureBlock)failure;
//your code...
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:baseurl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *mainArray = (NSArray *)responseObject;
airportArray = [[NSMutableArray alloc] init];
for (NSDictionary *all in mainArray) {
airports = [all objectForKey:@"something"];
[airportArray addObject:airports];
NSLog(@"%@", airports);//**this prints the value**
}
if (_successBlock) {
_successBlock(airports); //Change the type as per your need
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (_failureBlock) {
_failureBlock(error);
}
}];
}
- (void)printap
{
[self setupConnectionWithsuccess:^(NSArray *array) {
NSLog(@"CHK :%@", array);
} failure:^(NSError *error) {
UIAlertController *mainAlert = [UIAlertController alertControllerWithTitle:@"Something Wrong!" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:mainAlert animated:YES completion:nil];
}
}];
}
在下面的链接中阅读。