2015-05-02 162 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];'而且工作! –