RSS Feed无法加载

时间:2014-07-01 17:17:20

标签: ios objective-c uitableview rss

我有一个显示来自RSS提要的数据的tableview,只要它不是我的应用程序的根视图就可以正常工作。我总是通过按下按钮来显示它,但现在我想让它成为用户看到的第一个视图,但活动指示器只是保持旋转而内容永远不会加载。就像我说的那样,当我从一个按钮将它推到导航堆栈上时,它会加载内容,所以我不确定为什么它在第一个视图时无法加载所示。

的AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
     AgStoriesViewController *rootView = [[AgStoriesViewController alloc] initWithNibName:nil bundle:nil];
        WebViewController *wvc = [[WebViewController alloc]init];
        [rootView setWebViewController:wvc];

        KFBNavControllerViewController *navController = [[KFBNavControllerViewController alloc] initWithRootViewController:rootView];
        navController.delegate = rootView;
     self.window.rootViewController = navController;
     [self.window makeKeyAndVisible];
}

带RSS的TableView

#import "AgStoriesViewController.h"
#import "RSSChannel.h"
#import "RSSItem.h"
#import "WebViewController.h"
#import "DTCustomColoredAccessory.h"
#import "UIImage+ImageEffects.h"
#import "UIView+Borders.h"
#import "TSMessage.h"
#import "TSMessageView.h"
#import "ArticleCell.h"
#import "KFBAppDelegate.h"
#import "MenuTableViewController.h"

@implementation AgStoriesViewController
{
    UIActivityIndicatorView *loadingIndicator;
}

@synthesize webViewController, blurredView, contentView, menuShown;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.navigationController.delegate = self;
    }
    return self;
}

- (void)viewDidLoad
{
    menuShown = NO;

    UIImage *background = [UIImage imageNamed:@"sunset"];
    UIImageView *backgroundImageView = [[UIImageView alloc]initWithImage:background];

    CGFloat width = CGRectGetWidth(self.view.bounds);
    CGFloat height = CGRectGetHeight(self.view.bounds);

    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.backgroundView = backgroundImageView;

    self.title = @"Ag News";

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    {
        UIImage *hamburgerButton = [UIImage imageNamed:@"list_button"];
        UIBarButtonItem *listButton = [[UIBarButtonItem alloc]initWithImage:hamburgerButton style:UIBarButtonItemStyleBordered target:self action:@selector(showMenu)];
        self.navigationItem.leftBarButtonItem = listButton;
    }

    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    {
        loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(width / 2, height / 2, 37, 37)];
        loadingIndicator.center = CGPointMake(width / 2, height / 2 - 37);
    }
    else
    {
        loadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(142, 365, 37, 37)];
    }

    loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    loadingIndicator.hidesWhenStopped = YES;
    [self.tableView addSubview:loadingIndicator];
    [loadingIndicator startAnimating];
}

- (void)showMenu
{
    if (!menuShown)
    {
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        CGFloat screenWidth = screenRect.size.width;
        CGFloat screenHeight = screenRect.size.height;

        UIColor *kfbBlue = [UIColor colorWithRed:8.0/255.0f green:77.0/255.0f blue:139.0/255.0f alpha:1];

        contentView = [[UIView alloc]initWithFrame:self.tableView.bounds];
        contentView.autoresizesSubviews = YES;
        contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
        contentView.backgroundColor = [UIColor clearColor];

        blurredView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
        [blurredView setBarStyle:UIBarStyleBlack];
        [blurredView setBarTintColor:kfbBlue];

        MenuTableViewController *menu = [[MenuTableViewController alloc]initWithNibName:@"MenuTableViewController" bundle:nil];
        menu.view.frame = CGRectMake(0, 0, screenWidth, screenHeight - 50);
        [self.view addSubview:contentView];
        [contentView addSubview:blurredView];
        [self addChildViewController:menu];
        [contentView addSubview:menu.view];
        self.tableView.scrollEnabled = NO;
        menuShown = YES;
    }
    else if (menuShown)
    {
        [contentView removeFromSuperview];
        [blurredView removeFromSuperview];
        self.navigationController.navigationBarHidden = NO;
        self.tableView.scrollEnabled = YES;
        menuShown = NO;
    }
}

