Search code examples
iosobjective-cnsarrayobjective-c-blocks

how to return a array in success block in ios


I'm getting data from a web service.then I want to put that data into a mutable array and return that arrary. I treid just to check the array is null or not.

I have define this in my header file

typedef void(^FailureBlock)(NSError *error);
typedef void(^SuccessBlock) (NSArray *responseArray);

this is my implementation file

- (void)setupConnectionWithsuccess:(SuccessBlock)success failure:(FailureBlock)failure
{
    airportArray = nil;
    NSString *Code = [NSString stringWithFormat:@"something"];
    NSString *authCode = [NSString stringWithFormat:@"something"];
    NSString *baseurl = [NSString stringWithFormat:@"someurl%@%@",authCode,Code];
//    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:@"port"];

            [airportArray addObject:airports];
            NSLog(@"%@", airports);
        }

        if(_successBlock){
            _successBlock(airportArray);
        }

        //NSLog(@"%@", responseObject);
    }
    failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        if (_failureBlock) {
            _failureBlock(error);
        }
        UIAlertController *mainAlert = [UIAlertController alertControllerWithTitle:@"Something Wrong!" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:mainAlert animated:YES completion:nil];

    }];




}

- (void)printap
{   NSLog(@"ffffuuu");
    [self setupConnectionWithsuccess:^(NSArray *responseArray) {

        NSLog(@"Checking ::::%@", responseArray);

    } failure:^(NSError *error) {

        UIAlertController *failureAlert = [UIAlertController alertControllerWithTitle:@"Errrrr..." message:@"Errrrr...." preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:failureAlert animated:YES completion:nil];
    }];
    NSLog(@"fkjfkdjkfjdkfjdk");
}

** I want to use this airportArray after data retrieved(want to return array). how can I do that


Solution

  • These lines:

        if(_successBlock){
            _successBlock(airportArray);
        }
    

    should be:

        if(success){
            success(airportArray);
        }
    

    I don't know what _successBlock is but you want to use the parameter passed into the setupConnectionWithsuccess:failure: method.

    Make a similar change for the failure block by replacing _failureBlock with failure.