Showing RSS Data in a split view

Discussion in 'iOS Programming' started by BrooklynDon, Jan 28, 2011.

  1. macrumors newbie

    Joined:
    Jan 10, 2011
    #1
    Hello folks,
    Yes, this is the noodge from Brooklyn, again. My boss is also looking for news releases in a window. I was thinking about using a split view having the headlines in the RootView and showing the headline and news article in the DetailView window.
    Well, connect and load the XML file from the website, check. parse out the title tags check. Putting the titles in the RootView cells, problem. putting the title and story in the detail window, problem
    Code for the RootViewController:
    Code:
    #import "RootViewController.h"
    #import "DetailViewController.h"
    
    
    @implementation RootViewController
    
    @synthesize detailViewController;
    
    NSMutableArray *newsList;
    
    #pragma mark -
    #pragma mark View lifecycle
    
    - (void)viewDidLoad {
    	
    	newsList = [[NSMutableArray alloc] init];
    	
    	NSString *queryString = [NSString stringWithFormat:@"http://www.downstate.edu/RSS2/dnews2.xml"];
    	NSURL *url = [NSURL URLWithString:queryString];
    	NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    	[req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    	[req addValue:0 forHTTPHeaderField:@"Content-Length"];
    	[req setHTTPMethod:@"GET"];
    	
    	conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    	if (conn) {
    		webData = [[NSMutableData data] retain];
    	}
    	
        [super viewDidLoad];
        self.clearsSelectionOnViewWillAppear = NO;
        self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
    }
    
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    	[webData setLength:0];
    }
    
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    	[webData appendData:data];
    }
    
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Error" 
    													message:@"Please check your network connection"
    												   delegate:self 
    										  cancelButtonTitle:@"OK"
    										  otherButtonTitles:nil];
    	[alert show];
    	[alert release];
    	[webData release];
    }
    
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    	//NSLog(@"DONE. Received Bytes: %d", [webData length]);
    	NSString *theXML = [[NSString alloc]
    						initWithBytes:[webData mutableBytes]
    						length:[webData length]
    						encoding:NSUTF8StringEncoding];
    	//Show the XML
    	//NSLog(theXML);
    	[theXML release];
    	if (xmlParser) {
    		[xmlParser release];
    	}
    	xmlParser = [[NSXMLParser alloc] initWithData:webData];
    	newsList = [[NSMutableArray alloc] init];
    	[xmlParser setDelegate:self];
    	[xmlParser setShouldResolveExternalEntities:YES];
    	[xmlParser parse];
    	[connection release];
    	[webData release];
    }
    
    -(void) parser:(NSXMLParser *)parser 
    didStartElement:(NSString *)elementName 
      namespaceURI:(NSString *)namespaceURI 
     qualifiedName:(NSString *)qName 
    	attributes:(NSDictionary *)attributeDict {
    	if ([elementName isEqualToString:@"title"]) {
    		if (!titleResults) {
    			titleResults = [[NSMutableString alloc] init];
    		}
    		titleElementFound = YES;
    	}
    }
    
    -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    	if (titleElementFound) {
    		[titleResults appendString: string];
    	}
    }
    
    -(void)parser:(NSXMLParser *)parser 
    didEndElement:(NSString *)elementName 
     namespaceURI:(NSString *)namespaceURI 
    qualifiedName:(NSString *)qName{
    	
    	if ([elementName isEqualToString:@"title"]) {
    		//display the title in the debugger console
    		NSLog(@"i=%d",i);
    		NSLog(@"Title:");
    		NSLog(titleResults);
    		if (i == 0) {
    			self.navigationItem.title = titleResults;
    		} else {
    			[newsList addObject:titleResults];
    			NSLog(@"Added News Title!");
    		}
    		++i;
    		[titleResults setString:@""];
    		titleElementFound = FALSE;
    	} 
    }
    
    /*
    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
    }
    */
    /*
    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    }
    */
    /*
    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    }
    */
    /*
    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
    }
    */
    
    // Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
        return YES;
    }
    
    
    #pragma mark -
    #pragma mark Table view data source
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
        // Return the number of sections.
        return 1;
    }
    
    
    - (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
        // Return the number of rows in the section.
        // return 10;
    	return [newsList count];
    }
    
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        
        static NSString *CellIdentifier = @"CellIdentifier";
        
        // Dequeue or create a cell of the appropriate type.
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        // Configure the cell.
    	// cell.textLabel.text = [NSString stringWithFormat:@"Row %d", indexPath.row];
    	cell.textLabel.text = [newsList objectAtIndex:indexPath.row];
        return cell;
    }
    
    
    /*
    // Override to support conditional editing of the table view.
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        // Return NO if you do not want the specified item to be editable.
        return YES;
    }
    */
    
    
    /*
    // Override to support editing the table view.
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
        
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            // Delete the row from the data source
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
        }   
        else if (editingStyle == UITableViewCellEditingStyleInsert) {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }   
    }
    */
    
    
    /*
    // Override to support rearranging the table view.
    - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    }
    */
    
    
    /*
    // Override to support conditional rearranging of the table view.
    - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
        // Return NO if you do not want the item to be re-orderable.
        return YES;
    }
    */
    
    
    #pragma mark -
    #pragma mark Table view delegate
    
    - (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        
        /*
         When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
         */
        // detailViewController.detailItem = [newsList objectAtIndex:indexPath.row];
    	detailViewController.detailItem = [NSString stringWithFormat:@"%@",[newsList objectAtIndex:indexPath.row]];
    }
    
    
    #pragma mark -
    #pragma mark Memory management
    
    - (void)didReceiveMemoryWarning {
        // Releases the view if it doesn't have a superview.
        [super didReceiveMemoryWarning];
        
        // Relinquish ownership any cached data, images, etc. that aren't in use.
    }
    
    - (void)viewDidUnload {
        // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
        // For example: self.myOutlet = nil;
    }
    
    
    - (void)dealloc {
    	[titleResults release];
        [detailViewController release];
        [super dealloc];
    }
    
    
    @end
    
    I'm using the parsing algorithm from Wei-Meng Lee's Article in devx.com I could see the title ok. Here is the DetailView Controller:
    Code:
    #import "DetailViewController.h"
    #import "RootViewController.h"
    
    
    @interface DetailViewController ()
    @property (nonatomic, retain) UIPopoverController *popoverController;
    - (void)configureView;
    @end
    
    @implementation DetailViewController
    
    @synthesize newsLabel;
    @synthesize descriptionLabel;
    
    @synthesize toolbar, popoverController, detailItem, detailDescriptionLabel;
    
    NSMutableArray *newsList;
    NSMutableArray *descriptionList;
    
    #pragma mark -
    #pragma mark Managing the detail item
    
    /*
     When setting the detail item, update the view and dismiss the popover controller if it's showing.
     */
    - (void)setDetailItem:(id)newDetailItem {
        if (detailItem != newDetailItem) {
            [detailItem release];
            detailItem = [newDetailItem retain];
            
            // Update the view.
    		NSString *headline = [NSString stringWithFormat:@"%@",[newsList description]];
    		NSString *newsStory = [NSString stringWithFormat:@"%@",[descriptionList description]];
    		newsLabel.text = headline;
    		descriptionLabel.text = newsStory;
            [self configureView];
        }
    
        if (self.popoverController != nil) {
            [self.popoverController dismissPopoverAnimated:YES];
        }        
    }
    
    
    - (void)configureView {
        // Update the user interface for the detail item.
        detailDescriptionLabel.text = [detailItem description];   
    }
    
    
    #pragma mark -
    #pragma mark Split view support
    
    - (void)splitViewController: (UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController: (UIPopoverController*)pc {
        
        barButtonItem.title = @"SUNY Downstate Newsfeed";
        NSMutableArray *items = [[toolbar items] mutableCopy];
        [items insertObject:barButtonItem atIndex:0];
        [toolbar setItems:items animated:YES];
        [items release];
        self.popoverController = pc;
    }
    
    
    // Called when the view is shown again in the split view, invalidating the button and popover controller.
    - (void)splitViewController: (UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem {
        
        NSMutableArray *items = [[toolbar items] mutableCopy];
        [items removeObjectAtIndex:0];
        [toolbar setItems:items animated:YES];
        [items release];
        self.popoverController = nil;
    }
    
    
    #pragma mark -
    #pragma mark Rotation support
    
    // Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
        return YES;
    }
    
    
    #pragma mark -
    #pragma mark View lifecycle
    
    
     // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad {
    	
    	NSString *queryString = [NSString stringWithFormat:@"http://www.downstate.edu/RSS2/dnews2.xml"];
    	NSURL *url = [NSURL URLWithString:queryString];
    	NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    	[req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    	[req addValue:0 forHTTPHeaderField:@"Content-Length"];
    	[req setHTTPMethod:@"GET"];
    	
    	conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    	if (conn) {
    		webData = [[NSMutableData data] retain];
    	}
    	
        [super viewDidLoad];
    }
    
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    	[webData setLength:0];
    }
    
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    	[webData appendData:data];
    }
    
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Error"
    													message:@"Please check your network connection"
    												   delegate:self
    										  cancelButtonTitle:@"OK"
    										  otherButtonTitles:nil];
    	[alert show];
    	[alert release];
    	[webData release];
    }
    
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    	NSLog(@"Done. Received Bytes: %d", [webData length]);
    	NSString *theXML = [[NSString alloc]
    						initWithBytes:[webData mutableBytes]
    						length:[webData length]
    						encoding:NSUTF8StringEncoding];
    	NSLog(theXML);
    	[theXML release];
    	if (xmlParser) {
    		[xmlParser release];
    	}
    	xmlParser = [[NSXMLParser alloc]initWithData:webData];
    	newsList = [[NSMutableArray alloc]init];
    	descriptionList = [[NSMutableArray alloc]init];
    	[xmlParser setDelegate:self];
    	[xmlParser setShouldResolveExternalEntities:YES];
    	[xmlParser parse];
    	[connection release];
    	[webData release];
    }
    
    -(void)parser:(NSXMLParser *)parser
    didStartElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI
    qualifiedName:(NSString *)qName
       attributes:(NSDictionary *)attributeDict{
    	if ([elementName isEqualToString:@"title"]) {
    		if (!titleResults) {
    			titleResults = [[NSMutableString alloc] init];
    		}
    		titleElementFound = YES;
    	}
    	if ([elementName isEqualToString:@"description"]) {
    		if (!descriptionResults) {
    			descriptionResults = [[NSMutableString alloc] init];
    		}
    		descriptionElementFound = YES;
    	}
    }
    
    -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    	if (titleElementFound) {
    		[titleResults appendString:string];
    	}
    	if (descriptionElementFound) {
    		[descriptionResults appendString:string];
    	}
    }
    
    -(void)parser:(NSXMLParser *)parser
    didEndElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI
    qualifiedName:(NSString *)qName{
    	
    	if ([elementName isEqualToString:@"title"]) {
    		NSLog(titleResults);
    		[newsList addObject:titleResults];
    		[titleResults setString:@""];
    		titleElementFound = FALSE;
    	} else if ([elementName isEqualToString:@"description"]) {
    		NSLog(descriptionResults);
    		[descriptionResults setString:@""];
    		descriptionElementFound = FALSE;
    	}
    }
    	
    
    /*
    - (void)viewWillAppear:(BOOL)animated {
    	
        [super viewWillAppear:animated];
    }
    */
    /*
    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    }
    */
    /*
    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    }
    */
    /*
    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
    }
    */
    
    - (void)viewDidUnload {
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
        self.popoverController = nil;
    }
    
    
    #pragma mark -
    #pragma mark Memory management
    
    /*
    - (void)didReceiveMemoryWarning {
        // Releases the view if it doesn't have a superview.
        [super didReceiveMemoryWarning];
        
        // Release any cached data, images, etc that aren't in use.
    }
    */
    
    - (void)dealloc {
        [popoverController release];
        [toolbar release];
        
        [detailItem release];
        [detailDescriptionLabel release];
        [super dealloc];
    }
    
    @end
    
    How do I move the text from the title and article from the parsed XML (newsList and discriptionList) into the newsLabel and descriptionLabel? As always, TIA!
     
  2. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    First, when you say problem, what do you mean, exactly? Remember to be specific. What are you expecting to happen? And what actually happens? What basic debugging have you done and what have you learned from it?
     

Share This Page