Xcode live news feed with multiple accounts or user - facebook

Im new to xcode.
and Im creating this facebook, twitter, instagram and youtube news feed in a tableview
at first Im trying this facebook to load multiple json
#import "ViewController.h"
#import "DetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define kQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kJSONUrl [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=1387524391527078&format=json"]
#define kJSONUrl1 [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=196934133652011&format=json"]
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#interface ViewController ()
#end
#implementation ViewController
#synthesize jsonTitles,table,jsonContent;
-(void)loadJSON:(NSData *)responseData {
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *array = [json valueForKey:#"entries"];
for (int i = 0; i < array.count; i++) {
NSArray *entry = [array objectAtIndex:i];
NSString *title = [entry valueForKey:#"title"];
NSString *content = [entry valueForKey:#"content"];
[jsonTitles addObject:title];
[jsonContent addObject:content];
}
[self.table reloadData];
}
- (void)viewDidLoad
{
self.table.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]];
jsonTitles = [[NSMutableArray alloc]init];
jsonContent = [[NSMutableArray alloc]init];
dispatch_async(kQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:kJSONUrl];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data waitUntilDone:YES];
NSData *data1 = [NSData dataWithContentsOfURL:kJSONUrl1];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data1 waitUntilDone:YES];
});
[super viewDidLoad];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [jsonTitles count];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"detailSegue" sender:nil];
// NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"detailSegue" ascending:YES];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detailSegue"]) {
DetailViewController *detail = segue.destinationViewController;
NSIndexPath *path = [self.table indexPathForSelectedRow];
detail.titleText = [jsonTitles objectAtIndex:path.row];
detail.contentText = [jsonContent objectAtIndex:path.row];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *tableCellID = #"tableCellID";
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableCellID];
UITableViewCell *cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:tableCellID];
NSString *myurl = #"http://graph.facebook.com/idoltap/picture";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myurl]];
UIImage *myimage = [[UIImage alloc] initWithData:imageData];
cell.imageView.image = myimage;
// cell.imageView.image = [UIImage imageNamed:#"background.png"];
cell.textLabel.text = #"iDOLTap";
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCellID];
}
cell.detailTextLabel.text = [jsonTitles objectAtIndex:indexPath.row];
if ([cell.detailTextLabel.text isEqual: #" "]) {
cell.detailTextLabel.text = [jsonContent objectAtIndex:indexPath.row];
}
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Is my pattern correct?
I dont know how I can load the right profile picture for each json/user and sort it by its published date.
I just want some help to fix this one in the right way.

Related

Want to display the array values in the table

Table View:
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [self.detailArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
tableView.delegate = self;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 300.0f, 30.0f)];
label.text=[NSString stringWithFormat:#"%#",[self.detailArray objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
[self.myTableView reloadData];
return cell;
}
I want to store the detail (array value) in the tableView.I used both method numberOfRowsInSection and cellForRowAtIndexPath but the table display null. How can I display?
Make property for NSMutable array in .h
#property (nonatomic,retain) NSMutableArray *detailArray;
and synthesize it in .m
#synthesize detailArray=_detailArray;
and change this line
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
to
_detailArray=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
then use _detailArray for displaying table data.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [_detailArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// _detailArray objects for date population.
}
Your Code :
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
arr = [parsedJson objectForKey:#"routes"];
dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
}
}
}
}
});
first you go to your .h file -->
#property (nonatomic, strong) NSMutableArray * detailsArray;
In .m file -->
#synthesize detailsArray;
replace this code
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
by this -->
self.detailsArray = [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"];
# using table datasource methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.detailsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.titleLabel.text = [self.detailsArray objectAtIndex: indexPath.row ];
return cell;
}
}
//Note Please set the delegate method of table , if you write the code programmatically means tableView.delgate = self;
Use this :
self.detaisArray = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view, typically from a nib.
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
NSArray *legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
[self.detaisArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
if(i == legs.count-1){
self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 400) style:UITableViewStylePlain];
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
[self.view addSubview:self.myTableView];
}
}
}
}
}
});
first checked you connect your tableview delegate set self...
second checked youn row count pr detailarray cont in numberOfRowsInSection its may b zero
1st Declare Your Array in .h
like this
#property(strong,nonatomic)NSMutableArray * name;
And intialize into .m Init() method
name=[NSMutableArray alloc]initWithObjects:#"a",#"b", nil];
// TableView Delegate Method To Display Array Data into Tableview.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return name.count; //Give Your Array Name Here.
}
- (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];
}
cell.textLabel.text=[NSString stringWithFormat:#"%#",[name objectAtIndex:indexPath.row]];
return cell;
}
Try this code.

