Display Images using RSS Feed in Objective C - objective-c

I want to display images from the url
RSS Feed
I am using table view controller in my Objective c project..I am able to display text and links perfectly but not able to display images from the Feed url
I am using the following code
**TableViewController.h**
#import <UIKit/UIKit.h>
#interface TableViewController : UITableViewController <NSXMLParserDelegate>
#property (strong, nonatomic) IBOutlet UITableView *TableView;
#end
TableViewController.m
#import "TableViewController.h"
#import "ViewController.h"
#interface TableViewController (){
NSXMLParser *parser;
NSMutableArray *feeds;
NSMutableDictionary *item;
NSMutableString *title;
NSMutableString *link;
NSString *element;
NSString *imageType;
NSString *imageUrl;
}
#end
#implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
feeds=[[NSMutableArray alloc ] init];
NSURL *url = [NSURL URLWithString:#"https://www.nasa.gov/rss/dyn/breaking_news.rss"];
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 data source
- (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"];
// cell.imageView.image= [[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];
}
if ([element isEqualToString:#"enclosure"]) {
imageType = [attributeDict objectForKey:#"type"];
imageUrl = [attributeDict objectForKey:#"url"];
}
}
-(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"];
[item setObject:imageType forKey:#"imageType"];
[item setObject:imageUrl forKey:#"imageUrl"];
[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
Please help me to display images I am stuck with this.Thanks

Use this way :
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"identifier"];
UIImageview imgView = [[UIImageView alloc] initWithFrame:CGRectMake(150, 0, 48, 48)];
imgView.tag = 100;
//ssame way create a label
UILabel titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
titlelabel.tag = 102
[cell.contentview addsubview:imgview];
[cell.contentview addsubview:titlelabel];
}
UIImageview mImgView = (uiimageview *)[cell viewwithtag:100];
UILabel mLabel = (uilabel*)cell viewwithtag:102];
//set data
mlabel = //your label
mimgviw.imge = imageurl

Just put this line to your UITableViewCell
NSString *imgUrl = [[feeds objectAtIndex:indexPath.row] objectForKey:#"imageUrl"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]]];
cell.imageView.image = image;

Related

Objective-C Pull to Refresh

I'm trying to implement a pull-to-refresh feature on my RSS feed table. The list pulls normally when loading the app, but I essentially need to replicate that for the pull-down.
Could anyone help as to why the code isn't working?
#import "RSSTableViewController.h"
#import "RSSDetailViewController.h"
#interface RSSTableViewController () {
NSXMLParser *parser;
NSMutableArray *feeds;
NSMutableDictionary *item;
NSMutableString *title;
NSMutableString *link;
NSString *element;
}
#end
#implementation RSSTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// RSS Settings
feeds = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"http://external.example.co.uk/newpost/example.rss"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
refresh.attributedTitle = [[NSAttributedString alloc] initWithString:#"Pull to Refresh"];
[refresh addTarget:self
action:#selector(refreshView:)
forControlEvents:UIControlEventValueChanged];
self.refreshControl = refresh;
}
- (void)refreshView:(UIRefreshControl *)refresh {
refresh.attributedTitle = [[NSAttributedString alloc] initWithString:#"Refreshing news feed..."];
// Refresh Logic
NSURL *url = [NSURL URLWithString:#"http://external.example.co.uk/newpost/example.rss"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
// Set the timestamp
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM d, h:mm a"];
NSString *lastUpdated = [NSString stringWithFormat:#"Last updated: %#",
[formatter stringFromDate:[NSDate date]]];
refresh.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
[refresh endRefreshing];
[self.tableView reloadData];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[refreshView endRefreshing]; //'Use of undeclared identifier 'refresh view'//
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the 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)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
Anyone got any ideas?
Code works fine
Needed to remove the line in parserDidEndDocument with the error.
I then had to add [feeds removeAllObjects] under the //Refresh Logic line to clear the current table contents.
Thanks guys.

Search in a NSMutableArray

Hello how I can search in tableView with this?
I use XML parse for NSMutableArray. Gives error when I want to search. I want to make a detailed search for the cell.
http://i.hizliresim.com/blvZQj.png
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
}
// FirstViewController.h
//
//
//
// Copyright (c) 2015 Serkan. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "Haber.h"
#interface FirstViewController : UITableViewController<NSXMLParserDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate>
{
NSXMLParser *parser;
NSMutableArray *haberlistesi;
NSMutableArray *searchArray;
Haber *haber;
__weak IBOutlet UITableView *table;
NSString *currentElement;
}
#property IBOutlet UISearchBar *SearchBar;
#end
//
// FirstViewController.m
//
//
//
// Copyright (c) 2015 Serkan. All rights reserved.
//
#import "FirstViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize SearchBar;
- (void)viewDidLoad
{
[super viewDidLoad];
haberlistesi = [[NSMutableArray alloc] init];
searchArray = [[NSMutableArray alloc] initWithArray:haberlistesi];
// Hide the search bar until user scrolls up
CGRect newBounds = [[self tableView] bounds];
newBounds.origin.y = newBounds.origin.y + SearchBar.bounds.size.height;
[[self tableView] setBounds:newBounds];
// Initialize the filteredCandyArray with a capacity equal to the candyArray's capacity
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
self.refreshControl.backgroundColor = [UIColor purpleColor];
self.refreshControl.tintColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:#selector(getXMLData)
forControlEvents:UIControlEventValueChanged];
// Initialize the refresh control.
[self performSelectorInBackground:#selector(getXMLData) withObject:nil];
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
// Reload the table
[[self tableView] reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [haberlistesi count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Haber *temp = [haberlistesi objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"mycell"];
NSString *str =[NSString stringWithFormat:#"%#%#",temp.al,temp.sat];
cell.textLabel.text = str;
cell.detailTextLabel.text = temp.baslik;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor clearColor];
//tableView.backgroundColor = [UIColor clearColor]; //tableview arkakısmını transparan yapar.
//cell.textLabel.text = [searchArray objectAtIndex:indexPath.row];
return cell;
}
-(void)getXMLData
{
NSString *strURL = #"http://www.serkanuyanik.com/eksperlerimiz.xml";
NSURL *url = [NSURL URLWithString:strURL];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
haberlistesi = [[NSMutableArray alloc] init];
parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
[self performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
currentElement = elementName;
if ([elementName isEqualToString:#"record"]) {
haber = [[Haber alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([currentElement isEqualToString:#"sehir"])
[haber.al appendString:[string stringByReplacingOccurrencesOfString:#"\n" withString:#""]];
if ([currentElement isEqualToString:#"tarih"])
[haber.baslik appendString:[string stringByReplacingOccurrencesOfString:#"\n" withString:#""]];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"record"])
{
[haberlistesi addObject:haber];
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
[table reloadData];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *address = haber.al;
NSString *mapString = [NSString stringWithFormat:#"http://maps.apple.com/?=%#", address];
NSURL *urlMapScheme = [NSURL URLWithString:mapString];
[[UIApplication sharedApplication] openURL:urlMapScheme];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)reloadData
{
// Reload table data
[self.tableView reloadData];
// End the refreshing
if (self.refreshControl) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM d, h:mm a"];
NSString *title = [NSString stringWithFormat:#"Son Güncelleme: %#", [formatter stringFromDate:[NSDate date]]];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:[UIColor whiteColor]
forKey:NSForegroundColorAttributeName];
NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:title attributes:attrsDictionary];
self.refreshControl.attributedTitle = attributedTitle;
[self.refreshControl endRefreshing];
}
}
#end
You this code for searching :
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSArray * searchResults = [haberlistesi filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: #"al CONTAINS[c] %# OR baslik CONTAINS[c] %#", searchedString, searchedString]];
//Use this searchResults array as DataSource for your table view and reload the table view, For instance:
haberlistesi = [searchResults mutableCopy];
[self.tableView reloadData];
}
Happy Coding..:)

Tableview segue not working?

Yesterday I was working on a project and I came across this error. Kept me up all night! Still no answer that fixes MY ERROR! So what happens is when i tap my cell its not going to next view controller. I made prototype and everything. So before it was giving be a signal sgbart or something and I fixed it with adding this.
This was in -(void)viewDidLoad
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier];
The error was coming up here -
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Now all that is fixed. Now whenever i go and click a cell its not working.
It is a RSS reader project. Here is the full code.
//
// AppMain.m
// fcffv
//
// Created by Ajay Venkat on 6/09/2014.
// Copyright (c) 2014 AJTech. All rights reserved.
//
#import "AppMain.h"
#import "AppDetail.h"
#interface AppMain () {
NSXMLParser *parser;
NSMutableArray *feeds;
NSMutableDictionary *item;
NSMutableString *title;
NSMutableString *link;
NSString *element;
}
#end
#implementation AppMain
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad {
[super viewDidLoad];
static NSString *CellIdentifier = #"Cell";
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier];
feeds = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"http://bountyboulevardss.eq.edu.au/?cat=3&feed=rss2"];
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
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return feeds.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier 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
Thank you guys for helping.
By the way I have done all the re search I could do and all leaves me in failure and even more error so please try help me guys.
Also I am new to Objective-C.
Thank you to people who take the time to help me.
This is a project important to a school.
Do you implement didSelectRowatIndex method ? And set delegate ?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
Cheers S.

Passing Information in Segue Using StoryBoards

I have been dabbling with an iOS app for a little time and don't really get too much time to invest into it. I am now banging my head against a wall as I cannot figure out how to get this working or what I have not configured correctly...I am trying to get the bodytext that is referenced in the NewsTableViewController to load into the textView on the NewsView Controller. At present only the title updates and the textview just displays the lorum ipsum text.
My understanding is that because I can see the info in the NSLog and if i try to put news body text in the title of the pushed view it displays in the title - my thinking is that I have failed to define the view but as I say I just can't see it! Here's what I have anyway...
This is the table that loads the data to the first view from a xml file
//
// NewsTableViewController.h
//
#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
#interface NewsTableViewController : UITableViewController
{
IBOutlet UITableView *newsTable;
CGSize cellSize;
NSXMLParser *rssParser;
NSMutableArray *stories;
NSMutableDictionary *item;
NSString *currentElement;
NSMutableString *currentName, *currentTitle, *currentDated, *currentBodyText;
}
- (UITableViewCell *) getCellContentView:(NSString *)MyIdentifier;
#end
Implemntation of the the code
//
// NewsTableViewController.m
//
#import "NewsTableViewController.h"
#import "NewsViewController.h"
#interface NewsTableViewController ()
#end
#implementation NewsTableViewController
dispatch_queue_t myQueue;
-(void) showHUD{
MBProgressHUD *HUD;
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
//HUD.delegate = self;
HUD.labelText = #"News Loading";
HUD.detailsLabelText = #"please wait...";
HUD.square = YES;
HUD.dimBackground = YES;
[HUD showWhileExecuting:#selector(parserStart) onTarget:self withObject:nil animated:YES];
//dispatch_async(dispatch_get_main_queue(), ^ {[self parserStart]; });
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
//NSLog(#"View Did Appear");
myQueue = dispatch_queue_create("com.xxxxxxxxxxx.xxxxxxxxxx",NULL);
dispatch_async(dispatch_get_main_queue(), ^ {[self showHUD]; });
}
- (void) parserStart {
//Insert a small delay for testing purposes
//[NSThread sleepForTimeInterval:2];
if ([stories count] == 0) {
NSString *path = #"http://xxx.xxxxxxxxxxx.xxx/xxxxxx/xxxxxxx.xml";
[self parseXMLFileAtURL:path];
//[path release];
}
cellSize = CGSizeMake([newsTable bounds].size.width, 60);
[self.tableView reloadData];
}
- (void)parseXMLFileAtURL:(NSString *)URL {
if (stories) {
//[stories release];
stories = nil;
}
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)parserDidStartDocument:(NSXMLParser *)parser {
//NSLog(#"found file and started parsing");
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString * errorString = [NSString stringWithFormat:#"Unable to download the news 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);
//if (currentElement) {
//[currentElement release];
//currentElement = nil;
//}
currentElement = [elementName copy];
if ([elementName isEqualToString:#"article"]) {
// clear out our story item caches...
item = [[NSMutableDictionary alloc] init];
currentName = [[NSMutableString alloc] init];
currentTitle = [[NSMutableString alloc] init];
currentDated = [[NSMutableString alloc] init];
currentBodyText = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(#"found characters: %#", string);
// save the characters for the current item...
if ([currentElement isEqualToString:#"article"]) {
[currentName appendString:string];
} else if ([currentElement isEqualToString:#"title"]) {
[currentTitle appendString:string];
} else if ([currentElement isEqualToString:#"dated"]) {
[currentDated appendString:string];
} else if ([currentElement isEqualToString:#"bodytext"]) {
[currentBodyText appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//NSLog(#"ended element: %#", elementName);
if ([elementName isEqualToString:#"article"]) {
// save values to an item, then store that item into the array...
[item setObject:currentName forKey:#"article"];
[item setObject:currentTitle forKey:#"title"];
[item setObject:currentDated forKey:#"dated"];
[item setObject:currentBodyText forKey:#"bodytext"];
[stories addObject:[item copy]];
//NSLog(#"adding story: %#", currentName);
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
}
- (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)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [stories count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
cell = [self getCellContentView:MyIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UILabel *lblTitle = (UILabel *)[cell viewWithTag:101];
UILabel *lblDate = (UILabel *)[cell viewWithTag:102];
UILabel *lblBodyText = (UILabel *)[cell viewWithTag:103];
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
//NSString *articleValue = [[stories objectAtIndex: storyIndex] objectForKey: #"article"];
NSString *titleValue = [[stories objectAtIndex: storyIndex] objectForKey: #"title"];
NSString *datedValue = [[stories objectAtIndex: storyIndex] objectForKey: #"dated"];
NSString *bodytextValue = [[stories objectAtIndex: storyIndex] objectForKey: #"bodytext"];
lblTitle.text = titleValue;
lblDate.text = datedValue;
lblBodyText.text = bodytextValue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"NewsSegue"]) {
// note that "sender" will be the tableView cell that was selected
UITableViewCell *cell = (UITableViewCell*)sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NewsViewController *nvc = [segue destinationViewController];
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
nvc.title = [[stories objectAtIndex: storyIndex] objectForKey: #"title"];
nvc.textView.text = [[stories objectAtIndex: storyIndex] objectForKey: #"bodytext"];
//nvc.textView.text = [self getDataToPass:storyIndex.row];
// hide the tabBar Controller
nvc.hidesBottomBarWhenPushed = YES;
//NSLog(#"Article : %#", [[stories objectAtIndex:storyIndex] objectForKey: #"article"]);
NSLog(#"Title : %#", [[stories objectAtIndex:storyIndex] objectForKey: #"title"]);
NSLog(#"Dated : %#", [[stories objectAtIndex:storyIndex] objectForKey: #"dated"]);
NSLog(#"BodyText : %#", [[stories objectAtIndex:storyIndex] objectForKey: #"bodytext"]); }
}
- (void)dealloc {
}
#end
And now the view I am pushing onto...
//
// NewsViewController.h
//
#import <UIKit/UIKit.h>
#class NewsViewController;
#interface NewsViewController : UIViewController {
IBOutlet UITextView* textView;
}
#property (nonatomic, retain) IBOutlet UITextView* textView;
#end
And then the the implementation file for this view.
//
// NewsViewController.m
//
#import "NewsViewController.h"
#import "NewsTableViewController.h"
#interface NewsViewController ()
#end
#implementation NewsViewController
#synthesize textView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.textView = self.title;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
EDIT: From what I understand this part of the Segue is where I am sending the information from within the sending part of the code attached to the parser:
nvc.title = [[stories objectAtIndex: storyIndex] objectForKey: #"title"];
nvc.textView.text = [[stories objectAtIndex:storyIndex] objectForKey: #"bodytext"];
If I set the bodytext as the title the information displays and thus why I think there's something that isn't correct with the textview, it is this point that I am stuck?
Any help would be appreciated as I am really at the point I don't know what's going wrong!!! I'm actually hoping it's glaringly obvious what I have missed! Thanks for looking.
I added the following to my prepareforsegue
[nvc setTextFieldContentText:[[stories objectAtIndex:storyIndex] objectForKey: #"bodytext"]];
And then in the View did load in the receiving view
[textView setText:[self textFieldContentText]];
And obviously setting the property in the receiving view header file
#property NSString* textFieldContentText;
Thanks to all those that took the time to look and help.
I am a bit confused what this line of code is attempting to accomplish:self.textView = self.title;
But regardless, I think your issue is that you are attempting to set the text for a view that does not exist yet. Try creating an NSString (say textViewString) in your News View Controller and set that in your prepareForSegue and then in your viewDidLoad or viewWillAppear do self.textView.text = self.textViewString;
Need to set textView's text property. Try this:
self.textView.text = self.title;

I m trying to Retrieve the data from XML File into an IPhone application

The XML File Which i used is :
<note>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<URL>http://192.168.1.75/one.png</URL>
</note>
In this XML I have retrieve the text but i failed to display the image from the link in the XML File.
I want to display the image in table cell.I have given the coding which i used as follows.
In RootViewController.m
#implementation RootViewController
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [appDelegate.books count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
Book *aBook = [appDelegate.books objectAtIndex:indexPath.row];
cell.text = aBook.heading;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Set up the cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic -- create and push a new view controller
if(bdvController == nil)
bdvController = [[BookDetailViewController alloc] initWithNibName:#"BookDetailView" bundle:[NSBundle mainBundle]];
Book *aBook = [appDelegate.books objectAtIndex:indexPath.row];
bdvController.aBook = aBook;
[self.navigationController pushViewController:bdvController animated:YES];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to add the Edit button to the navigation bar.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
appDelegate = (XMLAppDelegate *)[[UIApplication sharedApplication] delegate];
self.title = #"Books";
}
XMLAppDelegate.m:
#implementation XMLAppDelegate
#synthesize window;
#synthesize navigationController, books;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSURL *url = [[NSURL alloc] initWithString:#"http://192.168.1.75/second.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];
}
Book.m:
#synthesize heading, body, URL;
XMLParser.m:
#implementation XMLParser
- (XMLParser *) initXMLParser {
[super init];
appDelegate = (XMLAppDelegate *)[[UIApplication sharedApplication] delegate];
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:#"note"]) {
appDelegate.books = [[NSMutableArray alloc] init];
}
if([elementName isEqualToString:#"note"]) {
}
NSLog(#"Processing Element: %#", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];
NSLog(#"Processing Value: %#", currentElementValue);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:#"note"]) {
[appDelegate.books addObject:aBook];
[aBook release];
aBook = nil;
}
if([elementName compare:#"heading"]==0) {
aBook.heading=currentElementValue;
}
if([elementName compare:#"body"]==0) {
aBook.body=currentElementValue;
}
if([elementName compare:#"URL"]==0) {
aBook.URL=currentElementValue;
}
else
[aBook setValue:currentElementValue forKey:elementName];
[currentElementValue release];
currentElementValue = nil;
}
BOOk DetailViewController.m:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.section == 0)
{
cell.text=aBook.heading;
}
if(indexPath.section == 1)
{
cell.text=aBook.body;
}
if(indexPath.section == 2)
{
cell.image=aBook.URL;
}
return cell;
}
- (NSString *)tableView:(UITableView *)tblView titleForHeaderInSection:(NSInteger)section {
NSString *sectionName = nil;
switch(section)
{
case 0:
sectionName = [NSString stringWithString:#"Title"];
break;
case 1:
sectionName = [NSString stringWithString:#"Author"];
break;
case 2:
sectionName = [NSString stringWithString:#"Summary"];
break;
}
return sectionName;
}
cell.image=aBook.URL;
An URL does not an image make. (Hint: create an UIImage from the contents of the URL.)
you have to get image from URL. you can not display image directly from url.
NSData *data = [NSData dataWithContentsOfURL : url];
UIImage *image = [UIImage imageWithData: data];
this code will help you.