XML解析后,数据不会加载

时间:2017-06-08 12:04:48

标签: ios objective-c xml-parsing nsxmlparserdelegate

我是iOS新手,我一直在努力实现XML解析。 我使用自定义类(XMLParser)进行XML解析,由Gabriel Theodoropoulos提供。 我试图在应用启动时加载并保存数据。

数据也被解析和保存,但我尝试加载保存文件的视图之前加载,因此数据不会被显示。但是当我再次将视图推入视图时,数据是可见的。

根据我的观察,AppDelegate中的XMLParser类方法的完成是在加载视图之后发生的。 单击刷新按钮执行相同操作时,解析和视图加载正确。

你能帮忙吗?

以下是我的到来:

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 个答案:

没有答案