Can't extracts information from RSS - Xcode - iphone

I built an app, and i left the Rss for the end, when i built it, everything works, except i can't see the information from the rss, i can see the title in the table view, but i can't see the image, Title, and description.
Please help me with this,
Thank From advance,
John
(The Application is based on : View Based Application !)
also, i attach my code :
-(void)reloadRss{
[self toggleToolBarButtons:NO];
[[self rssParser]startProcess];
}
-(void)toggleToolBarButtons:(BOOL)newState{
NSArray *toolbarItems = self.toolbar.items;
for (UIBarButtonItem *item in toolbarItems){
item.enabled = newState;
}
}
//Delegate method for blog parser will get fired when the process is completed
- (void)processCompleted{
//reload the table view
[self toggleToolBarButtons:YES];
[[self tableView]reloadData];
}
-(void)processHasErrors{
//Might be due to Internet
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"The" message:#"איןאפשרות להוריד מידע. אנאבדוק את חיבור האינטרנט שלך." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
[self toggleToolBarButtons:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[self rssParser]rssItems]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"rssItemCell"];
if(nil == cell){
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"rssItemCell"]autorelease];
}
cell.textLabel.text = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]title];
cell.detailTextLabel.text = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]description];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[[self viewController] setCurrentlySelectedBlogItem:[[[self rssParser]rssItems]objectAtIndex:indexPath.row]];
[self.view addSubview:newsr];
}
-(IBAction)rss{
[self.view addSubview:rss];
}
- (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); }
-(void)openWebLink{ // open a dialog with an OK and cancel button
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:#"האם אתה רוצה לפתוח דף זה ב-Safari ?" delegate:self cancelButtonTitle:#"בטל" destructiveButtonTitle:#"אשר" otherButtonTitles:nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
[actionSheet showFromToolbar:_toolbar];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 0){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[[self viewController] currentlySelectedBlogItem]linkUrl]]];
}
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSString * mediaUrl = [[[self viewController]currentlySelectedBlogItem]mediaUrl];
[[self image]setImage:[UIImage imageNamed:#"unknown.jpg"]];
if(nil != mediaUrl){
NSData* imageData;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
#try {
imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaUrl]];
}
#catch (NSException * e) {
//Some error while downloading data
}
#finally {
UIImage * imageFromImageData = [[UIImage alloc] initWithData:imageData];
[[self image]setImage:imageFromImageData];
[imageData release];
[imageFromImageData release];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
self.titleTextView.text = [[[self viewController] currentlySelectedBlogItem]title];
self.descriptionTextView.text = [[[self viewController] currentlySelectedBlogItem]description];
}
#end

Try to decode the content of the RSS with something like:
NSWindowsCP1252StringEncoding
NSUTF8StringEncoding
...

Related

