Passing Information in Segue Using StoryBoards - objective-c

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;

Related

Display Images using RSS Feed in Objective C

I want to display images from the url
RSS Feed
I am using table view controller in my Objective c project..I am able to display text and links perfectly but not able to display images from the Feed url
I am using the following code
**TableViewController.h**
#import <UIKit/UIKit.h>
#interface TableViewController : UITableViewController <NSXMLParserDelegate>
#property (strong, nonatomic) IBOutlet UITableView *TableView;
#end
TableViewController.m
#import "TableViewController.h"
#import "ViewController.h"
#interface TableViewController (){
NSXMLParser *parser;
NSMutableArray *feeds;
NSMutableDictionary *item;
NSMutableString *title;
NSMutableString *link;
NSString *element;
NSString *imageType;
NSString *imageUrl;
}
#end
#implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
feeds=[[NSMutableArray alloc ] init];
NSURL *url = [NSURL URLWithString:#"https://www.nasa.gov/rss/dyn/breaking_news.rss"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return feeds.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [[feeds objectAtIndex:indexPath.row] objectForKey:#"title"];
// cell.imageView.image= [[feeds objectAtIndex:indexPath.row] objectForKey:#"title"];
return cell;
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
element = elementName;
if ([element isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc] init];
title = [[NSMutableString alloc] init];
link = [[NSMutableString alloc] init];
}
if ([element isEqualToString:#"enclosure"]) {
imageType = [attributeDict objectForKey:#"type"];
imageUrl = [attributeDict objectForKey:#"url"];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"item"]) {
[item setObject:title forKey:#"title"];
[item setObject:link forKey:#"link"];
[item setObject:imageType forKey:#"imageType"];
[item setObject:imageUrl forKey:#"imageUrl"];
[feeds addObject:[item copy]];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([element isEqualToString:#"title"]) {
[title appendString:string];
} else if ([element isEqualToString:#"link"]) {
[link appendString:string];
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser {
[self.tableView reloadData];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *string = [feeds[indexPath.row] objectForKey:#"link"];
[[segue destinationViewController] setUrl:string];
}
}
#end
Please help me to display images I am stuck with this.Thanks
Use this way :
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"identifier"];
UIImageview imgView = [[UIImageView alloc] initWithFrame:CGRectMake(150, 0, 48, 48)];
imgView.tag = 100;
//ssame way create a label
UILabel titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
titlelabel.tag = 102
[cell.contentview addsubview:imgview];
[cell.contentview addsubview:titlelabel];
}
UIImageview mImgView = (uiimageview *)[cell viewwithtag:100];
UILabel mLabel = (uilabel*)cell viewwithtag:102];
//set data
mlabel = //your label
mimgviw.imge = imageurl
Just put this line to your UITableViewCell
NSString *imgUrl = [[feeds objectAtIndex:indexPath.row] objectForKey:#"imageUrl"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]]];
cell.imageView.image = image;

Search in a NSMutableArray

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

TableView doesn't push to WebView

I'm trying to make an RSS Feed for my website inside the app. I'm trying to make it so that when the user clicks a cell in my TableView it brings you to the link of the specific post parsed. The link is being parsed, but the console gives me this error:
Application tried to push a nil view controller on target .
Here is my code:
WebViewController.h
#import <Foundation/Foundation.h>
#interface WebViewController : UIViewController
#property (nonatomic, readonly) UIWebView *webView;
#end
WebViewController.m
#import "WebViewController.h"
#implementation WebViewController
-(void)loadView
{
CGRect screenFrame = [[UIScreen mainScreen] applicationFrame];
UIWebView *wv = [[UIWebView alloc] initWithFrame:screenFrame];
[wv setScalesPageToFit:YES];
[self setView:wv];
}
-(UIWebView *)webView
{
return (UIWebView *)[self view];
}
#end
MasterViewController.h My TableView
#import <UIKit/UIKit.h>
// A forward declaration; we'll import the header in the .m
#class RSSChannel;
#class WebViewController;
#interface MasterViewController : UITableViewController
<NSXMLParserDelegate>
{
NSURLConnection *connection;
NSMutableData *xmlData;
RSSChannel *channel;
}
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#property (strong, nonatomic) IBOutlet UINavigationItem *navigationBar;
#property (nonatomic, strong) WebViewController *webViewController;
- (void)fetchEntries;
#end
MasterViewController.m
#import "MasterViewController.h"
#import "WebViewController.h"
#import "RSSChannel.h"
#import "RSSItem.h"
#interface MasterViewController () {
NSMutableArray *_objects;
}
#end
#implementation MasterViewController
#synthesize tableView = _tableView;
#synthesize navigationBar;
#synthesize webViewController;
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self fetchEntries];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
#pragma mark - Table View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIImage *myImage = [UIImage imageNamed:#"SephardiJewsHeader.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
imageView.frame = CGRectMake(0,-1,320,93);
return imageView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 93;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"The amount of items in the table: %u", [[channel items] count]);
return [[channel items] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:#"UITableViewCell"];
}
RSSItem *item = [[channel items] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[item title]];
[[cell detailTextLabel] setText:[item date]];
return cell;
}
- (void)fetchEntries
{
// Create a new data container for the stuff that comes back from the service
xmlData = [[NSMutableData alloc] init];
// Construct a URL that will ask the service for what you want -
// Note we can concatenate literal strings together on multiple lines in this way it
// results in a single NSString instance
NSURL *url = [NSURL URLWithString:
#"http://sephardijews.com/feed/"];
// Putting the URL we made into an NSURLRequest, so we can connect to the url data that we specifed
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Creating a connecting that will exchange this request for the data from the URL we specifed
connection = [[NSURLConnection alloc] initWithRequest:req
delegate:self
startImmediately:YES];
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifedName
attributes:(NSDictionary *)attributeDict
{
NSLog(#"%# found a %# element", self, elementName);
if ([elementName isEqual:#"channel"]) {
// If the parser saw a channel, create new instance, store in our ivar
channel = [[RSSChannel alloc] init];
// Give the channel object a pointer back to ourselves for later
[channel setParentParserDelegate:self];
// Set the parser's delegate to the channel object
[parser setDelegate:channel];
}
}
// This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[xmlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
// Give it a delegate - don't worry about the warning
[parser setDelegate:self];
// Tell it to start parsing - the documet will be parsed and the delegate of NSXMLParser will get all of its delegate messages sent to it before this line finishes execution - it is blocking
[parser parse];
// Get rid of the XML data as we no longer need it
xmlData = nil;
// Get rid of the connection, no longer need it
connection = nil;
// Reload the table
[[self tableView] reloadData];
NSLog(#"%#\n %#\n %#\n", channel, [channel title], [channel infoString]);
}
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
// Release the connection object, we are done with it cause' there is no connection
// Setting the connection to nil will stop the connection because it is nothing/0
connection = nil;
// Release the xmlData object. We stopped to connection to put the data in the xmlData object, so we set it to nil also
xmlData = nil;
// Grab the description of the error object passed to us, so we can tell the user
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
// Create and show an alert view to the user with the error string to tell them the error in the process of the connection
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error"
message:errorString
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[av show];
}
/* - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
WebViewController *aWebViewController = [[WebViewController alloc] init];
self.webViewController = aWebViewController;
[self.navigationController pushViewController:self.webViewController animated:YES];
RSSItem *entry = [[channel items] objectAtIndex:[indexPath row]];
NSURL *url = [NSURL URLWithString:[entry link]];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[[webViewController webView] loadRequest:req];
[[webViewController navigationItem] setTitle:[entry title]];
} */
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showPost"]) {
WebViewController *awebViewController = [segue destinationViewController];
self.webViewController = awebViewController;
NSIndexPath *selectedRow = [self.tableView indexPathForSelectedRow];
RSSItem *entry = [[channel items] objectAtIndex:[selectedRow row]];
NSURL *url = [NSURL URLWithString:[entry link]];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[[webViewController webView] loadRequest:req];
[[webViewController navigationItem] setTitle:[entry title]];
}
}
#end
Thanks for your help!
Your WebViewController isn't being initialized anywhere. Try this in your tableView:didSelectRowAtIndexPath::
WebViewController *aWebViewController = [WebViewController alloc] init];
self.webViewController = aWebViewController;
[self.navigationController pushViewController:self.webViewController animated:YES];
[aWebViewController release];
If you're using Storyboard, add a view controller and change its class to WebViewController. From the MasterViewController in the Storyboard, right-click on a cell and connect the push segue to the WebViewController. Click the push segue and change its identifier to something like "showPost" or whatever.
Go back to MasterViewController.m and delete your code from tableView:didSelectRowAtIndexPath: and add this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showPost"]) {
WebViewController *aWebViewController = [segue destinationViewController];
NSIndexPath *selectedRow = [self.tableView indexPathForSelectedRow];
RSSItem *entry = [[channel items] objectAtIndex:[selectedRow row]];
NSURL *url = [NSURL URLWithString:[entry link]];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[aWebViewController.webView loadRequest:req];
aWebViewController.title = entry.title
}
}

How to make my UITableViewCell not just have a title and a subtitle, but a title, subtitle (date), and another label (summary)?

Trying to make an my RSS Feed app have the summary inside the label, I have parsed the description (summary), but I don't understand how to add it in the UITableViewCell. I am currently using UITableViewCellStyleSubtitle, so I can show the title of each post and the date below it. How do I add one more below it to show summary of each post?
MasterViewController.h (TableView Header)
#import <UIKit/UIKit.h>
#class RSSChannel;
#class WebViewController;
#interface MasterViewController : UITableViewController
<NSXMLParserDelegate>
{
NSURLConnection *connection;
NSMutableData *xmlData;
RSSChannel *channel;
}
- (void)fetchEntries;
#property (nonatomic, strong) WebViewController *webViewController;
#end
MasterViewController.m (TableView Implementation)
#import "MasterViewController.h"
#import "RSSChannel.h"
#import "RSSItem.h"
#import "WebViewController.h"
#interface MasterViewController () {
NSMutableArray *_objects;
}
#end
#implementation MasterViewController
#synthesize webViewController;
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self fetchEntries];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"The amount of items in the table: %u", [[channel items] count]);
return [[channel items] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:#"UITableViewCell"];
}
RSSItem *item = [[channel items] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[item title]];
[[cell detailTextLabel] setText:[item date]];
return cell;
}
- (void)fetchEntries
{
// Create a new data container for the stuff that comes back from the service
xmlData = [[NSMutableData alloc] init];
// Construct a URL that will ask the service for what you want -
// Note we can concatenate literal strings together on multiple lines in this way it
// results in a single NSString instance
NSURL *url = [NSURL URLWithString:
#"http://sephardijews.com/feed/"];
// Putting the URL we made into an NSURLRequest, so we can connect to the url data that we specifed
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Creating a connecting that will exchange this request for the data from the URL we specifed
connection = [[NSURLConnection alloc] initWithRequest:req
delegate:self
startImmediately:YES];
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifedName
attributes:(NSDictionary *)attributeDict
{
NSLog(#"%# found a %# element", self, elementName);
if ([elementName isEqual:#"channel"]) {
// If the parser saw a channel, create new instance, store in our ivar
channel = [[RSSChannel alloc] init];
// Give the channel object a pointer back to ourselves for later
[channel setParentParserDelegate:self];
// Set the parser's delegate to the channel object
[parser setDelegate:channel];
}
}
// Method used to start at the beginning of the instance of the tableview, it will intialize the connection method to retrieve the posts from the URL
/* - (id) initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
[self fetchEntries];
}
return self;
}
*/
// This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[xmlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
// Give it a delegate - don't worry about the warning
[parser setDelegate:self];
// Tell it to start parsing - the documet will be parsed and the delegate of NSXMLParser will get all of its delegate messages sent to it before this line finishes execution - it is blocking
[parser parse];
// Get rid of the XML data as we no longer need it
xmlData = nil;
// Get rid of the connection, no longer need it
connection = nil;
// Reload the table
[[self tableView] reloadData];
NSLog(#"%#\n %#\n %#\n", channel, [channel title], [channel infoString]);
}
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
// Release the connection object, we are done with it cause' there is no connection
// Setting the connection to nil will stop the connection because it is nothing/0
connection = nil;
// Release the xmlData object. We stopped to connection to put the data in the xmlData object, so we set it to nil also
xmlData = nil;
// Grab the description of the error object passed to us, so we can tell the user
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
// Create and show an alert view to the user with the error string to tell them the error in the process of the connection
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"Error"
message:errorString
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[av show];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Push the web view controller onto the navigation stack - this implicitly
// creates the web view controller's view the first time through
[[self navigationController] pushViewController:webViewController animated:YES];
//Grab the selected item
RSSItem *entry = [[channel items] objectAtIndex:[indexPath row]];
//Constructs a URL with the link string of the item
NSURL *url = [NSURL URLWithString:[entry link]];
// Construct a request object with that URL
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Load the request into the web view
[[webViewController webView] loadRequest:req];
// Set the title of the web view controller's navifation item
[[webViewController navigationItem] setTitle:[entry title]];
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#end
Try changing the UITableViewCellStyle to custom and dragging in your own UITextLabel objects to the prototype cell. Make #propertys for each of your data items in your TableViewController...
#interface MasterViewController ()
NSMutableArray *_objects;
#property (nonatomic, strong) IBOutlet UILabel *title;
#property (nonatomic, strong) IBOutlet UILabel *date;
#property (nonatomic, strong) IBOutlet UILabel *summary;
#end
Then connect the UITextLabels to their respective data.

Playing video in iPhone simulator with Media Player Framework

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