How to keep the checkmark in a UITableView after the view disappears

I have a uitableview that's displaying multiple selections with a custom checkmark. When selected the rows value is save using NSUserDefaults. The problem is that despite the values being saved the checkmarks disappear from the table cell rows. I can't figure out why.
thanks for any help, I'm really stuck on this.
Here's the .h code:
#interface CategoriesViewController : UITableViewController {
NSString *selectedCategoryTableString;
NSString *jsonStringCategory;
int prev;
}
// arForTable array will hold the JSON results from the api
#property (nonatomic, retain) NSArray *arForTable;
#property (nonatomic, retain) NSMutableArray *arForIPs;
#property (nonatomic, retain) NSMutableArray *categorySelected;
#property (nonatomic, retain) NSString *jsonStringCategory;
#property(nonatomic, retain) UIView *accessoryView;
#end
and the .m code:
#implementation CategoriesViewController
#synthesize jsonStringCategory;
#synthesize arForTable = _arForTable;
#synthesize arForIPs = _arForIPs;
- (void)viewDidLoad
{
[super viewDidLoad];
self.arForIPs=[NSMutableArray array];
self.categorySelected = [[NSMutableArray alloc] init];
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
-(void) reloadMain {
jsonString = #"http:///******";
// Download the JSON
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
// Create parser
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
itemsTMP = [results objectForKey:#"results"];
self.arForTable = [itemsTMP copy];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arForTable count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
UIImageView *cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
UIImageView *cellAccessoryNoneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#""]] ;
if([self.arForIPs containsObject:indexPath]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
// Get item from tableData
NSDictionary *item = (NSDictionary *)[_arForTable objectAtIndex:indexPath.row];
// encoding fix
NSString *utf8StringTitle = [item objectForKey:#"name"];
NSString *correctStringTitle = [NSString stringWithCString:[utf8StringTitle cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
cell.textLabel.text = [correctStringTitle capitalizedString];
NSNumber *num = [item objectForKey:#"id"];
cell.detailTextLabel.text = [num stringValue];
cell.detailTextLabel.hidden = YES;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if([self.arForIPs containsObject:indexPath]){
[self.arForIPs removeObject:indexPath];
[self.categorySelected removeObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
} else {
[self.arForIPs addObject:indexPath];
[self.categorySelected addObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
NSLog(#"%# categorySelected",self.categorySelected);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(#"%# defaults categorySelected",[defaults arrayForKey:#"selectedCategoryTableString"]);
NSString *string = [self.categorySelected componentsJoinedByString:#","];
[defaults setObject:string forKey:#"selectedCategoryTableString"];
NSLog(#"%# STRING",string);
}
[tableView reloadData];
}
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:NO];
[self.navigationController setNavigationBarHidden:YES animated:NO];
self.navigationController.toolbarHidden = YES;
}
First of all your code has lots of memory leaks, please do use the static analyzer and/or instruments to fix them, few for them are pretty obvious like you initialized the SBJSON parser and did not release it, itemsTMP is another.
I have rewritten your code to be much more efficient and memory friendly:
#interface CategoriesViewController : UITableViewController
{
NSArray *_items;
NSMutableArray *_selectedItems;
UIImageView *cellAccessoryImageView;
}
#end
#implementation CategoriesViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_selectedItems = [NSMutableArray new];
cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
- (void)reloadMain
{
NSString *jsonString = #"http:///******";
// Download the JSON
jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
// Create parser
SBJSON *parser = [SBJSON new];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
if (_items) [_items release];
_items = [[results objectForKey:#"results"] copy];
[parser release];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
// preloaded image will help you have smoother scrolling
cell.accessoryView = cellAccessoryImageView;
}
else
{
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryNone;
}
// Get item from tableData
cell.textLabel.text = [[NSString stringWithCString:[[item objectForKey:#"name"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] capitalizedString];
cell.detailTextLabel.text = [[item objectForKey:#"id"] stringValue];
cell.detailTextLabel.hidden = YES;
item = nil;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
[_selectedItems removeObject:item];
}
else
{
[_selectedItems addObject:item];
}
item = nil;
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)dealloc
{
[_selectedItems release];
[cellAccessoryImageView release];
[super dealloc];
}
#end
Since in your table there is only one section. Try this approach and this will help you certainly.
In - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath write following code;
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
And in - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath write code as below,
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
[self.arForIPs removeObject:[NSNumber numberWithInt:indexPath.row]];
} else {
[self.arForIPs addObject:[NSNumber numberWithInt:indexPath.row]]
}

Second view in UITableView will not display parsed data from JSON

I have a parsed data from JSON file. It works like a charm in the first view of my UITableView. However, it displays a blank second view when I tap on an item.
MasterView.h
#interface MasterViewController : UITableViewController
{
NSArray *json;
}
#property (nonatomic, retain) NSArray *json;
#end
MasterView.m
#import "MasterViewController.h"
#import "InformationViewController.h"
#interface MasterViewController ()
#end
#implementation MasterViewController
#synthesize json;
- (void)viewDidLoad
{
[super viewDidLoad];
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://j4hm.t15.org/ios/console.php"]];
[self performSelectorOnMainThread: #selector(fetchedData:) withObject: jsonData waitUntilDone: YES];
}
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
self.json = [NSJSONSerialization JSONObjectWithData: responseData options: kNilOptions error: &error];
NSLog(#"String is %#", self.json);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [json count];
}
// Customize the appearance of table view cells.
- (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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text = [[json objectAtIndex: indexPath.row] objectForKey: #"Console"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
InformationViewController *informationViewController = [[InformationViewController alloc] initWithStyle:UITableViewStylePlain];
informationViewController.title = [[json objectAtIndex: indexPath.row] objectForKey: #"Console"];
informationViewController.Information = [[json objectAtIndex: indexPath.row] objectForKey: #"Model"];
NSLog(#"String is %#", informationViewController.Information);
[self.navigationController pushViewController: informationViewController animated:YES];
}
InformationView.h
#interface InformationViewController : UITableViewController
#property (nonatomic, strong) NSArray * Information;
#end
InformationView.m
#interface InformationViewController ()
#end
#implementation InformationViewController
#synthesize Information;
- (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];
}
// Configure the cell...
cell.textLabel.text = [[Information objectAtIndex: indexPath.row] objectForKey: #"Model"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
Here i Posted Another Answer Just Because i don't want to Generate Confusion.
The Project Code : http://www.cogzentappz.com/demo/iostutorial/TestJson.zip
instead of passing the Selected Value, Pass the Whole Array through NSUsedDefaults And Retrive them Using Following Code.
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
self.json = [NSJSONSerialization JSONObjectWithData: responseData options: kNilOptions error: &error];
NSLog(#"String is %#", self.json);
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *arrayObj = [[NSMutableArray alloc] init];
for(int i = 0 ; i<[self.json count] ; i++) {
[arrayObj addObject:[json objectAtIndex:i]]];
}
[standardDefaults setObject:arrayObj forKey:#"longArray"];
[arrayObj release];
}
In the Next View you can Retrive the data Using the Below method.
in ViewDidLoad of informationViewcontroller use This
//reading
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSArray *arrayObj = [standardDefaults objectForKey:#"longArray"];
for(int i = 0 ; i<[arrayObj count] ; i++) {
NSLog(#"String is %#",[arrayObj objectAtIndex:i]);
}
As per Your Link The Json Output is like Below :
NSArray-->NSDictionary-->NSArray-->NSDictionary-->NSArray-->NSDictionary
Go to the link : http://json.bloople.net and Post all your json output and Hit enter.
So you have to get the values According to that format.
for(int i = 0 ; i<[self.json count] ; i++) {
NSArray *info_Array=[[self.json objectAtIndex:i ]valueForKey:#"Information"];
NSLog(#"info_Array is %#", info_Array);
for(int j = 0 ; j<[info_Array count] ; j++)
{
NSLog(#"Model is %#", [[info_Array objectAtIndex:j ]valueForKey:#"Model"]);
NSArray *title_Array=[[info_Array objectAtIndex:j ]valueForKey:#"Title"];
for(int k = 0 ; k<[title_Array count] ; k++)
{
NSLog(#"Game is %#", [[title_Array objectAtIndex:k ]valueForKey:#"Game"]);
NSLog(#"Publisher is %#", [[title_Array objectAtIndex:k ]valueForKey:#"Publisher"]);
}
}
NSString *Console_string= [[dataArray objectAtIndex:i ]valueForKey:#"Console"];
NSLog(#"String is %#", Console_string);
}
NSString *Console_string= [[self.Json objectAtIndex:i ]valueForKey:#"Console"];
NSLog(#"String is %#", Console_string);
}
I think you have to reloadData after you fetch your data. Right now, you specify that the NSArrray *json is empty, since the count returns 0. Thus, you prohibit the table view from being filled. Call [tableView reloadData]; after you fetch your data.
Change your code of MaterView.m with this
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
InformationViewController *informationViewController = [[InformationViewController alloc] initWithStyle:UITableViewStylePlain];
informationViewController.title = [[json objectAtIndex: indexPath.row] objectForKey: #"Console"];
informationViewController.Information = [[json objectAtIndex: indexPath.row] objectForKey: #"Model"];
NSLog(#"String is %#", informationViewController.Information);
[self.navigationController pushViewController: informationViewController animated:YES];
}
Hope it helps you...

IPhone - Images making scrolling and other functionality to crash

Everytime i load images in a tableview and try to scroll the table view i get a crash in my simulator but no errors are showing. Could this be that there is to much memory being used.
Below is the code for 1 out the three views:
#import "ResultViewController.h"
#import "JobAddSiteViewController.h"
#import "SpecificAddViewController.h"
#import "JobAddSiteAppDelegate.h"
#import "JSONKit.h"
#implementation ResultViewController
#synthesize listData;
#synthesize listLocation;
#synthesize listPostDate;
#synthesize listLogo;
#synthesize listDescription;
#synthesize uiTableView;
#synthesize buttonPrev;
#synthesize buttonNext;
NSInteger *countPage = 1;
NSMutableArray *tempArray;
NSMutableArray *tempArray2;
NSMutableArray *tempArray3;
NSMutableArray *tempArray4;
NSMutableArray *tempArray5;
-(IBAction)done{
JobAddSiteViewController *second = [[JobAddSiteViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];
[second release];
}
-(void)loadData{
NSString *strURL2 = [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/totaljobs.php", ""];
NSData *nsData2 = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL2]];
NSString *dataResult = [[NSString alloc] initWithData:nsData2 encoding:NSUTF8StringEncoding];
tempArray = [[NSMutableArray alloc] init];
tempArray2 = [[NSMutableArray alloc] init];
tempArray3 = [[NSMutableArray alloc] init];
tempArray4 = [[NSMutableArray alloc] init];
tempArray5 = [[NSMutableArray alloc] init];
NSString *strURL = [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/appresults3.php?pg=%d", countPage];
NSData *nsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL]];
NSDictionary *listDictionary = [nsData objectFromJSONData];
NSArray* people =[listDictionary objectForKey:#"jobs"];
for (NSDictionary *person in people) {
NSString *str = [NSString stringWithFormat:#"%#", [person valueForKey:#"position"]];
NSString *str2 = [NSString stringWithFormat:#"%#", [person valueForKey:#"subcounty"]];
NSString *str3 = [NSString stringWithFormat:#"%#", [person valueForKey:#"postdate"]];
NSString *str4 = [NSString stringWithFormat:#"%#", [person valueForKey:#"logo"]];
NSString *str5 = [NSString stringWithFormat:#"%#", [person valueForKey:#"description"]];
if(![str isEqualToString:#"<null>"])
{
NSString *position = [person objectForKey:#"position"];
[tempArray addObject: position];
if(![str2 isEqualToString:#"<null>"])
{
NSString *subcounty = [person objectForKey:#"subcounty"];
[tempArray2 addObject: subcounty];
}
else{
[tempArray2 addObject: #"-"];
}
if(![str3 isEqualToString:#"<null>"])
{
NSString *postDate = [person objectForKey:#"postdate"];
[tempArray3 addObject: postDate];
}
else{
[tempArray3 addObject: #"-"];
}
if(![str4 isEqualToString:#"<null>"])
{
NSString *logo = [person objectForKey:#"logo"];
[tempArray4 addObject: [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/employers/logo/Files/%#", logo]];
}
else{
[tempArray4 addObject: [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/employers/logo/Files/%#", "noimage.gif"]];
}
if(![str5 isEqualToString:#"<null>"])
{
NSString *description = [person objectForKey:#"description"];
[tempArray5 addObject: description];
}
else{
[tempArray5 addObject: #"-"];
}
}
}
if (countPage == 1) {
[self.buttonPrev setEnabled:FALSE];
}
else {
[self.buttonPrev setEnabled:TRUE];
}
NSInteger val = [dataResult intValue];
NSInteger pageEnd = val/10;
if (countPage < pageEnd) {
[self.buttonNext setEnabled:TRUE];
}
else {
[self.buttonNext setEnabled:FALSE];
}
//NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"iPhone", #"iPod",#"iPad",nil];
self.listData = tempArray;
self.listLocation = tempArray2;
self.listPostDate = tempArray3;
self.listLogo = tempArray4;
self.listDescription = tempArray5;
[self.listData release];
[self.listLocation release];
[self.listPostDate release];
[self.listLogo release];
[self.listDescription release];
tempArray = nil;
tempArray2 = nil;
tempArray3 = nil;
tempArray4 = nil;
tempArray5 = nil;
}
- (void)viewDidLoad {
[self loadData];
[super viewDidLoad];
}
- (void)dealloc {
[tempArray dealloc];
[tempArray2 dealloc];
[tempArray3 dealloc];
[tempArray4 dealloc];
[tempArray5 dealloc];
[self.listData dealloc];
[self.listLocation dealloc];
[self.listPostDate dealloc];
[self.listLogo dealloc];
[self.listDescription dealloc];
[super dealloc];
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (IBAction)prev{
countPage = countPage - 1;
[self.listData removeAllObjects];
[self.listLocation removeAllObjects];
[self.listPostDate removeAllObjects];
[self.listLogo removeAllObjects];
//NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"1", #"2",#"3",nil];
//self.listData = array;
[self loadData];
[self.uiTableView reloadData];
}
- (IBAction)next{
countPage = countPage + 1;
[self.listData removeAllObjects];
[self.listLocation removeAllObjects];
[self.listPostDate removeAllObjects];
[self.listLogo removeAllObjects];
//NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"1", #"2",#"3",nil];
//self.listData = array;
[self loadData];
[self.uiTableView reloadData];
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
JobAddSiteAppDelegate *ja = (JobAddSiteAppDelegate *)[[UIApplication sharedApplication] delegate];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews){
if ([view isKindOfClass:[UILabel class]]){
UILabel *label = (UILabel *)view;
if (label.tag == 1) {
ja.jobText = label.text;
}
if (label.tag == 2) {
ja.locationText = label.text;
}
if (label.tag == 3) {
ja.dateText = label.text;
}
if (label.tag == 4) {
}
if (label.tag == 5) {
ja.specificText = label.text;
}
}
if ([view isKindOfClass:[UIImageView class]]){
UIImageView *image = (UIImageView *)view;
if (image.tag = 4){
ja.logoText = image.image;
}
}
}
SpecificAddViewController *second = [[SpecificAddViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];
[second release];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath
*)indexPath
{
if (indexPath.section == 1 && indexPath.row == 1) {
return 65;
}
return 65;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
UILabel *labelMain;
UILabel *labelLocation;
UILabel *labelDate;
UIImageView *image;
UILabel *ref;
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
image = [[[UIImageView alloc] initWithFrame:CGRectMake(0,3,80,62)] autorelease];
image.tag = 4;
[cell.contentView addSubview:image];
labelMain = [[[UILabel alloc] initWithFrame:CGRectMake(90,3,200,20)] autorelease];
labelMain.tag = 1;
labelMain.font = [UIFont systemFontOfSize:14.0];
[cell.contentView addSubview:labelMain];
labelLocation = [[[UILabel alloc] initWithFrame:CGRectMake(90,20,200,20)] autorelease];
labelLocation.tag = 2;
labelLocation.font = [UIFont systemFontOfSize:12.0];
labelLocation.textColor = [UIColor darkGrayColor];
[cell.contentView addSubview:labelLocation];
labelDate = [[[UILabel alloc] initWithFrame:CGRectMake(90,40,200,20)] autorelease];
labelDate.tag = 3;
labelDate.font = [UIFont systemFontOfSize:12.0];
labelDate.textColor = [UIColor darkGrayColor];
[cell.contentView addSubview:labelDate];
ref = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)] autorelease];
ref.tag = 5;
[cell.contentView addSubview:ref];
}
[(UILabel *)[cell.contentView viewWithTag:1] setText:[self.listData objectAtIndex:indexPath.row]];
[(UILabel *)[cell.contentView viewWithTag:2] setText:[self.listLocation objectAtIndex:indexPath.row]];
[(UILabel *)[cell.contentView viewWithTag:3] setText:[self.listPostDate objectAtIndex:indexPath.row]];
[(UILabel *)[cell.contentView viewWithTag:5] setText:[self.listDescription objectAtIndex:indexPath.row]];
NSString *imagePath = [self.listLogo objectAtIndex:indexPath.row];
image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]]];
return cell;
}
#end
The call
image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]]];
will block the execution thread and being indeterminately long in terms of network use this is a bad thing. Each of your cells needs to wait to the image to load.
Check out "lazy loading of tableView cells" as a research topic.
Instead you should give the URL to the cell and tell it to load the image off the main thread.
as in
[cell loadImageAtURL:someURL];
and within a UITableViewCell subclass implementation
-(void)loadImageAtURL:(NSURL *)aurl
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:aurl];
if (data) {
UIImage *image = [UIImage imageWithData:data];
//must update UI on main queue
dispatch_async(dispatch_get_main_queue() ,^{
self.cellImageView = image;
}
}
});
}
Theres also a ton of Obj-C image loaders . EGOCache is my go to library but have a look round.
In summary the cell needs to own the image load process not the tableview because theres no guarantee that the cell will not be reused before the image loads and displays.
NSInteger is a primitive type, which means it can be stored locally on the stack. You don't need to use a pointer to access it. The way you are using it i think is a problem, getting the pointer value instead of the actual value of the primitive type.
I think this is what you want for the declaration/initialization of countPage:
NSInteger countPage = 1;

UITableView - methods are not being called

I have a subview in which I build a UITableview, I've set the delegate and datasource to the subview but for some reason the table methods are not being called...can someone look over my code and see what I am doing wrong? Thanks
.h file
#interface TwitterController : UIView <UITableViewDelegate, UITableViewDataSource> {
UIButton* btnCloseView;
UITableView* tblTweets;
UIImageView* imgTwitterIcon;
ColorController* colorManager;
NSMutableArray* tweetsArray;
NSMutableArray* tableData;
NSString* twitterID;
}
#property (nonatomic, retain) NSString* twitterID;
- (NSMutableArray* ) getTweets;
- (void) sendNotification : (id) sender;
#end
.m file
#import "TwitterController.h"
#implementation TwitterController
#synthesize twitterID;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
colorManager = [ColorController new];
}
return self;
}
/*- (void)drawRect:(CGRect)rect {
}*/
- (void)layoutSubviews {
imgTwitterIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"imgTwitterBird"]];
CGRect twitterIconFrame = [imgTwitterIcon frame];
twitterIconFrame.origin.x = 50.0;
twitterIconFrame.origin.y = 20.0;
tblTweets = [[UITableView alloc] initWithFrame:CGRectMake(50.0, 25.0, 220.0, 500.0)];
tblTweets.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
tblTweets.separatorColor = [colorManager setColor:176.0:196.0:222.0];
tblTweets.layer.borderWidth = 1.0;
tblTweets.rowHeight = 20.0;
tblTweets.scrollEnabled = YES;
tblTweets.delegate = self;
tblTweets.dataSource = self;
tableData = [self getTweets];
UIImage* imgCloseButton = [UIImage imageNamed:#"btnCloseWindow.png"];
CGSize imageSize = imgCloseButton.size;
btnCloseView = [[UIButton alloc] initWithFrame: CGRectMake(220.0, 550.0, imageSize.width, imageSize.height)];
[btnCloseView setImage:[UIImage imageNamed:#"btnCloseWindow.png"] forState:UIControlStateNormal];
[btnCloseView addTarget:self action:#selector(sendNotification:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:tblTweets];
[self addSubview:imgTwitterIcon];
[self addSubview:btnCloseView];
}
- (NSMutableArray*) getTweets {
//array to hold tweets
tweetsArray = [[NSMutableArray alloc] init];
twitterID = #"Pruit_Igoe";
///set up a NSURL to the twitter API
NSURL* twitterAPI = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=%#&count=10", twitterID]];
//get last 10 tweets (max is 20)
TWRequest *twitterRequest = [[TWRequest alloc] initWithURL:twitterAPI
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[twitterRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200) {
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *tweetsDict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
for(NSDictionary* thisTweetDict in tweetsDict) {
[tweetsArray addObject:[thisTweetDict objectForKey:#"text"]];
}
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
return tweetsArray;
}
#pragma mark Table Management
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [tableData count];
NSLog(#"%i", [tableData count]); //does not log!
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"tableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.textColor = [UIColor colorWithRed:66.0/255.0 green:66.0/255.0 blue:66.0/255.0 alpha:1];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size: 13.0];
cell.textLabel.text = [tweetsArray objectAtIndex:indexPath.row];
CGRect cellFrame = [cell frame];
cellFrame.size.height = 25.0;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString* thisTweet = [tableData objectAtIndex:indexPath.row];
}
#pragma mark Close Window
- (void) sendNotification : (id) sender {
NSMutableDictionary* userData = [[NSMutableDictionary alloc] init];
[userData setObject:#"closeTwitter" forKey:#"theEvent"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"theMessenger" object:self userInfo: userData];
}
#end
I think you are not allocate and initialize tableData. Write it tableData = [[NSMutableArray alloc] init]; in - (id)initWithFrame:(CGRect)frame method or - (void)layoutSubviews method. Just try it.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(#"%i", [tableData count]);
return [tableData count];
//NSLog(#"%i", [tableData count]); //does not log!
}
If the output is zero, tableData array is empty. Check it tableData array
You should do all the initialization (tblTweets for example) in initWithFrame:.
layoutSubviews is ment for laying out subviews.
In fact your code will (should) work if you move all the code fromLayoutSubviews to initWithFrame:. You can then move parts of the code (the laying out part) back.
EDIT: when you move initializing code you will probably also have to add [tblTweets reloadData]; right after tableData = [self getTweets];