- (void)closeMenu
{
    [contentView removeFromSuperview];
    self.navigationController.navigationBarHidden = NO;
    self.tableView.scrollEnabled = YES;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [loadingIndicator stopAnimating];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"%@ found a %@ element", self, elementName);
    if ([elementName isEqual:@"channel"])
    {
        channel = [[RSSChannel alloc]init];

        [channel setParentParserDelegate:self];


        [parser setDelegate:channel];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"channel items %lu", (unsigned long)[[channel items]count]);
    return [[channel items]count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 215;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ 
    RSSItem *item = [[channel items]objectAtIndex:[indexPath row]];

    ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"articleCell"];
    if (!cell)
    {
        NSArray *nibs =[[NSBundle mainBundle] loadNibNamed:@"ArticleCell" owner:self options:NULL];
        cell = [nibs firstObject];
    }
    cell.articleTitle.text = [item title];
    cell.articleDescription.text = [item infoString];

    cell.articleTitle.textColor = [UIColor whiteColor];
    cell.articleDescription.textColor = [UIColor whiteColor];
    cell.articleTitle.font = [UIFont fontWithName:@"FranklinGothicStd-ExtraCond" size:22.0];
    cell.articleDescription.font = [UIFont fontWithName:@"FranklinGothicStd-ExtraCond" size:16.0];
    cell.backgroundColor = [UIColor clearColor];

    return cell;
}

- (void)fetchEntries
{

    xmlData = [[NSMutableData alloc]init];


    NSURL *url = [NSURL URLWithString:@"http://kyfbnewsroom.com/category/ag-news/feed"];


    NSURLRequest *req = [NSURLRequest requestWithURL:url];


    connection = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];

    if (self)
    {
        [self fetchEntries];
    }

    return self;
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
    [xmlData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{ 
    [loadingIndicator stopAnimating];

    UIImage *background = [UIImage imageNamed:@"sunset"];
    UIImage *effectImage = [background applyDarkEffect];
    UIImageView *blurredBackground = [[UIImageView alloc]init];
    blurredBackground.image = effectImage;
    self.tableView.backgroundView = blurredBackground;

    // Create the parser object with the data received from the web service
    NSXMLParser *parser = [[NSXMLParser alloc]initWithData:xmlData];

    // Give it a delegate
    [parser setDelegate:self];

    //Tell it to start parsing - the document will be parsed and the delegate of NSXMLParser will get all of its delegate messages sent to it before this line finishes execution - it is blocking
    [parser parse];

    // Get rid of the XML data as we no longer need it
    xmlData = nil;

    NSMutableArray *actionAlerts = [NSMutableArray array];
    for (RSSItem *object in channel.items)
    {
        if (object.isActionAlert)
        {
            [actionAlerts addObject:object];
        }
    }

    for (RSSItem *object in actionAlerts)
    {
        [channel.items removeObject:object];
    }

    // Reload the table
    [[self tableView]reloadData];

    NSLog(@"%@\n %@\n %@\n", channel, [channel title], [channel infoString]);
}

- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
    // Release the connection object, we're done with it
    connection = nil;

    // Release the xmlData object, we're done with it
    xmlData = nil;

    [loadingIndicator stopAnimating];

    // Grab the description of the error object passed to us
    NSString *errorString = [NSString stringWithFormat:@"Fetch failed: %@", [error localizedDescription]];

    // Create and show an alert view with this error displayed
    // UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    // [av show];

    [TSMessage showNotificationWithTitle:@"Network Error" subtitle:errorString type:TSMessageNotificationTypeError];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    {
        [[webViewController webView]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];

        [self.navigationController pushViewController:webViewController animated:YES];

        RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]];

        NSURL *url = [NSURL URLWithString:[entry link]];

        NSURLRequest *req = [NSURLRequest requestWithURL:url];

        [[webViewController webView]loadRequest:req];
        webViewController.hackyURL = url;
    }
    else
    {
        [[webViewController webView]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];

        NSMutableArray *details = [self.splitViewController.viewControllers mutableCopy];

        UINavigationController *detailNav = [[UINavigationController alloc]initWithRootViewController:webViewController];

        [details replaceObjectAtIndex:1 withObject:detailNav];

        KFBAppDelegate *appDelegate = (KFBAppDelegate *)[[UIApplication sharedApplication]delegate];
        appDelegate.splitViewController.viewControllers = details;
        appDelegate.window.rootViewController = self.splitViewController;
        appDelegate.splitViewController.delegate = webViewController;
        [appDelegate.splitViewController viewWillAppear:YES];

        // Grab the selected item
        RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]];

        // Construct a URL with the link string of the item
        NSURL *url = [NSURL URLWithString:[entry link]];

        // Construct a request object with that URL
        NSURLRequest *req = [NSURLRequest requestWithURL:url];

        // Load the request into the web view
        [[webViewController webView]loadRequest:req];
        webViewController.hackyURL = url;

        // Set the title of the web view controller's navigation item
        [[webViewController navigationItem]setTitle:[entry title]];
    }
}

@end

1 个答案:

答案 0 :(得分:1)

使用此方法重新加载表数据 -

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
     [[self tableView]reloadData];
}

在解析xml文档完成时调用此方法。当数据未在数组中正确设置时,您正在重新加载表,因此它显示为空表。

编辑 - 在视图初始化时正确调用连接方法。

需要在fetchEntries中调用

viewDidLoad