2015-05-02 43 views
0

我想从RSS网址获取最新数据,并在Today Widget扩展中显示其内容,使用RSSParser,但问题是它返回null!这里是我的代码:今天扩展小部件使用RSSParser

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myBlog.net/?feed=rss2"]]; 
    [RSSParser parseRSSFeedForRequest:req success:^(NSArray *feedItems) { 

     [self setDataSource:feedItems]; 

    } failure:^(NSError *error) { 
     [self setTitle:@"Error"]; 
     NSLog(@"Error: %@",error); 

    }]; 

    item = [self.dataSource objectAtIndex:0]; 

    //this returns null: 
    NSLog(@"Title is %@",[item title]); 

    NSLog(@"Widget Runs"); 

} 

回答

1

不熟悉库,但调用模式足够熟悉,以便假定请求异步运行。这意味着人们通常假设代码从上到下执行并不成立。

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myBlog.net/?feed=rss2"]]; 
    [RSSParser parseRSSFeedForRequest:req success:^(NSArray *feedItems) { 
     // this runs after the request completes 
     NSLog(@"Got here #2"); 

     // moving your test code here will allow it to work 
     item = [self.dataSource objectAtIndex:0]; 
     NSLog(@"Title is %@",[item title]); 

    } failure:^(NSError *error) { 
     [self setTitle:@"Error"]; 
     NSLog(@"Error: %@",error); 

    }]; 

    // this runs before the request begins 
    NSLog(@"Got here #1"); 
} 
+0

我试过你的方法,但结果是'null' –

+0

我只是增加'[self setDataSource:feedItems];'而且工作! –