Easy XML-Parser for iOS - Objective C - ios

I'm looking for the most "easy-to-implement" method to parse XMLs in Objective-C mobile applications. I tried to use TBXML but I'm a newbie and I got several errors with that...do you think there's something easier out there? Thanks

this is very simple xml parsing..
- (void)viewDidLoad
{
[super viewDidLoad];
self.title=#"Feeds";
titarry=[[NSMutableArray alloc] init];
linkarray=[[NSMutableArray alloc] init];
NSString *rssaddr=#"http://news.prlog.org/rss.xml";
NSURL *url=[NSURL URLWithString:rssaddr];
xmlparser =[[NSXMLParser alloc] initWithContentsOfURL:url];
[xmlparser setDelegate:self];
[xmlparser parse];
// Do any additional setup after loading the view from its nib.
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
{
classelement=elementName;
if([elementName isEqualToString:#"item"])
{
itemselected=YES;
mutttitle=[[NSMutableString alloc] init];
mutstrlink=[[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
{
if([elementName isEqualToString:#"item"])
{
itemselected=NO;
[titarry addObject:mutttitle];
[linkarray addObject:mutstrlink];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
{
if (itemselected)
{
if ([classelement isEqualToString:#"title"])
{
[mutttitle appendString:string];
}
else if ([classelement isEqualToString:#"link"])
{
[mutstrlink appendString:string];
}
}
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;
{
UIAlertView *alt=[[UIAlertView alloc] initWithTitle:#"RSS Reader"
message:[NSString stringWithFormat:#"%#",parseError]
delegate:nil
cancelButtonTitle:#"Close"
otherButtonTitles:nil];
[alt show];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [titarry count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
cell.textLabel.text=[titarry objectAtIndex:indexPath.row];
cell.accessoryType=UITableViewCellSelectionStyleBlue;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
secondViewController *second = [[secondViewController alloc] initWithNibName:#"secondViewController" bundle:nil];
[self.navigationController pushViewController:second animated:YES];
NSURL *url=[NSURL URLWithString:[titarry objectAtIndex:indexPath.row]];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
second.webView.scalesPageToFit=YES;
[second.webView loadRequest:req];//here we have to perform changes try to do some things here
}
add following this in your .h file
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,NSXMLParserDelegate>
{
NSXMLParser *xmlparser;
NSString *classelement;
NSMutableArray *titarry;
NSMutableArray *linkarray;
bool itemselected;
NSMutableString *mutttitle;
NSMutableString *mutstrlink;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSURL *url = [[NSURL alloc] initWithString:#"Your link of the XML"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
// Configure and show the window
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
{
classelement=elementName;
if([elementName isEqualToString:#"item"])
{
itemselected=YES;
mutttitle=[[NSMutableString alloc] init];
mutstrlink=[[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
{
if([elementName isEqualToString:#"item"])
{
itemselected=NO;
[titarry addObject:mutttitle];
[linkarray addObject:mutstrlink];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
{
if (itemselected)
{
if ([classelement isEqualToString:#"title"])
{
[mutttitle appendString:string];
}
else if ([classelement isEqualToString:#"link"])
{
[mutstrlink appendString:string];
}
}
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;
{
UIAlertView *alt=[[UIAlertView alloc] initWithTitle:#"RSS Reader"
message:[NSString stringWithFormat:#"%#",parseError]
delegate:nil
cancelButtonTitle:#"Close"
otherButtonTitles:nil];
[alt show];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [titarry count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
cell.textLabel.text=[titarry objectAtIndex:indexPath.row];
cell.accessoryType=UITableViewCellSelectionStyleBlue;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
secondViewController *second = [[secondViewController alloc] initWithNibName:#"secondViewController" bundle:nil];
[self.navigationController pushViewController:second animated:YES];
NSURL *url=[NSURL URLWithString:[titarry objectAtIndex:indexPath.row]];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
second.webView.scalesPageToFit=YES;
[second.webView loadRequest:req];//here we have to perform changes try to do some things here
}

Related

NSXMLParser foundCharacters Thread 1: EXC_BAD_ACCESS (code=2, address=0x0)

I am trying to implement an rss reader into a table inside a container. I have the code of the parser in an other project and in the specific project it works fine without any error. I copied every file, 4 files exactly as they are in the other project and i copied also the view controllers into my storyboard so they are exactly the same. But when i run the code i get an error!
here is a pic with my error.
I don't know why is this happening. In the other project which has only two view controllers with the table view and the web view it works fine. But when i try to copy every file as it is into my other project I get this error.
This is my .m file
#import "APPMasterViewController.h"
#import "APPDetailViewController.h"
#interface APPMasterViewController () {
NSXMLParser *parser;
NSMutableArray *feeds;
NSMutableDictionary *item;
NSMutableString *title;
NSMutableString *link;
NSString *element;
}
#end
#implementation APPMasterViewController
(void)awakeFromNib {
[super awakeFromNib];
}
- (void)viewDidLoad {
[super viewDidLoad];
feeds = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"http://radioevros.gr/feed/"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return feeds.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [[feeds objectAtIndex:indexPath.row] objectForKey: #"title"];
return cell;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI: (NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
element = elementName;
if ([element isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc] init];
title = [[NSMutableString alloc] init];
link = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"item"]) {
[item setObject:title forKey:#"title"];
[item setObject:link forKey:#"link"];
[feeds addObject:[item copy]];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([element isEqualToString:#"title"]) {
[title appendString:string];
} else if ([element isEqualToString:#"link"]) {
[link appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[self.tableView reloadData];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *string = [feeds[indexPath.row] objectForKey: #"link"];
[[segue destinationViewController] setUrl:string];
}
}
-(void) viewDidUnload{
[element release];
element = nil;
[super viewDidUnload];
}
- (void)dealloc {
[element release];
[super dealloc];
}
#end
I can't say for certain since I haven't tried running your code, but you may want to try to store element using element = [elementName copy]; instead and see if that gets rid of the exception.
My guess is that elementName gets deallocated after you exit the method since it is only a local parameter variable.
As a side note, it appears that you are doing manual memory management. I highly suggest that you convert your project to use ARC since it not only streamlines memory management, it is also what Apple has been recommending to use for quite a while now.

Why isn't my iOS refresh controller working? [duplicate]

This question already exists:
UIRefreshControl not refreshing xml data
Closed 9 years ago.
Can anyone explain why my pull to refresh isn't working? I've called the UIRefresh controller and the "pull to refresh" animation works but the table view doesn't reload the XML data. What am I doing wrong? Please help.
#import "MasterViewController.h"
#import "DetailViewController.h"
#interface MasterViewController () {
NSXMLParser *parser;
NSMutableArray *feeds;
NSMutableDictionary *item;
NSMutableString *title;
NSMutableString *link;
NSString *element;
}
#end
#implementation MasterViewController
- (void)awakeFromNib {
[super awakeFromNib];
}
// Paste Blog feed here
- (void)viewDidLoad {
[super viewDidLoad];
feeds = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"http://www.placeholder.xml"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
UIRefreshControl *refreshControl = [UIRefreshControl new];
[refreshControl addTarget:self
action:#selector(refresh:)
forControlEvents:UIControlEventValueChanged];
refreshControl.attributedTitle =
[[NSAttributedString alloc] initWithString:#"Pull to refresh..."];
self.refreshControl = refreshControl;
}
- (void)refresh:(UIRefreshControl *)sender {
// ... your refresh code
NSURL *url = [NSURL URLWithString:#"http://www.placeholder.xml"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
[sender endRefreshing];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return feeds.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:#"Cell"
forIndexPath:indexPath];
cell.textLabel.text =
[[feeds objectAtIndex:indexPath.row] objectForKey:#"title"];
return cell;
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict {
element = elementName;
if ([element isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc] init];
title = [[NSMutableString alloc] init];
link = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"item"]) {
[item setObject:title forKey:#"title"];
[item setObject:link forKey:#"link"];
[feeds addObject:[item copy]];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([element isEqualToString:#"title"]) {
[title appendString:string];
} else if ([element isEqualToString:#"link"]) {
[link appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[self.tableView reloadData];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *string = [feeds[indexPath.row] objectForKey:#"link"];
[[segue destinationViewController] setUrl:string];
}
}
#end
The idea presented in the answer here should help: stackoverflow.com/a/16347259/1151545
Basically create ur UIRefreshControl then add it as a subview to any UIScrollView. FYI the UITableView is a subclass of UIScrollView

NSArray of dictionaries and copy

i have a huge huge problem, i feel like i will never get rid of it. i got a xml file coming from my server, parsing it well. but i got duplicates in that xml file. The thing is i need to get rid of the duplicates in my NSMutableArray, in order to know what i have in my NSMutable array and display a little menu with wich section is avaible and wich is not. But i can't manage to copy only the good stuff into another array since the NSMutableArray is as a matter of fact a Array of dictionaries. And i don't know how to manage them, i tried sevral things the past two days with no results, so please if someone can help me it would very appreciated.
here is my entire code (hope it doesn't burn you eyes :3) :
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#import "SizingDataViewController.h"
#import "LCYDataBackedTableView.h"
#implementation SizingDataViewController
- (void)viewDidLoad {
//Add the following line if you want the list to be editable
self.title = #"Last choice";
}
-(BOOL)ifStringExists:(NSString *)stringSentToCheck{
for (int i = 0; i < ([stories count]); i++) {
NSLog(#"i = %i", i);
NSMutableString *stringToCheck = (NSMutableString *)[[stories objectAtIndex: i] objectForKey: #"type"];
if ([stringToCheck isEqualToString:stringSentToCheck] == YES) {
NSLog(#"%#", #"okay its OKAY ");
return YES;
}
}
return NO;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
CGRect frame = CGRectMake(0, 0, 160, 50);
UILabel *lbl1 = [[UILabel alloc] initWithFrame:frame];
lbl1.textAlignment = NSTextAlignmentRight;
[lbl1 setFont:[UIFont fontWithName:#"Helvetica" size:12.0]];
[lbl1 setTextColor:[UIColor grayColor]];
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
lbl1.text = [[stories objectAtIndex: storyIndex] objectForKey: #"creation_date"];//Modifier pour changer le texte affiché
[cell.contentView addSubview:lbl1];
[lbl1 release];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [stories count];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)parseXMLFileAtURL:(NSString *)URL
{
stories = [[NSMutableArray alloc] init];
NSData *xmlData = [URL dataUsingEncoding:NSUTF8StringEncoding];
rssParser = [[[NSXMLParser alloc] initWithData:xmlData]autorelease];
[rssParser setDelegate:self];
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString * errorString = [NSString stringWithFormat:#"Unable to download story feed from web site (Error code %i )", [parseError code]];
NSLog(#"error parsing XML: %#", errorString);
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"data"]) {
item = [[NSMutableDictionary alloc] init];
currentData_id = [[NSMutableString alloc] init];
currentSizing_id = [[NSMutableString alloc] init];
currentName = [[NSMutableString alloc] init];
currentSize = [[NSMutableString alloc] init];
currentType = [[NSMutableString alloc]init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"data"]) {
[item setObject:currentData_id forKey:#"data_id"];
[item setObject:currentSizing_id forKey:#"sizing_id"];
[item setObject:currentName forKey:#"name"];
[item setObject:currentSize forKey:#"size"];
[item setObject:currentType forKey:#"type"]
// here is where the magic happens
--> if (([self ifStringExists:currentType] == NO)){
[stories addObject:[item copy]];
}
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(#"found characters in found characters: %#", string);
if ([currentElement isEqualToString:#"data_id"]) {
[currentData_id appendString:string];
} else if ([currentElement isEqualToString:#"sizing_id"]) {
[currentSizing_id appendString:string];
} else if ([currentElement isEqualToString:#"name"]) {
[currentName appendString:string];
} else if ([currentElement isEqualToString:#"size"]) {
[currentSize appendString:string];
}else if ([currentElement isEqualToString:#"type"]) {
[currentType appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
NSLog(#"all done!");
NSLog(#"stories array has %d items", [stories count]);
[newsTable reloadData];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[currentElement release];
[rssParser release];
[stories release];
[item release];
[currentData_id release];
[currentSize release];
[currentSizing_id release];
[currentName release];
[currentType release];
[super dealloc];
}
#end
my .h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "LCYDataBackedTableView.h"
#interface SizingDataViewController : LCYDataBackedTableView {
IBOutlet UITableView * newsTable;
UIActivityIndicatorView * activityIndicator;
CGSize cellSize;
NSXMLParser * rssParser;
NSMutableArray * stories;
NSMutableArray * newStories;
NSMutableArray *filteredStories;
NSString *l_uri;
NSString *myId;
NSString *idName;
BOOL *uploaded;
BOOL isFiltered;
NSIndexPath *indexPaath;
NSMutableDictionary * item;
NSString * currentElement;
NSMutableString * currentData_id, * currentSizing_id, * currentType, * currentName, * currentSize;
NSDictionary *data, *data1, *data2, *data3, *data4;
}
- (void)parseXMLFileAtURL:(NSString *)URL;
-(void)lastChance;
-(BOOL)ifStringExists:(NSString *)stringSentToCheck;
-(void)lastChance;
#end
Where you have the code [stories addObject:[item copy]]; in your parser delegate callback, don't just blindly add the new item - check if it exists already:
if (![stories containsObject:item]) {
[stories addObject:item copy];
}
Then you won't have duplicates at all.
You don't strictly need to copy item because you're creating a new one each time you start a new element. Also, if you don't define 'duplicate' as a full match to the entire dictionary then you will need to write your own contains type method which iterates the array and check the parts of each dictionary that you're interested in.

iOS - How do I add search bar function to this array?

can someone please tell me how to add the search function to an array that contains the titles of rss news links that i have gathered using the xml parser in Xcode 4.6.2 here in the following code? All i basically want is to be able to go to the search bar in my viewcontroller whilst in the simulator or app, and be able to search through the different rss headlines which fill the tableview cell in the ns url array i have here in the code.
//
#import "SocialMasterViewController.h"
#import "SocialDetailViewController.h"
#interface SocialMasterViewController () {
NSXMLParser *parser;
NSMutableArray *feeds;
NSMutableDictionary *item;
NSMutableString *title;
NSMutableString *link;
NSString *element;
NSMutableArray *totalStrings;
NSMutableArray *filteredStrings;
BOOL isFiltered;
}
#end
#implementation SocialMasterViewController
-(void)gotosharing {
UIStoryboard *sharingStoryboard = [UIStoryboard storyboardWithName:#"Sharing" bundle:nil];
UIViewController *initialSharingVC = [sharingStoryboard instantiateInitialViewController];
initialSharingVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;
[self presentViewController:initialSharingVC animated:YES completion:nil];
}
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.mySearchBar.delegate = self;
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
feeds = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"http://rssmix.com/u/3747019/rss.xml"
];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table View
// table view and my data source's and delegate methods......
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [[feeds objectAtIndex:indexPath.row] objectForKey: #"title"];
return cell;
static NSString *CellIdentifier =#"Cell";
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
element = elementName;
if ([element isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc] init];
title = [[NSMutableString alloc] init];
link = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"item"]) {
[item setObject:title forKey:#"title"];
[item setObject:link forKey:#"link"];
[feeds addObject:[item copy]];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([element isEqualToString:#"title"]) {
[title appendString:string];
} else if ([element isEqualToString:#"link"]) {
[link appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[self.tableView reloadData];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *string = [feeds[indexPath.row] objectForKey: #"link"];
[[segue destinationViewController] setUrl:string];
}
}
#end
btw this is my masterviewcontroller.m file code
Looking forward to ur response guys :)
Anytime your search bar changes you want to update the contents of the table view.
So, first you filter the url strings then update tableView by reloading the data.
1) Make the calls when search bar changes:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[self filterURLsWithSearchBar:searchText];
[self.myTableView reloadData];
}
2) filter the strings you want to show
- (void)filterURLsWithSearchBar:(NSString *)searchText
{
[filteredStrings removeAllObjects];
for (NSString *rssUrl in totalStrings)
{
NSComparisonResult result = [rssUrl compare:searchText
options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)
range:[rssUrl rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)]];
if (result == NSOrderedSame) {
[self.filteredStrings addObject:rssUrl];
}
}
}
3) reload table data (needs to change the # of rows and the datasource)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self.mySerchBar.text isEqualToString:#""] || self.mySearchBar.text == NULL) {
return totalStrings.count;
}
else {
return filteredStrings.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"UITableViewCell"];
}
if ([self.mySearchBar.text isEqualToString:#""]|| self.mySearchBar.text == NULL)
{
cell.textLabel.text = [totalStrings objectAtIndex:[indexPath row]];
}
else {
cell.textLabel.text = [filteredStrings objectAtIndex:[indexPath row]];
}
return cell;
}

Youtube thumbnail from channel rss feed?

I am trying to load a youtube channel's feed into a uitableview with an rss feed. I need this to display the thumbnail from the individual videos. I can only find this using the gdata client which does not work. Here is the code I have so far:
Videos.h:
#import <UIKit/UIKit.h>
#interface Videos : UITableViewController<NSXMLParserelegate>{
IBOutlet UITableView * newsTable;
UIActivityIndicatorView * activityIndicator;
CGSize cellSize;
NSXMLParser * rssParser;
NSMutableArray * stories;
// a temporary item; added to the "stories" array one at a time, and cleared for the next one
NSMutableDictionary * item;
// it parses through the document, from top to bottom...
// we collect and cache each sub-element value, and then save each item to our array.
// we use these to track each current item, until it's ready to be added to the "stories" array
NSString * currentElement;
NSMutableString * currentTitle, * currentDate, * currentSummary, * currentLink;
}
- (void)parseXMLFileAtURL:(NSString *)URL;
#end
Videos.m
#import "Videos.h"
#import "AppDelegate.h"
#implementation Videos
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.tabBarItem.image = [UIImage imageNamed:#"clapboard#2x.png"];
}
return self;
}
- (void)viewDidLoad {
// Add the following line if you want the list to be editable
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [stories count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
// Set up the cell
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
cell.textLabel.text=[[stories objectAtIndex: storyIndex] objectForKey: #"title"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: #"link"];
NSLog(#"%#",stories );
// clean up the link - get rid of spaces, returns, and tabs...
storyLink = [storyLink stringByReplacingOccurrencesOfString:#" " withString:#""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:#"\n" withString:#""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:#" " withString:#""];
// open in Safari
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if ([stories count] == 0) {
NSString * path = #"https://youtube.com/rss/user/TheGruenebergBrother/videos.rss";
[self parseXMLFileAtURL:path];
}
cellSize = CGSizeMake([newsTable bounds].size.width, 60);
}
- (void)viewWillDisappear:(BOOL)animated {
}
- (void)viewDidDisappear:(BOOL)animated {
}
#pragma mark - parseing_Delegate_methods
- (void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(#"found file and started parsing");
}
- (void)parseXMLFileAtURL:(NSString *)URL
{
stories = [[NSMutableArray alloc] init];
//you must then convert the path to a proper NSURL or it won't work
NSURL *xmlURL = [NSURL URLWithString:URL];
// here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
// this may be necessary only for the toolchain
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[rssParser setDelegate:self];
// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString * errorString = [NSString stringWithFormat:#"Unable to download story feed from web site (Error code %i )", [parseError code]];
NSLog(#"error parsing XML: %#", errorString);
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//NSLog(#"found this element: %#", elementName);
currentElement = [elementName copy];
if ([elementName isEqualToString:#"item"]) {
// clear out our story item caches...
item = [[NSMutableDictionary alloc] init];
currentTitle = [[NSMutableString alloc] init];
currentDate = [[NSMutableString alloc] init];
currentSummary = [[NSMutableString alloc] init];
currentLink = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//NSLog(#"ended element: %#", elementName);
if ([elementName isEqualToString:#"item"]) {
// save values to an item, then store that item into the array...
[item setObject:currentTitle forKey:#"title"];
[item setObject:currentLink forKey:#"link"];
[item setObject:currentSummary forKey:#"summary"];
[item setObject:currentDate forKey:#"date"];
[stories addObject:[item copy]];
NSLog(#"adding story: %#", currentTitle);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(#"found characters: %#", string);
// save the characters for the current item...
if ([currentElement isEqualToString:#"title"]) {
[currentTitle appendString:string];
} else if ([currentElement isEqualToString:#"link"]) {
[currentLink appendString:string];
} else if ([currentElement isEqualToString:#"description"]) {
[currentSummary appendString:string];
} else if ([currentElement isEqualToString:#"pubDate"]) {
[currentDate appendString:string];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
NSLog(#"all done!");
NSLog(#"stories array has %d items", [stories count]);
[newsTable reloadData];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[currentElement release];
[rssParser release];
[stories release];
[item release];
[currentTitle release];
[currentDate release];
[currentSummary release];
[currentLink release];
[super dealloc];
}
#end
Also where should the code go, and what is the code?
Thanks
there is a thumbnail url,
http://img.youtube.com/vi/VIDEOIDHERE/0.jpg
http://img.youtube.com/vi/VIDEOIDHERE/1.jpg
http://img.youtube.com/vi/VIDEOIDHERE/2.jpg
http://img.youtube.com/vi/VIDEOIDHERE/3.jpg
will fetch you the thumbnail for any video. The number represents the quality, zero being the highest. E.g:
http://img.youtube.com/vi/F2Jko4Ipdrs/0.jpg

Resources