iOS XMPP received message in conversation screen - ios

I am working on XMPP based project. I am able to send message and it displays in conversation screen but when I receive message it only show in alertview not able to see in conversation screen.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(messageReceived:) name:MessageRecivedNotif object:nil];
appdelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
[self getAllMessagesArrayWithOppositeUser:_jid];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification
object:nil];
}
#pragma mark table delegate and datasource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tblobj dequeueReusableCellWithIdentifier:#"cell"];
UILabel *lbl;
if (cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
if (chatLblRight == 1)
{
lbl = [[UILabel alloc]initWithFrame:CGRectMake(200, 10, 150, 44)];
[lbl setTextColor:[UIColor redColor]];
[cell.contentView addSubview:lbl];
}
}
if (chatLblRight == 1)
{
lbl.text = [[data objectAtIndex:indexPath.row]valueForKey:#"text"];
chatLblRight = 0;
lbl = [[UILabel alloc]initWithFrame:CGRectMake(200, 10, 150, 44)];
[lbl setTextColor:[UIColor redColor]];
[cell.contentView addSubview:lbl];
return cell;
}
else
{
cell.textLabel.text=[[data objectAtIndex:indexPath.row]valueForKey:#"text"];
return cell;
}
}
-(void)messageReceived:(NSNotification*)notif
{
XMPPMessage *message=(XMPPMessage*)notif.object;
NSString *body = [[message elementForName:#"body"] stringValue];
NSMutableDictionary *dic_recive = [[NSMutableDictionary alloc]init];
[dic_recive setObject:body forKey:#"text"];
[data addObject:dic_recive];
chatLblRight = 1;
[tblobj reloadData];
}
-(IBAction)btnsend:(id)sender
{
[txtmsg resignFirstResponder];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.2];
[msgview setFrame:CGRectMake(0, self.view.bounds.size.height-53, self.view.bounds.size.width, 53)];
[UIView commitAnimations];
[((AppDelegate*)[[UIApplication sharedApplication]delegate]) sendMessage:txtmsg.text toUserWithJid:_jid];
NSMutableDictionary *dic_send = [[NSMutableDictionary alloc]init];
[dic_send setObject:txtmsg.text forKey:#"text"];
[data addObject:dic_send];
[tblobj reloadData];
txtmsg.text=#"";
}
-(NSMutableArray *)getAllMessagesArrayWithOppositeUser:(XMPPJID *)xmppUser
{
XMPPMessageArchivingCoreDataStorage *storage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"XMPPMessageArchiving_Message_CoreDataObject"
inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescription];
NSError *error;
NSArray *messages = [moc executeFetchRequest:request error:&error];
data=[[NSMutableArray alloc] init];
#autoreleasepool {
for (XMPPMessageArchiving_Message_CoreDataObject *message in messages) {
if ([message.bareJid isEqual:xmppUser])
{
NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
[dict setObject:message.body forKey:#"text"];
[dict setObject:message.timestamp forKey:#"date"];
if ([message isOutgoing]) {
[dict setObject:#"1" forKey:#"type"];
[dict setObject:[[message.bareJidStr componentsSeparatedByString:#"#"] firstObject] forKey:#"username"];
[dict setObject:[UIColor greenColor] forKey:#"color"];
}
else{
[dict setObject:#"2" forKey:#"type"];
[dict setObject:[[message.bareJidStr componentsSeparatedByString:#"#"] firstObject] forKey:#"username"];
// [dict setObject:userName forKey:#"username"];
[dict setObject:[UIColor blueColor] forKey:#"color"];
}
[data addObject:dict];
}
}
}
return data;
}
Where is my mistake ?
EDIT
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
if ([message isChatMessageWithBody])
{
XMPPMessageArchivingCoreDataStorage *xmppMessageStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
XMPPMessageArchiving *xmppMessageArchiving = [[XMPPMessageArchiving alloc] initWithMessageArchivingStorage:xmppMessageStorage];
[xmppMessageArchiving activate:xmppStream];
[xmppMessageArchiving addDelegate:self delegateQueue:dispatch_get_main_queue()];
XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[message from]
xmppStream:xmppStream
managedObjectContext:[self managedObjectContext_roster]];
[[NSNotificationCenter defaultCenter] postNotificationName:MessageRecivedNotif object:message];
NSString *body = [[message elementForName:#"body"] stringValue];
NSString *displayName = [user displayName];
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
message:body
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
else
{
// We are not active, so use a local notification instead
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertAction = #"Ok";
localNotification.alertBody = [NSString stringWithFormat:#"From: %#\n\n%#",displayName,body];
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}
}

you need to set your logic in uitableviewcellforrowatindexpath method like this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tblobj dequeueReusableCellWithIdentifier:#"cell"];
UILabel *lbl;
if (cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
if([[[data objectAtIndex:indexPath.row]valueForKey:#"type"] isEqualToString:#"2"])
//if (chatLblRight == 1)
{
lbl = [[UILabel alloc]initWithFrame:CGRectMake(200, 10, 150, 44)];
[lbl setTextColor:[UIColor redColor]];
[cell.contentView addSubview:lbl];
}
}
if([[[data objectAtIndex:indexPath.row]valueForKey:#"type"] isEqualToString:#"2"])
//if([[[data objectAtIndex:indexPath.row]valueForKey:#"type"] isEqualToString:#"1"])
//if (chatLblRight == 1)
{
lbl.text = [[data objectAtIndex:indexPath.row]valueForKey:#"text"];
chatLblRight = 0;
lbl = [[UILabel alloc]initWithFrame:CGRectMake(200, 10, 150, 44)];
[lbl setTextColor:[UIColor redColor]];
[cell.contentView addSubview:lbl];
return cell;
}
else
{
cell.textLabel.text=[[data objectAtIndex:indexPath.row]valueForKey:#"text"];
return cell;
}
}
please check this code once.

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage*)message
{
//in this the (XMPPMessage*)message parameter is xml data
//parse you xml and create dictionary For eg : sampledict
}
Normally when you are getting reply from XMPP it comes like XML data. That you have to parse and use for your operations.
And in your code here
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
// UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
message:body
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
// [alertView show];
}
else
{
// We are not active, so use a local notification instead
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertAction = #"Ok";
localNotification.alertBody = [NSString stringWithFormat:#"From: %#\n\n%#",displayName,body];
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}
You have used alertview. So you have to hide your alertview so that you don't get alerts. Instead manage your observer method to get data and use it
-(void)messageReceived:(NSNotification*)notif
{
XMPPMessage *message=(XMPPMessage*)notif.object;
NSString *body = [[message elementForName:#"body"] stringValue];
NSMutableDictionary *dic_recive = [[NSMutableDictionary alloc]init];
[dic_recive setObject:body forKey:#"text"];
[data addObject:dic_recive];
chatLblRight = 1;
[tblobj reloadData];
}
I think this will help you..

Please go to xmpp custom class and post a notification like this
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
//parse you xml and create dictionary For eg : sampledict
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:#"updateValue" object:nil userInfo:sampledict];
}
and receive notification from your class like
using notification like
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveUpdatedValues:)
name:#"updateValue"
object:nil];
-(void)receiveUpdatedValues : (NSNotification *)notification
{
NSDictionary *dictinfo=notification.userInfo;
// here use your info dict to get your message
}

Related

How can I reload the price of product by clicking on select the quantity in table view in iOS?

In this, I am clicking on update button and my price is not updating instantly, Its updating when i go back to home view controller. Please help me out of this.[I want when I click on update button, My price of product will be change according to selection of quantity like 1 kg, 2kg ,5 kg etc]
#import "MainCartViewController.h"
#import "CartTableCell.h"
#import "CheckOutViewController.h"
#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "Detail.h"
#import "MBProgressHUD.h"
#define JSON_URL #"http://www.webchefz.com/Andriod/index.php?Table=Cart&UserID=11"
#interface MainCartViewController ()
#end
#implementation MainCartViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[self navigationController] setNavigationBarHidden:NO animated:YES];
UINavigationBar *navBar = [[self navigationController] navigationBar];
[ navBar setTintColor:[UIColor whiteColor]];
UIButton *Btn =[UIButton buttonWithType:UIButtonTypeCustom];
[Btn setFrame:CGRectMake(0.0f,0.0f,30.0f,30.0f)];
[Btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:#"carc.png"]] forState:UIControlStateNormal];
[Btn addTarget:self action:#selector(AddtoCartButton:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithCustomView:Btn];
cFRAIPArray = [[NSMutableArray alloc]init];
tableData =[[NSMutableArray alloc]init];
blogURL= [NSURL URLWithString:JSON_URL];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
tableData = [dataDictionary objectForKey:#"userlist"];
// int tp = [NSString stringWithFormat:#"%d",[dataDictionary valueForKey:#"TotalPrice"]];
totalPrice= [[dataDictionary objectForKey:#"userlist"]valueForKey:#"TotalPrice"];
NSLog(#"TP IS %#", [dataDictionary valueForKey:#"TotalPrice"]);
subtotal.text= [[NSString alloc] initWithFormat:#"%# Rs.",[dataDictionary valueForKey:#"TotalPrice"]];
int ShippingValue = [[subtotal text] intValue];
int value = 50;
float floatNum = ShippingValue + value;
grandTotal.text=[[NSString alloc] initWithFormat:#"%.1f Rs.", floatNum];
NSLog(#"dwfefefeusers are %#", totalPrice);
NSLog(#"dwfefefeusers are %#", tableData);
NSString *items= [[dataDictionary objectForKey:#"userlist"]valueForKey:#"Name"];
NSLog(#"hjdbhsdbchjds%#",items
);
for (dataDictionary in tableData)
{
// currentHotel= [[Detail alloc]initWithId:[[bpDictionary objectForKey:#"id"]integerValue] Name:[bpDictionary objectForKey:#"Name"] HindiName:[bpDictionary objectForKey:#"HindiName"] MRP:[[bpDictionary objectForKey:#"MRP"]integerValue] ImagePath:[bpDictionary objectForKey:#"ImagePath"]Category:[bpDictionary objectForKey:#"Category"]];
currentHotel = [[Detail alloc]initWithId:[[dataDictionary objectForKey:#"ID"]integerValue] Name:[dataDictionary objectForKey:#"Name"] HindiName:[dataDictionary objectForKey:#"HindiName"] MRP:[[dataDictionary objectForKey:#"TotalPrice"]integerValue] CartID:[[dataDictionary objectForKey:#"CartID"]integerValue] ProductID:[[dataDictionary objectForKey:#"ProductID"]integerValue] Quantity:[[dataDictionary objectForKey:#"Quantity"]integerValue] userName:[dataDictionary objectForKey:#"UserName"] ImagePath:[dataDictionary objectForKey:#"ImagePath"] Category:[dataDictionary objectForKey:#"Category"]];
[self.objectHolderArray addObject:currentHotel];
}
CGRect frame = CGRectMake(0, 0, 0, 44);
UILabel *label = [[UILabel alloc]initWithFrame:frame];
label.text = #"Cart List";
label.textColor=[UIColor whiteColor];
label.font = [UIFont fontWithName:#"Helvetica Neue" size:16];
self.navigationItem.titleView = label;
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
// Initialize table data
// tableData = [NSMutableArray arrayWithObjects:#"Egg Benedict", #"Mushroom Risotto", #"Full Breakfast", #"Hamburger", #"Ham and Egg Sandwich", #"Creme Brelee", #"White Chocolate Donut", #"Starbucks Coffee", #"Vegetable Curry", #"Instant Noodle with Egg", #"Noodle with BBQ Pork", #"Japanese Noodle with Pork", #"Green Tea", #"Thai Shrimp Cake", #"Angry Birds Cake", #"Ham and Cheese Panini", nil];
}
-(NSMutableArray *)objectHolderArray
{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}
IBAction)AddtoCartButton:(id)sender
{
MainCartViewController *cartView= [[MainCartViewController alloc]initWithNibName:#"MainCartViewController" bundle:nil];
[self.navigationController pushViewController:cartView animated:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"CartTableCell";
cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CartTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
currentHotel = [self.objectHolderArray
objectAtIndex:indexPath.item];
NSLog(#"%#",[self.objectHolderArray
objectAtIndex:indexPath.item] );
cell.nameLabel.text=currentHotel.name;
cell.MRPLabel.text=[NSString stringWithFormat:#"Rs.%d",currentHotel.MRP];
NSLog(#"price is %#",cell.MRPLabel.text);
[cell.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:currentHotel.images] placeholderImage:[UIImage imageNamed:#"defaultPlayerImge.png"] options:SDWebImageRefreshCached|SDWebImageProgressiveDownload];
[cell.deleteBtn addTarget:self action:#selector(deleteProduct:) forControlEvents:UIControlEventTouchUpInside];
cell.deleteBtn.tag = [indexPath row];
[cell.PickerBtn addTarget:self action:#selector(createPickerView:) forControlEvents:UIControlEventTouchUpInside];
cell.PickerBtn.tag = [indexPath row];
[cell.updateBtn addTarget:self action:#selector(updateProduct:) forControlEvents:UIControlEventTouchUpInside];
cell.updateBtn.tag = [indexPath row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (debtn.deleteBtn.highlighted) {
NSLog(#"cff");
}
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.objectHolderArray count];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
int errorCode = httpResponse.statusCode;
NSString *fileMIMEType = [[httpResponse MIMEType] lowercaseString];
NSLog(#"response is %d, %#", errorCode, fileMIMEType);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(#"data is %#", data);
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string is %#", myString);
NSError *e = nil;
flickrDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSLog(#"dictionary is %#", flickrDictionary);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[HUD hide:YES];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Quanity updated succesfully" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.tableView1 reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView1 reloadData];
// }
NSLog(#"cfraiparray %#", cFRAIPArray);
NSLog(#"Succeeded!");
}
-(void)createPickerView :(UIButton *)button
{
currentHotel=[self.objectHolderArray objectAtIndex:button.tag];
self.pickerViewTextField = [[UITextField alloc] initWithFrame:CGRectZero];
[self.view addSubview:self.pickerViewTextField];
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
weights= [[NSMutableArray alloc] initWithObjects:#"1 Kg",#"2 Kg",#"5 Kg",#"10 Kg",#"50 Kg",
nil];
// set change the inputView (default is keyboard) to UIPickerView
self.pickerViewTextField.inputView = pickerView;
// add a toolbar with Cancel & Done button
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
toolBar.barStyle = UIBarStyleBlackOpaque;
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneTouched:)];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(cancelTouched:)];
[toolBar setItems:[NSArray arrayWithObjects:cancelButton, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], doneButton, nil]];
self.pickerViewTextField.inputAccessoryView = toolBar;
[self.pickerViewTextField becomeFirstResponder];
// [self.view addSubview:pickerView];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
// [self bringUpPickerViewWithRow:indexPath];
}
-(void) deleteProduct:(UIButton *)button
{
currentHotel=[self.objectHolderArray objectAtIndex:button.tag];
NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.webchefz.com/Andriod/delete.php?Table=Cart&CartID=%d&UserID=11",currentHotel.CartID]];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
NSURLConnection *myConnection = [NSURLConnection connectionWithRequest:myRequest delegate:self];
NSLog(#"main cart id is %#", [NSString stringWithFormat:#"%d",currentHotel.CartID]);
NSLog(#"ded");
[self.objectHolderArray removeObjectAtIndex:button.tag];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
[self.tableView1 deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.tableView1 reloadData];
}
-(void) updateProduct:(UIButton *)button
{
HUD= [MBProgressHUD showHUDAddedTo:self.view animated:YES];
HUD.labelText = #"Please Wait...";
HUD.mode = MBProgressHUDModeIndeterminate;
[self.view addSubview:HUD];
[HUD show:YES];
currentHotel=[self.objectHolderArray objectAtIndex:button.tag];
NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.webchefz.com/Andriod/update.php?Table=Cart&CartID=%d&Quantity=%d&UserID=11&ProductID=%d",currentHotel.CartID,pickerQuantity,currentHotel.ProductID]];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
NSURLConnection *myConnection = [NSURLConnection connectionWithRequest:myRequest delegate:self];
NSLog(#"main cart id is %#", [NSString stringWithFormat:#"%d",currentHotel.ProductID]);
NSLog(#"ded%#",[NSString stringWithFormat:#"%d",currentHotel.CartID]);
// [self.tableView1 insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
// [self.objectHolderArray removeObjectAtIndex:button.tag];
self.tableView1.delegate = self;
self.tableView1.dataSource = self;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
[self.tableView1 reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView1 reloadData];
}
- (void)cancelTouched:(UIBarButtonItem *)sender
{
// hide the picker view
[self.pickerViewTextField resignFirstResponder];
}
- (void)doneTouched:(UIBarButtonItem *)sender
{
// hide the picker view
[self.pickerViewTextField resignFirstResponder];
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
NSIndexPath *indexPath ;
if ([self.objectHolderArray objectAtIndex:indexPath.row])
{
if ([[weights objectAtIndex:row]isEqual:#"1 Kg"])
{
pickerQuantity=1;
[self.pickerViewTextField becomeFirstResponder];
[self.pickerViewTextField becomeFirstResponder];
selectWeight.hidden=YES;
[self.tableView1 reloadData];
}
else if ([[weights objectAtIndex:row]isEqual:#"2 Kg"])
{
pickerQuantity=2;
selectWeight.hidden=YES;
[self.pickerViewTextField becomeFirstResponder];
[self.tableView1 reloadData];
}
else if ([[weights objectAtIndex:row]isEqual:#"5 Kg"]) {
pickerQuantity=5;
[self.pickerViewTextField becomeFirstResponder];
selectWeight.hidden=YES;
[self.tableView1 reloadData];
}
else if ([[weights objectAtIndex:row]isEqual:#"10 Kg"]) {
pickerQuantity=10;
[self.pickerViewTextField becomeFirstResponder];
selectWeight.hidden=YES;
[self.tableView1 reloadData];
}
else{
pickerQuantity=50;
selectWeight.hidden=YES;
[self.tableView1 reloadData];
}}
selectWeight.hidden=YES;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 30;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
//---number of items(rows) in the Picker View---
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [weights count];
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
// self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 30)];
// [self.view addSubview:selectWeight];
//
//
// // Get the text of the row.
NSString *rowItem = [weights objectAtIndex: row];
////
UILabel *lblRow = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView bounds].size.width, 44.0f)];
[lblRow setTextAlignment:UITextAlignmentCenter];
[lblRow setTextColor: [UIColor blackColor]];
[lblRow setText:rowItem];
lblRow.font = [UIFont fontWithName:#"Verdana" size:12];
[lblRow setBackgroundColor:[UIColor clearColor]];
return lblRow;
}
#end
You should just call [tableView reloadData], to update info inside table view each time.

NSCoding: Save custom object and load to table view iOS

I try to understand the application to save the data. I have a custom object.
#interface CellObject : NSObject <NSCoding>
#property (nonatomic, strong) NSString *links;
#property (nonatomic, strong) NSString *title;
#property (assign) BOOL isFavorite;
#end
#import "CellObject.h"
#implementation CellObject
#synthesize title, links;
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:title forKey:#"title"];
[aCoder encodeObject:links forKey:#"links"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self){
[self setTitle:[aDecoder decodeObjectForKey:#"title"]];
[self setLinks:[aDecoder decodeObjectForKey:#"links"]];
}
return self;
}
And the controller to the table in cells which must be my objects.
#import "SettingsViewController.h"
#import "SettingsCell.h"
#import "CellObject.h"
#define kFileName #"archive"
#define kDataKey #"Data"
#implementation SettingsViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = #"Settings";
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:#"Helvetica" size:20.0f], NSFontAttributeName, nil] forState:UIControlStateNormal];
}
return self;
}
-(NSString *)dataFilePath {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFileName];
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
[_rssObjectArray removeAllObjects];
_rssObjectArray = nil;
if(!_rssObjectArray)
{
_rssObjectArray = [[NSMutableArray alloc]init];
}
_resourceTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
[_resourceTV setAutoresizesSubviews:YES];
[_resourceTV setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
[_resourceTV setDataSource:self];
[_resourceTV setDelegate:self];
[self.view addSubview:_resourceTV];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showAlert)];
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSMutableData* data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
CellObject *cellObj = [unarchiver decodeObjectForKey:kDataKey];
[unarchiver finishDecoding];
}
}
-(void)applicationWillResignActive:(NSNotification *)notification
{
CellObject *cellObj = [[CellObject alloc] init];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:cellObj forKey:kDataKey];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
}
- (void)showAlert
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Enter name" message:#"And internet adress" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
UITextField *bottomField = [alertView textFieldAtIndex:0];
[bottomField setPlaceholder:#"Name"];
UITextField *footerField = [alertView textFieldAtIndex:1];
[footerField setPlaceholder:#"Internet adress"];
footerField.secureTextEntry = NO;
alertView.tag = -1;
[alertView show];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _rssObjectArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [SettingsCell cellIdentifier];
SettingsCell *sCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!sCell)
{
sCell = [[SettingsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
CellObject *object = [_rssObjectArray objectAtIndex:indexPath.row];
sCell.linkLabel.text = object.links;
sCell.nameLabel.text = object.title;
sCell.favorite.selected = object.isFavorite;
return sCell;
}
//change rows in table
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[_rssObjectArray removeObjectAtIndex:indexPath.row];
[_resourceTV deleteRowsAtIndexPaths:#[indexPath] withRowAnimation: UITableViewRowAnimationTop];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex && (alertView.alertViewStyle == UIAlertViewStyleLoginAndPasswordInput))
{
CellObject *object = nil;
if (alertView.tag == -1) {
object = [[CellObject alloc]init];
[_rssObjectArray addObject:object];
} else {
object = [_rssObjectArray objectAtIndex:alertView.tag];
}
object.links = [[alertView textFieldAtIndex:0] text];
object.title = [[alertView textFieldAtIndex:1] text];
[_resourceTV reloadData];
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Enter name" message:#"And internet adress" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
UITextField *bottomField = [alertView textFieldAtIndex:0];
[bottomField setPlaceholder:#"Name"];
UITextField *footerField = [alertView textFieldAtIndex:1];
[footerField setPlaceholder:#"Internet adress"];
footerField.secureTextEntry = NO;
CellObject *cellObj = [_rssObjectArray objectAtIndex:indexPath.row];
bottomField.text = cellObj.links;
footerField.text = cellObj.title;
alertView.tag = indexPath.row;
[alertView show];
}
#end
On the Internet find tutorials, but they are not very helpful, tell me how to do so would object persists after restarting the application, they remained in the cells?
In your viewDidLoad:
- (void)viewDidLoad
{
// ...
if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) { // Check if the file exist.
NSMutableData* data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]]; // Retrieve the data from the file
self.rssObjectArray = [[NSKeyedUnarchiver unarchiveObjectWithData:data] mutableCopy];
}
}
And your
- (NSString *)dataFilePath
{
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"CustomFeed.plist"];
/*BOOL result = [NSKeyedArchiver archiveRootObject:self.rssObjectArray toFile:path];
// This line above erase the file when it's called, remove all the code i commented.
if(result == YES)
{
NSLog(#"Array saved");
}*/
return path;
}
With these modifications, i tested your application and it's work.

Implement Pull to Refresh for RSS Feed [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have an RSS feed in my app and I'm trying to figure out how to implement pull to refresh. Here is my code:
#import "ActionAlertsViewController.h"
#import "RSSChannel.h"
#import "RSSItem.h"
#import "WebViewController.h"
#import "DTCustomColoredAccessory.h"
#import "SVProgressHUD.h"
#implementation ActionAlertsViewController
{
UIActivityIndicatorView *loadingIndicator;
}
#synthesize webViewController;
- (void)viewDidLoad
{
UIImageView *background = [[UIImageView alloc]init];
background.image = [UIImage imageNamed:#"plain_app-background.png"];
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
[self.tableView setBackgroundView:background];
self.title = #"Action Alerts";
[[SVProgressHUD appearance]setHudBackgroundColor:[UIColor blackColor]];
[[SVProgressHUD appearance]setHudForegroundColor:[UIColor whiteColor]];
[SVProgressHUD showWithStatus:#"Loading"];
}
- (void)viewDidDisappear:(BOOL)animated
{
[SVProgressHUD dismiss];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName 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];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return 0;
NSLog(#"channel items %d", [[channel items]count]);
return [[channel items]count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// return nil;
UIImageView *image = [[UIImageView alloc]init];
image.image = [UIImage imageNamed:#"CellImage.png"];
UIImageView *background = [[UIImageView alloc]init];
background.image = [UIImage imageNamed:#"plain_app-background.png"];
UIImageView *highlightedCellImage = [[UIImageView alloc]init];
highlightedCellImage.image = [UIImage imageNamed:#"HighlightedCellImage"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"UITableViewCell"];
cell.textLabel.font=[UIFont systemFontOfSize:16.0];
}
RSSItem *item = [[channel items]objectAtIndex:[indexPath row]];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"EEE, dd MMM yyyy HH:mm:ssZ"];
NSDate *pubDate = [formatter dateFromString:[item date]];
[formatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateString = [formatter stringFromDate:pubDate];
NSLog(#"Date String: %#", dateString);
[[cell textLabel]setText:[item title]];
[[cell detailTextLabel]setText:dateString];
NSLog(#"Date: %#", [item date]);
tableView.backgroundColor = [UIColor clearColor];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.highlightedTextColor = [UIColor blueColor];
cell.textLabel.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:20.0];
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.highlightedTextColor = [UIColor blueColor];
cell.detailTextLabel.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:14.0];
cell.detailTextLabel.textColor = [UIColor whiteColor];
cell.backgroundView = image;
cell.selectedBackgroundView = highlightedCellImage;
tableView.backgroundView = background;
DTCustomColoredAccessory *accessory = [DTCustomColoredAccessory accessoryWithColor:cell.textLabel.textColor];
accessory.highlightedColor = [UIColor blueColor];
cell.accessoryView =accessory;
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
NSURL *url = [NSURL URLWithString:#"http://kyfbnewsroom.com/category/public-affairs/notifications/feed/"];
// Put that URL into an NSURLRequest
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
connection = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];
}
- (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
{
/* We are just checking to make sure we are getting the XML
NSString *xmlCheck = [[NSString alloc]initWithData:xmlData encoding:NSUTF8StringEncoding];
NSLog(#"xmlCheck = %#", xmlCheck);*/
[SVProgressHUD dismiss];
// Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:xmlData];
[parser setDelegate:self];
[parser parse];
// Get rid of the XML data as we no longer need it
xmlData = nil;
// Reload the table.. for now, the table will be empty
NSMutableArray *notActionAlerts = [NSMutableArray array];
for (RSSItem *object in channel.items) {
if (!object.isActionAlert) {
[notActionAlerts addObject:object];
}
}
for (RSSItem *object in notActionAlerts) {
[channel.items removeObject:object];
}
[[self tableView]reloadData];
NSLog(#"%#\n %#\n %#\n", channel, [channel title], [channel infoString]);
}
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
// Release the connection object, we're done with it
connection = nil;
// Release the xmlData object, we're done with it
xmlData = nil;
[SVProgressHUD dismiss];
// Grab the description of the error object passed to us
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
// Create and show an alert view with this error displayed
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[webViewController webView]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"about:blank"]]];
// 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];
[self.navigationController pushViewController:webViewController animated:YES];
// Grab the selected item
RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]];
// Construct 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];
webViewController.hackyURL = url;
// Set the title of the web view controller's navigation item
// [[webViewController navigationItem]setTitle:[entry title]];
}
#end
If you're using storyboard for that you have native support for pull-to-refresh.
Only change Refreshing to enabled and then you can hook up an action for this event.

UICollectionView Cells Loading Same Items too many times

Here is the layout of my app. I have a UICollectionView in a Tab Bar Controller. I have two different XML files located on server. Depending on subscription purchases, one of two xmls will be parsed, and each item gets added to an array, which the UICollectionView in turn displays. I use MKiCloudSync to store the NSUserDefault values across iCloud as the method to determine if a subscription is still valid or not, so the user can access the app on multiple devices.
I call [MKiCloudSync start]; on didFinishLaunchingWithOptions in the AppDelegate implementation file.
In the UICollectionViewController file, the layout is essentially this:
viewDidLoad adds listener for MKiCloudSync changes. If change is made, it runs the code to update the UI. viewWillAppear checks the NSUserDefaults to see if it should load paid or free XML, and parses based off of that. If user does not have subscription, the right bar button item allows them to purchase it, which calls the code to do so. Upon successful code, it runs the code refreshpaid which parses the paid xml.
That is the setup in theory. I ran the app on my device from Ad Hoc build, and purchased the subscription in sandbox environment. The UI Updated as it should to show the additional content available in the Paid XML.
I then deleted the app, restarted the device, and reinstalled the ad hoc build to ensure the iCloud sync was working. When the app started, it showed 11 cells for every single item (assuming somehow code to refresh got called 11 times somehow). If I navigate to another tab and come back, or click on a cell and pop back, it corrects itself and just shows 1 cell per item in the XML.
Now, here is the full code from my UICollectionView.m file:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(updatetheui) name: NSUserDefaultsDidChangeNotification object: nil];
UINib *cellNib = [UINib nibWithNibName:#"NibCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:#"cvCell"];
self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"shelves.png"]];
}
-(void)updatetheui {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *status = [defaults objectForKey:#"Pay?"];
NSString *expirationdate = [defaults objectForKey:#"expiration"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSDate *date = [dateFormat dateFromString:expirationdate];
NSLog(#"Date: %#", [dateFormat stringFromDate:date]);
if ([status isEqualToString:#"PaidUp"]|([date timeIntervalSinceNow] > 0.0)) {
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Status" style:UIBarButtonItemStyleBordered target:self action:#selector(statusofsubscription)];
self.navigationItem.leftBarButtonItem = nil;
NSLog(#"UPDATEUI PAY");
[_allEntries removeAllObjects];
[self.collectionView reloadData];
[self refreshpaid];
} else {
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Subscribe" style:UIBarButtonItemStyleBordered target:self action:#selector(buyButtonTapped:)];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Restore" style:UIBarButtonItemStyleBordered target:self action:#selector(timetorestore)];
[_allEntries removeAllObjects];
[self.collectionView reloadData];
[self refreshfree];
NSLog(#"UPDATEUI FREE");
}
}
- (void)viewWillAppear:(BOOL)animated {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *status = [defaults objectForKey:#"Pay?"];
NSString *expirationdate = [defaults objectForKey:#"expiration"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSDate *date = [dateFormat dateFromString:expirationdate];
NSLog(#"Date: %#", [dateFormat stringFromDate:date]);
if ([status isEqualToString:#"PaidUp"]|([date timeIntervalSinceNow] > 0.0)) {
[self refreshpaid];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Status" style:UIBarButtonItemStyleBordered target:self action:#selector(statusofsubscription)];
self.navigationItem.leftBarButtonItem = nil;
NSLog(#"WILLAPPEARPAID");
}
else {
[self refreshfree];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Subscribe" style:UIBarButtonItemStyleBordered target:self action:#selector(buyButtonTapped:)];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Restore" style:UIBarButtonItemStyleBordered target:self action:#selector(timetorestore)];
}
//[self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)timetorestore {
[MKiCloudSync start];
UIAlertView *syncing = [[UIAlertView alloc]initWithTitle:#"Syncing" message:#"Now attempting to restore your subscription from iCloud. If unsuccessful, your subscription may have expired, or you may need to try again in a stronger network." delegate:self cancelButtonTitle:#"Okay" otherButtonTitles: nil];
[syncing show];
[syncing release];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
NSLog(#"1");
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [_allEntries count];
NSLog(#"2");
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
[UIView animateWithDuration:5.0
delay:0
options:(UIViewAnimationOptionAllowUserInteraction)
animations:^{
NSLog(#"animation start");
[cell setBackgroundColor:[UIColor colorWithRed: 180.0/255.0 green: 238.0/255.0 blue:180.0/255.0 alpha: 1.0]];
}
completion:^(BOOL finished){
NSLog(#"animation end");
[cell setBackgroundColor:[UIColor whiteColor]];
}
];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
{
if (_webViewController2 == nil) {
self.webViewController2 = [[[WebViewController2 alloc] initWithNibName:#"WebViewController2" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController2.entry = entry;
[self.navigationController pushViewController:_webViewController2 animated:YES];
}
else {
if (_webViewController == nil) {
self.webViewController = [[[WebViewController alloc] initWithNibName:#"WebViewController" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController.entry = entry;
[self.navigationController pushViewController:_webViewController animated:YES];
}
#endif
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
static NSString *cellIdentifier = #"cvCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UIImageView *titleLabel = (UIImageView *)[cell viewWithTag:100];
UILabel *titleLabel2 = (UILabel *)[cell viewWithTag:200];
NSString *thearticleImage = entry.articleImage;
[titleLabel setImageWithURL:[NSURL URLWithString:entry.articleImage] placeholderImage:[UIImage imageNamed:#"icon#2x.png"]];
// [titleLabel2 setText:entry.articleTitle];
return cell;
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *issueTitle = [item valueForChild:#"title"];
NSString *issueURL = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
NSString *issueCoverArt = [item valueForChild:#"guid"];
NSLog(#"Title%#", issueTitle);
NSLog(#"Link%#", issueURL);
NSLog(#"Date%#", articleDateString);
NSLog(#"CoverArt%#", issueCoverArt);
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:issueTitle
articleUrl:issueURL
articleDate:articleDate
articleImage:issueCoverArt] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.collectionView reloadData];
}
}];
}
}];
}
One possibility: you should always make sure that what get displayed is always what you intended. Take this as an example: (from my WFAsyncImageCell for iOS, it is largely the same principle on OS X.)
- (void)loadImage
{
if ([self.lastLoadedURL isEqual:self.imageURL])
{
return; // The current image URL is being reloaded. Ignore.
}
self.imageView.image = nil;
NSURL *loadURL = self.imageURL;
dispatch_group_async(WFBackgroundTasks,
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0),
^
{
// Get the image data. Possible check cached data
NSData *imageData = [NSData dataWithContentsOfURL:loadURL];
UIImage *image = [[UIImage alloc] initWithData:imageData];
if (!image)
{
// Oops, image file downloaded is bad.
image = [UIImage imageNamed:#"defaultFallback"];
}
else
{
// Cache it. Not gonna implement here in the demo.
}
dispatch_async(dispatch_get_main_queue(),
^
{
if ([loadURL isEqual:self.imageURL])
{
self.imageView.image = image;
}
else
{
// Oops, reload.
[self loadImage];
}
});
});

Add only SOME items from XML to TableView

Using this tutorial, I made an iPhone blog app. It uses the count of the array created to setup the number of rows. I don't want to do every single item, because there are over 200 right now and growing. When I return any number for rows in section, it always crashes with the error about 0 beyond bounds of empty array. What else do I need to tweak from this tutorial to only allow the first 20 items to show in tableview?
UPDATE: I think I am making some progress. In the reqeustFinished method where it sorts the array, I edited it to make it this:
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[entries removeLastObject];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
NSLog(#"%#", entries);
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
Adding the line to removeLastObject for entries, removed the first item (which is ideally the ONLY one I would want on the first day). Are there other methods that would allow me to remove a range of objects at Index?
Here is the code I have for the Table View Class and DataSources.
- (void)refresh {
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:#"addressofxmlfile",
nil];
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:#selector(refreshInvoked:forState:) forControlEvents:UIControlEventValueChanged];
[self refresh];
}
-(void) refreshInvoked:(id)sender forState:(UIControlState)state {
// Refresh table here...
[_allEntries removeAllObjects];
[self.tableView reloadData];
[self refresh];
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"guid"];
NSString *articleDateString = [item valueForChild:#"pubdate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
NSString *articleImage = [item valueForChild:#"description"];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateofarticle = [dateFormatter stringFromDate:articleDate];
NSString *days = [articleImage substringFromIndex:7];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate
articleImage:articleImage
date:thedate] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
}else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
[self.refreshControl endRefreshing];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
[self refresh];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// [tableView setBackgroundColor:[UIColor redColor]];
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:11];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"Papyrus" size:19];
UIFont *cellFont2 = [UIFont fontWithName:#"Papyrus" size:17];
// cell.imageView.image = [UIImage imageNamed:#"icon#2x.png"];
cell.textLabel.text = entry.date;
cell.detailTextLabel.text = entry.articleTitle;
cell.detailTextLabel.textColor = [UIColor blackColor];
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 73.4;
}
You are assigning allEntries to new Array in the Refresh method here:
- (void)refresh {
self.allEntries = [NSMutableArray array];
The tutorial only does this in the ViewDidLoad Method. Not sure if this is a problem as i don't know exactly when/how refresh is called.
Found this answer that shows how to hide cells/rows here.

Resources