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
Related
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..:)
I have a simple view which has been successfully loading a table of data from CoreData for the last 18 months. It even works now on devices that have been upgraded to IOS 7. But when I upgraded to Xcode5 and run through the IOS7 3.5inch retina simulator my table is always empty. I have pasted my code below and I can confirm that the fetchRequests are returning the data because I can see this in the NSLog outputs. But why has be table stopped populating the cells?
I feel really stupid because I just cannot figure this one out…
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"listData count in numberOFRowsInSection is: %i", listData.count);
return [self.listData count];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
Sessions *info = [_fetchedResultsController objectAtIndexPath:indexPath];
NSLog(#"info content is: %#", info.sport);
//Format cell data ready to be displayed
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"EE, dd LLL yyyy"];
NSString *dateString = [dateFormat stringFromDate:info.date];
NSNumber *dist1Nbr = info.dist1;
int dist1Int = [dist1Nbr integerValue];
float distIntKorM = ([dist1Nbr integerValue])/1000;
NSString *dist1StrMeters = [[NSString alloc] initWithFormat:#"%i", dist1Int];
NSString *dist1StrKorM = [[NSString alloc] initWithFormat:#"%.01f", distIntKorM];
//Select image to display
if ([info.sport isEqualToString:#"Run"]) {
UIImage *image = [UIImage imageNamed:#"trainers-15x10.png"];
cell.imageView.image = image;
cell.textLabel.text = [[NSString alloc] initWithFormat:#"%#: (%#),", dateString, info.sport];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"Type: %#, Dist: %#", info.sessiontype, dist1StrKorM];
NSLog(#"Cell text for Runs shoudl be: %#", cell.textLabel.text);
} else if ([info.sport isEqualToString:#"Other"]) {
UIImage *image = [UIImage imageNamed:#"weights-15x10.png"];
cell.imageView.image = image;
cell.textLabel.text = [[NSString alloc] initWithFormat:#"%#: (%#),", dateString, info.sport];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"Type: %#, Dist: %#", info.sessiontype, dist1StrKorM];
} else if ([info.sport isEqualToString:#"Swim"]) {
UIImage *image = [UIImage imageNamed:#"goggles-15x10.png"];
cell.imageView.image = image;
cell.textLabel.text = [[NSString alloc] initWithFormat:#"%#: (%#),", dateString, info.sport];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"Type: %#, Dist: %#m", info.sessiontype, dist1StrMeters];
NSLog(#"Cell text for Swims shoudl be: %#", cell.textLabel.text);
} else if ([info.sport isEqualToString:#"Cycle"]) {
UIImage *image = [UIImage imageNamed:#"bike-15x10.png"];
cell.imageView.image = image;
cell.textLabel.text = [[NSString alloc] initWithFormat:#"%#: (%#),", dateString, info.sport];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"Type: %#, Dist: %#", info.sessiontype, dist1StrKorM];
} else if ([info.sport isEqualToString:#"Brick"]) {
UIImage *image = [UIImage imageNamed:#"brick-15x10.png"];
cell.imageView.image = image;
cell.textLabel.text = [[NSString alloc] initWithFormat:#"%#: (%#),", dateString, info.sport];
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"Type: %#, Dist: %#", info.sessiontype, dist1StrKorM];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"editSession";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// this cell backgrond colour alternating works!
UIView *bgColor = [cell viewWithTag:100];
if (!bgColor) {
CGRect frame = CGRectMake(0, 0, 320, 50);
bgColor = [[UIView alloc] initWithFrame:frame];
bgColor.tag = 100;
[cell addSubview:bgColor];
[cell sendSubviewToBack:bgColor];
}
if (indexPath.row % 2 == 0) {
bgColor.backgroundColor = [UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:1.0];
} else {
bgColor.backgroundColor = [UIColor clearColor]; }
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
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 - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
if (_context == nil)
{
_context = [(SGK_T4T_01AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", _context);
}
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1);
} else {
NSLog(#"After fetchedResultsController: %#", _fetchedResultsController);
//NSLog(#"After managedObjectContext: %#", _fetchedResultsController);
}
self.title = #"Sessions";
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[self setListData:nil];
[self setSelectedSession:nil];
[self setSessionSport:nil];
//[self setRecordCount:nil];
[self setFetchedResultsController:nil];
[self setContext:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
SGK_T4T_01AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDiscription = [NSEntityDescription entityForName:#"Sessions" inManagedObjectContext:context];
//NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"refid" ascending:YES];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDiscription];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(#"The fetch request returned an array == nil");
} else {
NSLog(#"The fetch request returned an array!!!");
NSLog(#"objects contents is: %#", objects);
NSLog(#"objects count = %i", [objects count]);
listData = objects;
NSLog(#"listData count = %i", [listData count]);
//NSUInteger *recordCount = [objects count];
recordCount = [objects count];
}
//reload tableView:dataSource from CoreData when view reappears...
if (_context == nil)
{
_context = [(SGK_T4T_01AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", _context);
}
NSError *error1;
if (![[self fetchedResultsController] performFetch:&error1]) {
NSLog(#"Unresolved error %#, %#", error1, [error1 userInfo]);
exit(-1);
} else {
NSLog(#"viewWillAppear: fetchedResultsController: %#", _fetchedResultsController);
}
//end of reload tableView:dataSource from CoreData when view reappears...
[self.tableView reloadData];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//[self setFetchedResultsController:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
//[self setFetchedResultsController:nil];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[_context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
NSError *error = nil;
if (![_context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
[self.tableView reloadData];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
if (type == NSFetchedResultsChangeDelete) {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
NSUInteger index = indexPath.row;
//NSLog(#" Prep4Seg indexPath.row = %u", index);
//NSLog(#" Prep4Seg recordCount = %u", recordCount);
/*
Subtract the row index from the row count to get the correct position in the Array (because I am sorting on date order so tableCell position 0 is position 2 in the Array (if there are 3 only items in the table and array) so if you don't invert the indexPath you end up passing the last item instead of the first or second last item instead of the second and so on...
*/
NSUInteger arrayIndex = (recordCount-index-1);
//NSLog(#" Prep4Seg arrayIndex = %u", arrayIndex);
selectedSession = [listData objectAtIndex:arrayIndex];
//NSLog(#"listData = %#", listData);
//NSLog(#"SelectedSession = %#", selectedSession);
NSNumber *refId = [selectedSession valueForKey:#"refid"];
NSString *refIdToSend = [[NSString alloc] initWithFormat:#"%#", refId];
NSLog(#"Prep4Seg in tableView: refIdToSend = %#", refIdToSend);
if ([segue.identifier isEqualToString:#"editSession"]) {
SGK_T4T_EditSessionDetail *editSessionDetail = segue.destinationViewController;
editSessionDetail.delegate = (id)self;
editSessionDetail.returnFromDatePickerView = [[NSString alloc] initWithFormat:#"no"];
editSessionDetail.recedIndex = refIdToSend;
}
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller is about to start sending change notifications, so prepare the table view for updates.
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller has sent all current change notifications, so tell the table view to process all updates.
[self.tableView endUpdates];
}
And my log output is:
2013-11-09 16:04:04.034 trainForTri copy[6509:a0b] After managedObjectContext: <NSManagedObjectContext: 0xb589bc0>
2013-11-09 16:04:04.036 trainForTri copy[6509:a0b] After fetchedResultsController: <NSFetchedResultsController: 0xb5e2c40>
2013-11-09 16:04:04.040 trainForTri copy[6509:a0b] The fetch request returned an array!!!
2013-11-09 16:04:04.041 trainForTri copy[6509:a0b] objects contents is: (
"<NSManagedObject: 0xb5c8570> (entity: Sessions; id: 0xb5ac970 <x-coredata://B93EE0DE-E6FA-491C-9C8F-23692A36DD0C/Sessions/p1> ; data: <fault>)",
"<NSManagedObject: 0xb5d6320> (entity: Sessions; id: 0xb58a2a0 <x-coredata://B93EE0DE-E6FA-491C-9C8F-23692A36DD0C/Sessions/p2> ; data: <fault>)",
"<NSManagedObject: 0xb5d0370> (entity: Sessions; id: 0xb5dc270 <x-coredata://B93EE0DE-E6FA-491C-9C8F-23692A36DD0C/Sessions/p3> ; data: <fault>)",
"<NSManagedObject: 0xb5e3dd0> (entity: Sessions; id: 0xb5ebcc0 <x-coredata://B93EE0DE-E6FA-491C-9C8F-23692A36DD0C/Sessions/p4> ; data: <fault>)",
"<NSManagedObject: 0xb585e40> (entity: Sessions; id: 0xb5e4e40 <x-coredata://B93EE0DE-E6FA-491C-9C8F-23692A36DD0C/Sessions/p5> ; data: <fault>)"
)
2013-11-09 16:04:04.041 trainForTri copy[6509:a0b] objects count = 5
2013-11-09 16:04:04.042 trainForTri copy[6509:a0b] listData count = 5
2013-11-09 16:04:04.043 trainForTri copy[6509:a0b] viewWillAppear: fetchedResultsController: <NSFetchedResultsController: 0xb5a01e0>
2013-11-09 16:04:04.043 trainForTri copy[6509:a0b] listData count in numberOFRowsInSection is: 5
OK, found the issue with this. Eventually after almost wanting to throw my Macbook out of the window in frustration with Xcode5 I shut everything down and restarted. when I opened Xcode, built and ran my App it lo longer loaded an empty table - it now produced an error which indicated that there was something wrong with my NSFetchedResultsController. I traced it to an issue with the cache not clearing (or not being mutable) - so I removed the cache name and set it to nil and everything is working again. I am not sure if this is an IOS7/Xcode5 issue but it has not been a problem until this upgrade. For anyone searching for a similar fix here is the offending line of code:
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_context sectionNameKeyPath:nil cacheName:#"Root"];
And this is the version that works!
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_context sectionNameKeyPath:nil cacheName:nil];
I hope I'm not the only one ever to struggle with this and therefore just a thickie!
I'm testing my ios app that has a deployment target of 5.0 and a base SDK of 6.1.
Everything works fine in ios 5.0, and ios 5.1, but in ios 6.0 I'm having an issue with inserting a subview at index. The subview is a tableview and the parent view is an uialertview that was created as a special class "UIAlertTableView." The alertview appears, but there appears to be nothing inserted. Before this, I had fixed an autorotation issue of the superview (which is in landscape) because, as it is well known ios 6.0 handles rotation differently, so now my superview appears correctly, but as I said, this alertview pops up with no table now. Am I suppose to be fixing autorotation issues for the tableview as well as the superview? I didn't think this would be necessary since the tableview is not declared in the imported class, is is declared within the parent viewcontroller. Or could this be because of some method that was deprecated in ios 6.0?
/*UIAlertTableView.m (the imported object class)*/
#interface UIAlertView (private)
- (void)layoutAnimated:(BOOL)fp8;
#end
#implementation UIAlertTableView
#synthesize tableWidth;
#synthesize tableHeight;
#synthesize lowestView;
#synthesize kTablePadding;
#synthesize alertDelegate;
- (void)layoutAnimated:(BOOL)fp8 {
[super layoutAnimated:fp8];
[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y - tableExtHeight/2, self.frame.size.width, self.frame.size.height + tableExtHeight)];
// We get the lowest non-control view (i.e. Labels) so we can place the table view just below
int i = 0;
while (![[self.subviews objectAtIndex:i] isKindOfClass:[UIControl class]]) {
lowestView = [self.subviews objectAtIndex:i];
i++;
}
tableWidth = 262.0f;
for (UIView *sv in self.subviews) {
// Move all Controls down
if ([sv isKindOfClass:[UIControl class]]) {
sv.frame = CGRectMake(sv.frame.origin.x, sv.frame.origin.y + tableExtHeight, sv.frame.size.width, sv.frame.size.height);
}
}
}
- (void)show{
[self prepare];
[super show];
}
- (void)prepare {
if (tableHeight == 0) {
tableHeight = 150.0f;
}
kTablePadding = 8.0f;
tableExtHeight = tableHeight + 2 * kTablePadding;
[self setNeedsLayout];
}
#end
/*the UIAlertTableView class is imported into the myViewController header file*/
/*myViewController.m*/
#implementation myViewController
#synthesize myTableView;
#synthesize alert;
#synthesize imageView;
#synthesize scrollView;
#synthesize models;
#synthesize picked;
#pragma myTableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [models 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];
}
// now configure the cell
cell.textLabel.text = [models objectAtIndex:[indexPath row]];
[cell setAccessibilityTraits: UIAccessibilityTraitButton];
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (returnedSetting && (indexPath.row == prevSelectedIndex)){
returnedSetting = FALSE;
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//index path to row that's selected
NSIndexPath *myIndexPath = [myTableView indexPathForSelectedRow];
UITableViewCell *cell = [myTableView cellForRowAtIndexPath:myIndexPath];
labelText = cell.textLabel.text;
selectedModel = cell.textLabel.text;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSIndexPath *myIndexPath = [tableView indexPathForSelectedRow];
prevSelectedIndex = myIndexPath.row;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:myIndexPath];
[alert dismissWithClickedButtonIndex:0 animated:YES];
labelText = cell.textLabel.text;
selectedModel = cell.textLabel.text;
[self dismissModalViewControllerAnimated:YES];
}
-(void)removeButton{
[UIView animateWithDuration:1.5
delay:1.5
options:UIViewAnimationCurveEaseInOut
animations:^ {
eButton.alpha = 0;
}
completion:^(BOOL finished) {
}];
}
- (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.
}
-(void)showAlertFor:(NSTimer *)timer{
[alert show];
myTableView.frame = CGRectMake(11.0f, alert.lowestView.frame.origin.y + alert.lowestView.frame.size.height + 2 * alert.kTablePadding, alert.tableWidth, alert.tableHeight);
[alert insertSubview:myTableView atIndex:1];
[myTableView performSelector:#selector(flashScrollIndicators) withObject:nil afterDelay:.3];
}
-(void)bringupAlertTableViewFor:(NSString *)dName atLocationOnScreen:(CGPoint)newPoint{
if (([dName isEqualToString:#"hello"]){
picked =TRUE;
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f) style:UITableViewStylePlain];
alert = [[UIAlertTableView alloc] initWithTitle:dName
message:#"Choose from the table below:"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert setDelegate: alert.alertDelegate];
models = [[NSMutableArray alloc]init];
myTableView.delegate = self;
myTableView.dataSource = self;
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"Decisions" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"dName == %#", dName];
[request setPredicate: predicate];
NSError *error;
//matches found
NSArray *matchingData = [context executeFetchRequest: request error: &error];
for (NSManagedObject *obj in matchingData) {
[models addObject:[NSString stringWithFormat:#"%#",[obj valueForKey: #"model"]]];
}
alert.tableHeight = 120;
[alert show];
myTableView.frame = CGRectMake(11.0f, alert.lowestView.frame.origin.y + alert.lowestView.frame.size.height + 2 * alert.kTablePadding, alert.tableWidth, alert.tableHeight);
[alert insertSubview:myTableView atIndex:1];
[myTableView performSelector:#selector(flashScrollIndicators) withObject:nil afterDelay:.3];
}else{
picked = TRUE;
frame.origin.x = newPoint.x - 29; // new x coordinate
frame.origin.y = 240; // new y coordinate
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 1.5];
[UIView commitAnimations];
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f) style:UITableViewStylePlain];
alert = [[UIAlertTableView alloc] initWithTitle:dName
message:#"Select a choice:"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert setDelegate: alert.alertDelegate];
models = [[NSMutableArray alloc]init];
myTableView.delegate = self;
myTableView.dataSource = self;
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"Decisions" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"deName == %#", dName];
[request setPredicate: predicate];
NSError *error;
//matches found
NSArray *matchingData = [context executeFetchRequest: request error: &error];
for (NSManagedObject *obj in matchingData) {
[models addObject:[NSString stringWithFormat:#"%#",[obj valueForKey: #"model"]]];
}
alert.tableHeight = 120;
[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:#selector(showAlertFor:) userInfo:nil repeats:NO];
previousPoint = newPoint;
}
}
-(IBAction)singleTapImageView:(UITapGestureRecognizer *)sender {
CGPoint pt = [sender locationInView: sender.view];
//find out which was pressed
if ( ((pt.x >= 52) && (pt.x <= 79)) && ((pt.y >= 269) && (pt.y <= 296))){
CGPoint newPoint = {45, (257 + 55)};
[self bringupAlertTableViewFor:#"Choice1" atLocationOnScreen:newPoint];
}
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)sView{
[self removeButton];
}
-(void)scrollViewDidScroll:(UIScrollView *)sView{
eButton.alpha = .7;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)sView
{
[self removeButton];
}
-(void)exitButtonPressed{
[self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
UIImage *imageS = [UIImage imageNamed:#"ti.png"];
imageView = [[TouchDetectingImageView alloc]initWithImage:imageS];
[imageView setDelegate:self];
imageView.frame = CGRectMake(20, 25, imageS.size.width,imageS.size.height);
CGFloat newScrollWidth = imageView.image.size.width + 20;
[scrollView setContentSize:(CGSizeMake(newScrollWidth, imageView.image.size.height))];
[scrollView addSubview: imageView];
imageView.contentMode = UIViewContentModeScaleToFill;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapImageView:)];
singleTap.numberOfTapsRequired = 1;
[scrollView addGestureRecognizer:singleTap];
UIImage *img = [UIImage imageNamed:#"backbutton.png"];
CGRect frameForButton = CGRectMake(0, 3, img.size.width, img.size.height);
eButton = [[exitButton alloc] initWithFrame:frameForButton];
[eButton setDelegate:self];
[eButton addTarget:self action:#selector(exitButtonPressed) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *buttonTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(exitButtonPressed)];
buttonTap.numberOfTapsRequired = 1;
[eButton addGestureRecognizer:buttonTap];
eButton.alpha = 0;
[self.view addSubview:eButton];
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewDidUnload
{
[self setScrollView:nil];
[self setImageView:nil];
[self setmyTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
[scrollView flashScrollIndicators];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// The menu is only going to support landscape orientations
return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}
- (NSInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}
-(BOOL)shouldAutorotate{
return YES;
}
#end
The reason(s) for this were:
1) the call to layoutAnimated was being ignored
2) it appears that ios 6 handles view hierarchy somewhat differently...
3) ios 6.0 automatically scales to fit a 1136x640 display vs earlier version that scale to fit a 960x640 display.
solutions were:
use a layoutsubviews call and layoutifneeded
also using conditional statements to find the ios version (e.g. greater_than_or_equal_to ios 6.0)
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;
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.