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..:)
Related
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;
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.
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 am giving my entire code below if that helps anyway.....
#import "ContentViewController.h"
#import "ContentViewController.h"
#import "MediaPlayerViewController.h"
#import "TwitterViewController.h"
#import "YoutubeViewController.h"
#implementation ContentViewController
#synthesize imageView;
#synthesize imageView1;
#synthesize tableView;
#synthesize navigationController;
#synthesize toolBar;
#synthesize item;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - XMLParser Delegate
-(void)parseXMLFileAtURL:(NSString *)URL{
NSURL *xmlURL = [NSURL URLWithString:URL];
rssParser = [[NSXMLParser alloc]initWithContentsOfURL:xmlURL];
[rssParser setDelegate:self];
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
NSLog(#"Parsed");
}
-(void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(#"Found file and started parsing");
}
-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSString *errorString = [NSString stringWithFormat:#"Unable to download feed from website (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:#"channel"]) {
rssElement = [[NSMutableDictionary alloc]init];
title = [[NSMutableString alloc]init];
link = [[NSMutableString alloc]init];
description = [[NSMutableString alloc]init];
copyright = [[NSMutableString alloc]init];
}
}
-(void)parser: (NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:#"channel"]) {
[rssElement setObject:title forKey:#"title"];
[rssElement setObject:link forKey:#"link"];
[rssElement setObject:description forKey:#"description"];
[rssElement setObject:copyright forKey:#"copyright"];
[item addObject:[rssElement copy]];
NSLog(#"adding stories %#", title);
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if ([currentElement isEqualToString:#"title"]) {
[title appendString:string];
}else if ([currentElement isEqualToString:#"link"]) {
[link appendString:string];
}else if ([currentElement isEqualToString:#"description"]) {
[description appendString:string];
}else if ([currentElement isEqualToString:#"copyright"]) {
[copyright appendString:string];
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
NSLog(#"all done");
NSLog(#"item array has %d items", [item count]);
[tableView reloadData];
NSLog(#"Finished Parsing");
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
/* Add Segmented Controller */
if (segmentedControl == nil) {
segmentedControl = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:#"Video", #"Images", #"Audio", nil]];
}
[segmentedControl setFrame:CGRectMake(55.0, 47.0, 180.0, 31.0)];
[segmentedControl setSegmentedControlStyle:UISegmentedControlStyleBar];
[segmentedControl setWidth:70.0 forSegmentAtIndex:0];
[segmentedControl setWidth:70.0 forSegmentAtIndex:1];
[segmentedControl setWidth:70.0 forSegmentAtIndex:2];
[segmentedControl addTarget:self
action:#selector(segmentClick:)
forControlEvents:UIControlEventValueChanged];
[segmentedControl setMomentary:YES];
// [[[segmentedControl subviews]objectAtIndex:0]setTintColor:[UIColor blackColor]];
[self.view addSubview:segmentedControl];
/* Add Image View */
imageView1.image = [UIImage imageNamed:#"Harry.png"];
/* Add Page Control */
pageControl = [[UIPageControl alloc] init];
pageControl.frame = CGRectMake(120.0, 250.0, 100.0 ,10.0);
pageControl.numberOfPages = 5;
pageControl.currentPage = 0;
[self.view addSubview:pageControl];
/* Customize Table View */
tableView.backgroundColor = [UIColor clearColor];
imageView.image = [UIImage imageNamed:#"gradientBackground.png"];
item = [[NSMutableArray alloc]init];
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Video";
[self parseXMLFileAtURL:path];
[tableView reloadData];
NSLog(#"Returned %#", item);
}
headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(10.0, 270.0, 300.0, 14.0)];
headerLabel.text = #"Latest Videos";
headerLabel.textColor = [UIColor whiteColor];
headerLabel.backgroundColor = [UIColor clearColor];
[self.view addSubview:headerLabel];
}
/* Assign control to Segment Controller */
-(void)segmentClick:(UISegmentedControl *)segmentControl {
if (segmentControl.selectedSegmentIndex == 1){
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Image";
[self parseXMLFileAtURL:path];
[tableView reloadData];
headerLabel.text = #"Latest Images";
NSLog(#"Returned %#",item);
}
}
else if (segmentedControl.selectedSegmentIndex == 2){
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Audio";
[self parseXMLFileAtURL:path];
[tableView reloadData];
headerLabel.text = #"Latest Audios";
NSLog(#"Returned no items");
// [[[segmentedControl subviews]objectAtIndex:2]setTintColor:[UIColor blackColor]];
}
}
else {
if ([item count] == 0) {
path = #"http://172.19.58.172/Android/GetApprovedList.php?ip=172.19.58.172&type=Video";
[self parseXMLFileAtURL:path];
[tableView reloadData];
headerLabel.text = #"Latest Videos";
NSLog(#"Returned %#", item);
}
// [[[segmentedControl subviews]objectAtIndex:0]setTintColor:[UIColor blackColor]];
}
}
#pragma mark Table View Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"this is returned %#", item);
return item.count;
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
int feed = [indexPath indexAtPosition:[indexPath length] - 1];
cell.textLabel.text = [[item objectAtIndex:feed]objectForKey:#"title"];
cell.detailTextLabel.text = [[item objectAtIndex:feed]objectForKey:#"description"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *moviePath = [self.item objectAtIndex:indexPath.row];
NSURL *movieURL = [NSURL fileURLWithPath:moviePath];
NSLog(#"Item has %#", movieURL);
playerController = [[MPMoviePlayerController alloc]initWithContentURL:movieURL];
[playerController play];
// MediaPlayerViewController *mediaView = [[MediaPlayerViewController alloc]initWithNibName:#"MediaPlayerViewController" bundle:nil];
// [self presentModalViewController:mediaView animated:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0) {
shareAlert = [[UIActionSheet alloc]initWithTitle:#"Share to" delegate:self cancelButtonTitle:#"Cancel"
destructiveButtonTitle:#"Facebook" otherButtonTitles:#"Twitter", nil];
[shareAlert showInView:self.view];
}
else if (buttonIndex == 1){
NSLog(#"button 2");
}
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) {
TwitterViewController *twitterController = [[TwitterViewController alloc]initWithNibName:#"TwitterViewController" bundle:nil];
[self presentModalViewController:twitterController animated:YES];
}
}
-(void)moviePlayBackDidFinish:(NSNotification *)notification{
MPMoviePlayerController *moviePlayerController = [notification object];
[moviePlayerController.view removeFromSuperview];
[moviePlayerController release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Changed didSelectRow method like following:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
moviePath = [[item objectAtIndex:indexPath.row]objectForKey:#"link"];
NSLog(#"moviepath has %#", moviePath);
movieURL = [NSURL URLWithString:moviePath];
NSLog(#"movieURL has %#", movieURL);
viewController = [[MPMoviePlayerViewController alloc]initWithContentURL:movieURL];
[self presentMoviePlayerViewControllerAnimated:viewController];
viewController.moviePlayer.movieSourceType = MPMovieSourceTypeStreaming;
[playerController play];
viewController = nil;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:viewController];
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
viewController = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:viewController];
if ([viewController respondsToSelector:#selector(setFullscreen:animated:)])
{
[viewController.view removeFromSuperview];
}
}
Now, on selecting any row a blank screen is coming and the application gets stuck there. Video is not played
Any help in this regard is appreciated.
Thanks in advance.
By looking at you code what i can tell you is that you dont have to reallocate your item object.
If you have allocated your item object somewhere in the class and stored the values in it then do not reallocate it again as you did here:
item = [[NSMutableArray alloc]init];
NSString *moviePath = [item objectAtIndex:indexPath.row];
by reallocating it you are allocating a new memory to it and in the new memory there is no objects present.
you are allocating new memory to your array by : item = [[NSMutableArray alloc]init]; . It means NO objects in it right now. And you are trying to access it by NSString *moviePath = [item objectAtIndex:indexPath.row]; where there is NO object at indexPath.row thats why it crashed.
There was actually nothing wrong with the code for playing video. The error was in the code for parsing and retrieving the rss feed which eventually was giving me wrong names of the videos. hence, videos were not playing.
The parsing code is Parsing attributes with same name but in different fields in iOS
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.