Data won't load after XML parsing

2019-08-18 18:52发布

I'm new to iOS and I have been trying to implement XML parsing. I'm using a custom class(XMLParser) for XML parsing, provided by Gabriel Theodoropoulos. I'm trying to load and save data when the app launches.

The data is parsed and saved too, but the view that I'm trying to load the saved file loads before and so the data isn't being displayed. But when I push the view again into view, data is visible.

From what I have observed, the completion of the XMLParser class method in AppDelegate takes place after the view has been loaded. The parsing and view loading happens correctly when I click a refresh button to perform the same action.

Can you help?

Here is how far I've come:

AppDelegate.m

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self initialNewsFetch];
return YES;
}
-(void) initialNewsFetch
{
//1. Main view|Home:- Most Read
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
RootViewController * mostRead = [storyboard instantiateViewControllerWithIdentifier:@"RootViewController"];
[mostRead refreshData];
[[NSNotificationCenter defaultCenter] postNotificationName:@"ArtsNewsAvailable" object:nil];

}
@end

ViewController.m

 -(void)refreshData{

XMLParser *xmlParser = [[XMLParser alloc] initWithXMLURLString:MostReadNewsFeed];
[xmlParser startParsingWithCompletionHandler:^(BOOL success, NSArray *dataArray, NSError *error) {

    if (success) {
        [self performNewFetchedDataActionsWithDataArray:dataArray];
    }
    else{
        NSLog(@"%@", [error localizedDescription]);
    }
}];

}

-(void)performNewFetchedDataActionsWithDataArray:(NSArray *)dataArray{
// 1. Initialize the arrNewsData array with the parsed data array.
if (self.arrNewsData != nil) {
    self.arrNewsData = nil;
}
self.arrNewsData = [[NSArray alloc] initWithArray:dataArray];


// 2. Write the file and reload the view.
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * docDirectory = [paths objectAtIndex:0];
NSString * newsFilePath = [NSString stringWithFormat:@"%@",[docDirectory stringByAppendingPathComponent:@"mostRead"]]; // NewsFile

if (![self.arrNewsData writeToFile:newsFilePath atomically:YES]) {
    _newsAvailable = NO;
    NSLog(@"Couldn't save data.");
}
else
{
    _newsAvailable = YES;
    [self viewDidLoad]; //even tried calling this//
}
}

0条回答
登录 后发表回答