Return type of method is NSArray, so when I call this method I get nil or empty array. Here it's below my method implementation:
- (NSArray *)startParsing {
__block NSArray *array;
allProductsID = [[NSMutableArray alloc] init];
NSString *string = [NSString stringWithFormat:@"http://%@:@%@",kPrestaShopAPIKey, kPrestaShopURLString];
NSURL *url = [NSURL URLWithString:string];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
[manager GET:@"categories/21" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSXMLParser *parser = (NSXMLParser *)responseObject;
[parser setShouldProcessNamespaces:YES];
parser.delegate = self;
[parser parse];
//NSLog(@"First response %@", responseObject);
for (int i = 0; i< [[self.xmlShop objectForKey:@"product"] count]; i++) {
//NSLog(@"Second ID --> %@", [self.xmlShop objectForKey:@"product"][i]);
NSString *productID = [NSString stringWithFormat:@"products/%@", [[self.xmlShop objectForKey:@"product"][i] objectForKey:@"id"]];
[allProductsID addObject:productID];
}
array = [allProductsID copy];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error occured %@", [error localizedDescription]);
}];
return array;
}
Can anyone help me with this problem?
As Quentin already mentioned, you can not directly do that because you are internally performing an asynchronous request. That means that your program starts the request and then continues its next statements and does not wait for the request to finish. What you should do is either
startParsing
method (the same way blocks are used for the actual request callbacks)That would loke for example like the following:
- (void)startParsing:(void (^)(NSArray*))parsingFinished {
allProductsID = [[NSMutableArray alloc] init];
NSString *string = [NSString stringWithFormat:@"http://%@:@%@",kPrestaShopAPIKey, kPrestaShopURLString];
NSURL *url = [NSURL URLWithString:string];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
[manager GET:@"categories/21" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// do your parsing...
parsingFinished([allProductsID copy]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
parsingFinished([[NSArray alloc] init]);
// or return nil or provide a parsingFailed callback
}];
}
which you would then call like
[yourObject startParsing:^(NSArray *parsedData) {
// do something with the parsed data
}];