how can i show accessary checked cell values in alertbox [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
how to get accessarychecked cell value and show it on alertview
how-to-get-accessarychecked-cell-value-and-show-it-on-alertview
I have created UITableView and cell in UITableView are accessarychecked . I have implemented an action named
-(IBAction) checkBoxClicked.
What I need is that I wanted to show accessarychecked cell values in Alertbox when I click on button this is the code which I have written:
#import "ViewController.h"
#implementation ViewController
#synthesize cell;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 7;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell= [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil)
{
cell = [[ UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [myarray objectAtIndex:indexPath.row];
/*
NSString *imagefile = [[NSBundle mainBundle] pathForResource:#"cellimage" ofType:#"png"];
UIImage *ui = [[UIImage alloc] initWithContentsOfFile:imagefile];
cell.imageView.image = ui;*/
NSString *check = [[NSBundle mainBundle] pathForResource:#"checkbox_not_ticked" ofType:#"png"];
UIImage *bi = [[UIImage alloc] initWithContentsOfFile:check];
cell.imageView.image = bi;
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
[cell release];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
-(IBAction) checkBoxClicked
{
NSArray *array = [[NSArray alloc] initWithArray:[myarray objectAtIndex:cell.accessoryType]:UITableViewCellAccessoryCheckmark];
if (array.cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
UIAlertView *msg = [[ UIAlertView alloc] initWithTitle:#"selected items are given: " message:array delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[msg show ];
[msg release];
[myarray release];
}
}
//-(IBAction)checkBoxClicked{}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
myarray = [[NSArray alloc] initWithObjects:#"mondey",#"tuesday",
#"wednesday",#"thursday",#"friday",#"saturday",#"sundey", nil];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[myarray release];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
Use tag for each button and retrieve the button instance

TableView, handle clicks error

I have an IOS example project which i downloaded from internet. This project is only a tableview filled up with names. When you click on a name a dialog opens. Pretty simple. When i try to move the code over to my "main project" (A TAB-based application) it wont work. I paste the exact same code in the m and h files.
Could it be something in my layout file?
#import "SecondViewController.h"
#implementation TableViewViewController
#synthesize tableViewArray;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *message = [NSString stringWithFormat:#"%#",[tableViewArray objectAtIndex:indexPath.row]];
NSString *focus = [NSString stringWithFormat:#"Focus"];
if ([focus isEqualToString:message]) {
// ...
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message: message delegate:self cancelButtonTitle:#"Sebastian :)" otherButtonTitles:nil];
[alert show];
[alert release];
}
//NSString *message = [NSString stringWithFormat:#"You selected %#",[tableViewArray objectAtIndex:indexPath.row]];
/*NSString *message = [NSString stringWithFormat:#"You selected %#",[tableViewArray objectAtIndex:indexPath.row]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message: message delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[alert show];
[alert release];*/
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableViewArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SimpleTableIdentifier"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"SimpleTableIdentifier"]autorelease];
}
cell.textLabel.text = [tableViewArray objectAtIndex:indexPath.row];
return cell;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *array = [[NSArray alloc] initWithObjects:#"1",#"2",#"3",#"4 ",#"5",#"6",#"Sko-7",#"",#"8",#"9",nil];
self.tableViewArray = array;
[array release];
}
- (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 {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
Thanks :)
The usual suspect in a case like that is hooking up outlets in the nib or - even more likely - hooking up tableView delegate and datasource in the nib. Can you double check to see that you did that?

How to list only online users on facebook with xmpp framework

I have integrated xmpp in my app and able to list all the users in a table view, but I only want to display the online users and then want to implement the feature to send and recieve messages to my online friends...
Please suggest me some helpful code...
Here is my code, executed after facebook login.
- (void)fbDidLogin
{
NSLog(#"logged in.....................");
[appDelegate.facebook requestWithGraphPath:#"me" andDelegate:self];
DDLogVerbose(#"%s accessToken: %# expirationDate: %#",__PRETTY_FUNCTION__,appDelegate.facebook.accessToken,appDelegate.facebook.expirationDate);
self.accessToken = appDelegate.facebook.accessToken;
if (xmppStreamFB) {
[xmppStreamFB release];
xmppStreamFB = nil;
}
xmppStreamFB = [[XMPPStreamFacebook alloc] init];
xmpReconnect = [[XMPPReconnect alloc] initWithStream:xmppStreamFB];
if (xmppRosterStorage) {
[xmppRosterStorage release];
xmppRosterStorage = nil;
}
xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
if (xmppRoster) {
[xmppRoster release];
xmppRoster = nil;
}
xmppRoster = [[XMPPRoster alloc] initWithStream:xmppStreamFB rosterStorage:xmppRosterStorage];
[xmppStreamFB addDelegate:self];
[xmppRoster addDelegate:self];
[xmppRoster setAutoRoster:YES];
xmppStreamFB.myJID = [XMPPJID jidWithString:[NSString stringWithFormat:#"%##chat.facebook.com", uid]];
// You may need to alter these settings depending on the server you're connecting to
allowSelfSignedCertificates = NO;
allowSSLHostNameMismatch = YES;
// Uncomment me when the proper information has been entered above.
NSError *error = nil;
if (![xmppStreamFB connect:&error])
NSLog(#"Error connecting: %#", error);
if(!tableView)
{
tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, 480, 320) style:UITableViewStylePlain];
}
[tableView setFrame:CGRectMake(0,0, 480, 320)];
[tableView setTag:2];
[tableView setDelegate:self];
[tableView setDataSource:self];
[tableView setHidden:NO];
[tableView setBackgroundColor:[UIColor clearColor]];
[tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
[tableView setAlpha:1.0];
[self.view addSubview:tableView];
[self.tableView reloadData];
[self showTopBar];
}
I don't know the actual flow of the xmpp framework for showing users online and to implement chat feature...
i have the following delegate methods as well..
- (void)xmppStreamDidSecure:(XMPPStreamFacebook *)sender
{
NSLog(#"---------- xmppStreamDidSecure: ----------");
}
- (void)xmppStreamDidConnect:(XMPPStreamFacebook *)sender
{
NSLog(#"---------- xmppStreamDidConnect: ----------");
isOpen = YES;
NSError *error = nil;
if (![self.xmppStreamFB authenticateWithAppId:_APP_ID accessToken:self.accessToken error:&error])
{
NSLog(#"Error authenticating: %#", error);
}
else {
NSLog(#"NO Error authenticating:");
/*
ChatViewController *cvc = [[ChatViewController alloc] init];
[self.view addSubview:cvc.view];*/
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
NSLog(#"---------- xmppStreamDidAuthenticate: ----------");
[self goOnline];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
NSLog(#"---------- xmppStream:didNotAuthenticate: ----------");
}
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
NSLog(#"---------- xmppStream:didReceiveIQ: ----------");
/*
ChatViewController *cvc = [[ChatViewController alloc] init];
[self.view addSubview:cvc.view];*/
return NO;
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
NSLog(#"---------- xmppStream:didReceiveMessage: ----------");
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
NSLog(#"---------- xmppStream:didReceivePresence: ----------");
}
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
NSLog(#"---------- xmppStream:didReceiveError: ----------");
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender
{
NSLog(#"---------- xmppStreamDidDisconnect: ----------");
if (!isOpen)
{
NSLog(#"Unable to connect to server. Check xmppStream.hostName");
}
}
And the two methods for online and offline user presence, but don't know how to modify them for my task:
- (void)goOnline
{
NSXMLElement *presence = [NSXMLElement elementWithName:#"presence"];
[[self xmppStream] sendElement:presence];
}
- (void)goOffline
{
NSXMLElement *presence = [NSXMLElement elementWithName:#"presence"];
[presence addAttributeWithName:#"type" stringValue:#"unavailable"];
[[self xmppStream] sendElement:presence];
}
finally after lots of efforts i found out how to show online/offline/away users.
i'm going to tell you step by step how i did it, so that i can be useful for the less experienced users too..
Step 1- on click of chat button i'm calling the following method-
-(void) chatFacebook
{
if (appDelegate.facebook == nil)
{
appDelegate.facebook = [[[Facebook alloc] initWithAppId:_APP_ID] autorelease];
}
if (!accessToken)
{
[appDelegate.facebook authorize:[XMPPStreamFacebook permissions] delegate:self appAuth:NO safariAuth:NO];
}
else
{
[self fbDidLogin];
}
}
step 2- Now its time for login dialog delegate methods to come in , if the login is successfull the fbDidLogin is called, here are the delegate methods you should include-
#pragma mark FBLoginDialogDelegate
/**
* Called when the user successfully logged in.
*/
- (void)fbDidLogin
{
NSLog(#"logged in.....................");
[appDelegate.facebook requestWithGraphPath:#"me" andDelegate:self];
DDLogVerbose(#"%s accessToken: %# expirationDate: %#",__PRETTY_FUNCTION__,appDelegate.facebook.accessToken,appDelegate.facebook.expirationDate);
self.accessToken = appDelegate.facebook.accessToken;
if (xmppStream) {
[xmppStream release];
xmppStream = nil;
}
xmppStream = [[XMPPStreamFacebook alloc] init];
xmpReconnect = [[XMPPReconnect alloc] initWithStream:xmppStream];
if (xmppRosterStorage) {
[xmppRosterStorage release];
xmppRosterStorage = nil;
}
xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
if (xmppRoster) {
[xmppRoster release];
xmppRoster = nil;
}
xmppRoster = [[XMPPRoster alloc] initWithStream:xmppStream rosterStorage:xmppRosterStorage];
[xmppStream addDelegate:self];
[xmppRoster addDelegate:self];
[xmppRoster setAutoRoster:YES];
xmppStream.myJID = [XMPPJID jidWithString:[NSString stringWithFormat:#"%##chat.facebook.com", uid]];
// You may need to alter these settings depending on the server you're connecting to
allowSelfSignedCertificates = NO;
allowSSLHostNameMismatch = YES;
// Uncomment me when the proper information has been entered above.
NSError *error = nil;
if (![xmppStream connect:&error])
NSLog(#"Error connecting: %#", error);
if(!tableView)
{
tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, 480, 320) style:UITableViewStylePlain];
}
[tableView setFrame:CGRectMake(0,0, 480, 320)];
[tableView setTag:2];
[tableView setDelegate:self];
[tableView setDataSource:self];
[tableView setHidden:NO];
[tableView setBackgroundColor:[UIColor clearColor]];
[tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
[tableView setAlpha:1.0];
[self.view addSubview:tableView];
[self.tableView reloadData];
[self showTopBar];
}
/**
* Called when the user dismissed the dialog without logging in.
*/
- (void)fbDidNotLogin:(BOOL)cancelled
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Canceled" message:#"Login cancled" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
/**
* Called when the user logged out.
*/
- (void)fbDidLogout
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Logged out" message:#"Logged out" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
Step 3- The second line of the fbDidLogin method calls the FBRequestDelegate methods so you should include this protocol in your .h class, to get the uid of the user(which is logged in , means the current user) you need to implement the following methods-
pragma mark
pragma mark FBRequestDelegate
- (void)request:(FBRequest*)request didFailWithError:(NSError*)error{
DDLogError(#"%s %#",__PRETTY_FUNCTION__,error);
//[appDelegate.facebook logout:self];
}
/**
* Called when a request returns and its response has been parsed into an object.
* The resulting object may be a dictionary, an array, a string, or a number, depending
* on thee format of the API response.
*/
- (void)request:(FBRequest*)request didLoad:(id)result {
DDLogVerbose(#"%s............DDLOG................... %#",__PRETTY_FUNCTION__,result);
NSLog(#" Result>>>>-------%#", result);
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:(NSMutableDictionary *)result];
uid = [dict objectForKey:#"id"];
NSLog(#"iddddddddddddd---%#", uid);
}
Step 4- Now comes the table view DataSource and Delegate methods, you need to implement these, here are the methods-
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView1
{
return [[[self fetchedResultsController] sections] count];
// need to implement NSFetchedResultsControllerDelegate
}
- (NSString *)tableView:(UITableView *)sender titleForHeaderInSection:(NSInteger)sectionIndex
{
NSArray *sections = [[self fetchedResultsController] sections];
if (sectionIndex < [sections count])
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:sectionIndex];
int section = [sectionInfo.name intValue];
switch (section)
{
case 0 : return #"Available";
case 1 : return #"Away";
default : return #"Offline";
}
}
}
return #"";
}
- (NSInteger)tableView:(UITableView *)tableView1 numberOfRowsInSection:(NSInteger)sectionIndex
{
NSArray *sections = [[self fetchedResultsController] sections];
if (sectionIndex < [sections count])
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:sectionIndex];
return sectionInfo.numberOfObjects;
NSLog(#"section ifnfo ===========%#", sectionInfo);
}
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
user = [[self fetchedResultsController] objectAtIndexPath:indexPath];
cell.textLabel.text = user.displayName;
cell.textLabel.textColor = [UIColor whiteColor];
cell1 = cell;
}
Step 5- Finally you also need to implement NSFetchedResultsController delegate methods , so that you can fill table with the chat users, here are the methods-
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil)
{
NSEntityDescription *entity = [NSEntityDescription entityForName:#"XMPPUserCoreDataStorage"
inManagedObjectContext:[self managedObjectContext]];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:#"sectionNum" ascending:YES];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:#"displayName" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchBatchSize:10];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:[self managedObjectContext]
sectionNameKeyPath:#"sectionNum"
cacheName:nil];
[fetchedResultsController setDelegate:self];
[sd1 release];
[sd2 release];
[fetchRequest release];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
NSLog(#"Error performing fetch: %#", error);
}
}
return fetchedResultsController;
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[[self tableView] reloadData];
}
Step 6 - Compile and run your code ,user list should appear in table view
if any problems appears, please share , i'm always here to help you .And please dont mind if there are some mistakes while posting this answer, cz i'm posting just for the third time
Thanks.

Need Help Adding User's Text To NSArray

I am prompting users for text when they click the + for my table. They are shown a UIAlert with textField prompt and the text is then saved as a string in a dictionary.
I have the following code so far:
- (void)viewDidLoad
{
NSArray *myData = [NSMutableArray arrayWithContentsOfFile:#"mydata"];
if (myData == nil)
{
myData = [NSMutableArray array];
}
[super viewDidLoad];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
}
}
The NSlog shows the entered text but how do I get it to save in my Array?
Also, should I save the text as a string, a dictionary with a string in it, or an array itself with a string in it? Because there is going to be a dictionary or array within each of these other dictionaries with objects that the user can choose from (the objects they can choose from are stored in a separate plist).
For example, User types in "Arms Day" for the prompt, then it saves to the array and he can choose from all the exercises for the arm that I have stored in a data.plist
Update with new code:
#import "RoutineTableViewController.h"
#import "AlertPrompt.h"
#implementation RoutineTableViewController
#synthesize routineArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
/*
NSArray *myData = [NSMutableArray arrayWithContentsOfFile:#"mydata"];
if (myData == nil)
{
myData = [NSMutableArray array];
}
*/
[super viewDidLoad];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
[self.routineArray addObject:entered]; }
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// do delete
// get count of rows in UITableView and hide table if it's empty
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [routineArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 0;
}
- (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] autorelease];
}
cell.textLabel.text = [self.routineArray objectAtIndex:indexPath.row];
return cell;
}
Update 3:
#implementation RoutineTableViewController
#synthesize myArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
myArray = [[NSMutableArray alloc] init];
myData = [[NSMutableArray arrayWithContentsOfFile:#"mydata"] retain];
if (myData == nil)
{
myData = [NSMutableArray array];
}
[super viewDidLoad];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
//if(myData && entered)
{
[myArray addObject:entered];
}
}
NSLog(#"%#",[myArray objectAtIndex:0]);
[tableView reloadData];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// do delete
// get count of rows in UITableView and hide table if it's empty
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [myArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 0;
}
- (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] autorelease];
}
cell.textLabel.text = [self.myArray objectAtIndex:indexPath.row];
return cell;
}
Suggest you to save the user text in NSMutableArray.
Declare NSMutableArray variable in your .h file,
NSMutableArray *myData;
In Source file .m:
myData = [[NSMutableArray arrayWithContentsOfFile:#"mydata"] retain];
if (myData == nil)
{
myData = [NSMutableArray array];
}
Add text in Array.
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
if(myData && entered)
{
[myArray addObject:entered];
}
}
Neither of the current answers are very helpful, because they haven't looked at your code! Just doing addObject won't help you, in fact your code probably won't compile if you add it.
Your array is a local variable, so it's only available inside the viewDidLoad method. If you try to add anything to it inside yourwillDismissWithButtonIndex method without changing how you're declaring your array you'll cause a compiler error. The first step is to make your myData variable available to all your methods. You can use a property to achieve this - if you're unsure how to declare a property you should think about perhaps stepping back and reading up a bit more on Objective-C before diving in.
So, in your header file you might declare:
#property (nonatomic, retain) NSMutableArray *myArray;
And in your implementation file:
#synthesize myArray
- (void)viewDidLoad
{
self.myData = [NSMutableArray arrayWithContentsOfFile:#"mydata"];
....
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
[self.myArray addObject:entered];
Hope that helps you out!
Make your array as part of your class and use its reference in your method to add it to array.
[myArray addObject:entered];

iphone Dev - activity indicator with NSThread not working on Nav controller table view

I really can't get this to work, basically when my JSON feeds loads I want the indicator to show, then hide when it's stopped.
It loads top level menu items 1st "Publishing, Broadcasting, Marketing Services", then when Broadcasting is selected it loads a feed using the JSON framework hosted on Google. Round this load I call startIndicator and stopIndicator using the NSThread. Have I missed something?
#implementation GeneralNewsTableViewController
#synthesize dataList;
#synthesize generalNewsDetailViewController;
#synthesize atLevel;
-(void) startIndicator
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc ] init ];
[(UIActivityIndicatorView *)[self navigationItem].rightBarButtonItem.customView startAnimating];
[pool release];
}
-(void) stopIndicator
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc ] init ];
[(UIActivityIndicatorView *)[self navigationItem].rightBarButtonItem.customView stopAnimating];
[pool release];
}
- (void)viewDidLoad {
NSMutableArray *checker = self.dataList;
if(checker == nil)
{
self.title = NSLocalizedString(#"General1",#"General News");
NSMutableArray *array = [[NSArray alloc] initWithObjects:#"Publishing", #"Broadcasting",#"Marketing Services",nil];
self.dataList = [array retain];
self.atLevel = #"level1";
[array release];
}
UIActivityIndicatorView * activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//set the initial property
[activityIndicator stopAnimating];
[activityIndicator hidesWhenStopped];
//Create an instance of Bar button item with custome view which is of activity indicator
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
//Set the bar button the navigation bar
[self navigationItem].rightBarButtonItem = barButton;
//Memory clean up
[activityIndicator release];
[barButton release];
[super viewDidLoad];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *level = self.atLevel;
if([level isEqualToString:#"level2"])
{
return 70.0f;
}
else
{
return 40.0f;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *FirstLevelCell = #"FirstLevelCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FirstLevelCell];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:FirstLevelCell] autorelease];
}
NSInteger row = [indexPath row];
NSString *level = self.atLevel;
if([level isEqualToString:#"level2"])
{
NSMutableArray *stream = [self.dataList objectAtIndex:row];
NSString *newsTitle = [stream valueForKey:#"title"];
if( ![newsTitle isKindOfClass:[NSString class]] )
{
cell.textLabel.text = #"";
}
else
{
cell.textLabel.text = [stream valueForKey:#"title"];
}
cell.textLabel.numberOfLines = 2;
cell.textLabel.font =[UIFont systemFontOfSize:10];
cell.detailTextLabel.numberOfLines = 1;
cell.detailTextLabel.font= [UIFont systemFontOfSize:8];
cell.detailTextLabel.text = [stream valueForKey:#"created"];
NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.website.co.uk/images/stories/img.jpg"]];
UIImage *newsImage = [[UIImage alloc] initWithData:imageURL];
cell.imageView.image = newsImage;
[imageURL release];
[newsImage release];
}
else
{
cell.textLabel.text = [dataList objectAtIndex:row];
}
return cell;
}
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSMutableString *levelType = (NSMutableString *) [dataList objectAtIndex:row];
if(![levelType isKindOfClass:[NSString class]])
{
if(self.generalNewsDetailViewController == nil)
{
GeneralNewsDetailViewController *generalDetail = [[GeneralNewsDetailViewController alloc] initWithNibName:#"GeneralNewsDetailView" bundle:nil];
self.generalNewsDetailViewController = generalDetail;
[generalDetail release];
}
NSDictionary *stream = [self.dataList objectAtIndex:row];
NSString *newsTitle = [stream valueForKey:#"title"];
if( ![newsTitle isKindOfClass:[NSString class]] )
{
generalNewsDetailViewController.newsTitle = #"";
}
else
{
generalNewsDetailViewController.newsTitle =[stream valueForKey:#"title"];
}
generalNewsDetailViewController.newsId = [stream valueForKey:#"id"];
generalNewsDetailViewController.fullText = [stream valueForKey:#"fulltext"];
generalNewsDetailViewController.newsImage = [stream valueForKey:#"images"];
generalNewsDetailViewController.created = [stream valueForKey:#"created"];
HowDo_v1AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.generalNewsNavController pushViewController:self.generalNewsDetailViewController animated:YES];
}
else
{
GeneralNewsTableViewController
*generalSubDetail = [[GeneralNewsTableViewController alloc] initWithNibName:#"GeneralNewsTableView" bundle:nil];
NSMutableArray *array;
NSString *titleSelected = (NSString *) [dataList objectAtIndex:row];
if([titleSelected isEqualToString:#"Publishing"])
{
generalSubDetail.title = #"Publishing news detail";
array = [[NSArray alloc] initWithObjects:#"pub News1", #"pub News2",#"pub News3",nil];
generalSubDetail.atLevel = #"level1";
}
else if ([titleSelected isEqualToString:#"Broadcasting"])
{
generalSubDetail.title = #"Broadcasting news detail";
/// START
[self performSelectorOnMainThread:#selector(startIndicator) withObject:nil waitUntilDone:YES];
if(jSONDataAccessWrapper == nil)
{
jSONDataAccessWrapper = [JSON_DataAccess_Wrapper alloc];
}
array = [jSONDataAccessWrapper downloadJSONFeed];
[self performSelectorOnMainThread:#selector(stopIndicator) withObject:nil waitUntilDone:YES];
generalSubDetail.atLevel = #"level2";
}
else if ([titleSelected isEqualToString:#"Marketing Services"])
{
generalSubDetail.title = #"Marketing Services news detail";
array = [[NSArray alloc] initWithObjects:#"Marketing News1", #"Marketing News2",#"Marketing News3",nil];
generalSubDetail.atLevel = #"level1";
}
generalSubDetail.dataList = array;
[self.navigationController pushViewController:generalSubDetail animated:YES];
[titleSelected release];
}
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
//- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSIndexPath *) section
{
return [self.dataList count];
}
Cheers for any feedback
Frames
It is usually recommended by Apple that operations on user interface should be done on the main thread.
What you can do is to defer the callback into the main thread:
- (void)startIndicator
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self performSelectorOnMainThread:#selector(startAnimating:) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void)startAnimating:(id)sender
{
[(UIActivityIndicatorView *)[self navigationItem].rightBarButtonItem.customView startAnimating];
}
Check out the Thread Guide from Apple. It contains useful information.