EXC_BAD_access code=1 address 0x NSURLConnection JSON - ios

Doing JSON work in my iPhone app, trying to list the json in a tableview, the json can be found here: appwhittle.com/api/db_all.php
I need this json to work with both android and ios, since i made the android app first it works without problem on the android device, but i cant seem to figure out what is wrong.
SearchViewController.m:
//
// SearchViewController.m
// Night Locations
//
// Created by Stian Wiik Instebø on 12/9/13.
// Copyright (c) 2013 Stian Wiik Instebø. All rights reserved.
//
#import "SearchViewController.h"
#import "SBJson4.h"
#interface SearchViewController ()
#end
#implementation SearchViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = #"Search for location";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://appwhittle.com/api/db_all.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
news = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[mainTableView reloadData];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The download could not complete" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
[cell release];
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"name"];
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
SearchViewController.h:
#import <UIKit/UIKit.h>
#interface SearchViewController : UIViewController {
IBOutlet UITableView *mainTableView;
NSArray *news;
NSMutableData *data;
}
#end
The error appears at the line: cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"name"]; where i get the title into one of the rows in the tableView.
What seems to be the problem, is it the formatting on the json? if it is, is there any way to get around it?
Programming for iOS 7
Any help is much appreciated!

Don't use these many lines use below code for it :
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://appwhittle.com/api/db_all.php"]];
NSData *returnData = [ NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *err = nil;
NSMutableArray *search = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
NSLog(#"Search %#",search);

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [search count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *store=#"cell";
UITableViewCell *utvc = [tableView dequeueReusableCellWithIdentifier:store];
if(utvc == nil)
{
utvc = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
}
NSString *str = [[[search valueForKey:#"locations"]objectAtIndex:indexPath.row]valueForKey:#"location"];
NSLog(#"%#", str);
return utvc;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

Try to use NSMutableArray for collecting data from connectionDidFinishLoading method.

Related

How to reloadData in tableView with didSelectedRowAtIndexPath and call group of methods in it

In my app I'm starting NSURLConnection, parsing XML, initialize array from this XML, and show it in the tableView. In ViewDidLoad I appeal to the server with a query parameter 0 , and it's returned for me string, after all conversion a have in tableView 4 rows - titles, and when i push on some of this titles, all process (connection to the server, parsing, arrays initialising, ) must be repeated. In didSelectedRowAtIndexPath I have to transmit section ID (so that the server sent me the correct data). How can I do it correctly? I'm establish connection in ViewDidLoad, how can I call it again?
My .m file:
#import "catalogViewController.h"
#import "XMLReader.h"
#interface catalogViewController ()
#end
#implementation catalogViewController
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) { } return self;
}
//-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-CONNECTIONS METHOD START-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[_receivedData release];
NSString *errorString = [[NSString alloc] initWithFormat:#"Connection failed! Error - %# %# %#", [error localizedDescription], [error description], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; NSLog(#"%#",errorString);
[errorString release];
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-GET FULL DATA HERE-=-=-=-=-=-=-=-=--=-=-=-=-=-=-
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *dataString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
NSString *testXMLString = [NSString stringWithContentsOfURL:myURL usedEncoding:nil error:nil];
// -=-=-=-=-=-=-=-=-=-=Parse the XML into a dictionary-=-=-=-=-=-=-=-=-=-=
NSError *parseError = nil;
_xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART END-=-=-=-=-=-=-=
_titleArr = [[NSArray alloc] initWithArray:[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"]];
_IDArr = [[NSArray alloc] [[[_xmlDictionary objectForKey:#"result"] objectForKey:#"id"] valueForKey:#"text"]];
_priceArr= [[NSArray alloc][[[_xmlDictionary objectForKey:#"result"] objectForKey:#"price"] valueForKey:#"text"]];
_ImageURLArr=[[NSArray alloc][[[_xmlDictionary objectForKey:#"result"] objectForKey:#"img"] valueForKey:#"text"]];
[connection release];
[_receivedData release];
[dataString release];
_didDataLoaded=TRUE;
[_myTableView reloadData]; // IBOutlet property
[self.tableView reloadData]; //default
}
//-=-=-=-=-=-=-=-=-=-=-Connection methods END-=-=-=-=-=-=-=-=-=-
- (void)viewDidLoad {
[super viewDidLoad];
_didDataLoaded=FALSE;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-=-==-=-=-=-=-=-=-=-=-=-=--=-=START Shit with connection-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=
NSString* params = #"request_params";
NSURL* url = [NSURL URLWithString:#"my URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connecting...");
_receivedData = [[NSMutableData data] retain];
} else {
NSLog(#"Connecting error");
}
}
//-=-==-=-=--=-==-=-=-=-=-=--=-==---=-=--==-=-=-=-=-TableView methods-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=--=-=-=-=-=-=-=
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_didDataLoaded == FALSE) {
return 1;
}
else return self.titleArr.count;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"creatures"];
UIImage *creatureImage = nil;
if (_didDataLoaded == FALSE) {
cell.textLabel.text=#"Downloading...";
cell.detailTextLabel.text= #"downloading...";
} else {
cell.textLabel.text = [self.titleArr objectAtIndex:indexPath.row];
cell.detailTextLabel.text= _IDArr[indexPath.row];
NSString *img = self.ImageURLArr[indexPath.row];
creatureImage =[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]]; cell.imageView.image = creatureImage;
}
return cell;
}
#end
You can move the relevant code from viewDidLoad to a specific method, something like:
- (void)loadXMLData {
// Initiate your loading/parsing
}
In viewDidLoad just call this method:
- (void)viewDidLoad {
[super viewDidLoad];
[self loadXMLData];
}
This way you can call [self loadXMLData] multiple times.
However... be careful with calling [tableView reloadData] from inside a UITableViewDelegate method implementation, as this will cause the tableview to call (at least some of the) delegate methods, which can cause recursive loops or other odd behaviour.

Parse links of a JSON file und download them

I want to create an App which parses the picture Links of a Facebook page and shows them in an iOS app (display them in tableView). But after I parsed the JSON file and added them to an array which should be downloaded nothing is displayed.
Here's the code:
- (void)viewDidLoad
{
self.edgesForExtendedLayout = UIRectEdgeNone;
[super viewDidLoad];
items = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/HuppFotografie/photos/uploaded/?fields=id,name,picture"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData = [[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"fail with error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *arrayOfData = [allDataDictionary objectForKey:#"data"];
for (NSDictionary *dicton in arrayOfData) {
NSString *picture = [dicton objectForKey:#"picture"];
[items addObject:picture];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 250.0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MyImageCell";
ImageCell *cell = (ImageCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor clearColor];
if (cell == nil) {
NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"ImageCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (ImageCell *)currentObject;
break;
}
}
}
// Here we use the new provided setImageWithURL: method to load the web image
[cell.imageView setImageWithURL:[NSURL URLWithString:[items objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:#"Placeholder.jpg"]];
cell.imageSource.text = [items objectAtIndex:indexPath.row];
return cell;
}
I really don't get why. I'm sorry if this question is stupid but I am coding just as a hobby and have not that great experience.
In fact your connection is asynchronous, so you just need to reload your table view programmatically to display loaded images:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *arrayOfData = [allDataDictionary objectForKey:#"data"];
for (NSDictionary *dicton in arrayOfData) {
NSString *picture = [dicton objectForKey:#"picture"];
[items addObject:picture];
}
// Just add this line, in order to force reload when all your data is arrived
[self.tableView reloadData];
}

Parsing multiple jSon in IOS

For my code, I am following instruction on this link http://www.youtube.com/watch?v=RJZcD3hfs3k and success,
but I want to modify to multiple JSON and failed (if i print log, that its running).
I modify in:
- (void)viewDidLoad
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
This is my modified code(ViewController.m) :
#import "ViewController.h"
#import "DetailViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"News";
//[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//before
//NSURL *url = [NSURL URLWithString:#"http://zacandcatie.com/YouTube/json.php"];
//after
NSURL *url = [NSURL URLWithString:#"http://service.berisiknews.com/article/byAll/0/3"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//before
//news = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
//[mainTableView reloadData];
//ßNSLog(#"array %#", news);
//after
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: nil];
NSArray *news = [jsonArray valueForKeyPath:#"data"];
[mainTableView reloadData];
NSLog(#"array %#", news);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The download could not complete please make sure you're connected to either 3G or Wi-Fi" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (int)numberINSectionsInTableView: (UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [news count];
//return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"title"];
//cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"date_string"];
cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"category_name"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
detailViewController.title = [[news objectAtIndex:indexPath.row] objectForKey:#"title"];
detailViewController.newsArticle = [news objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Any help?
Your news array is a local variable as your code.
In connectionDidFinishLoading, please modify as below
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: nil];
news = [jsonArray valueForKeyPath:#"data"];
[mainTableView reloadData];
NSLog(#"array %#", news);
so it will be the right news array which your are accessing in table view.
it works fine for me.
#interface AlbumViewController ()
#end
#implementation AlbumViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//navigation Controller
[self.navigationController setNavigationBarHidden:NO];
self.title=#"Album List";
//json data parsing
NSURL *url = [NSURL URLWithString:#".......your Link......"];
NSURLRequest *urlrequest = [[NSURLRequest alloc]initWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:nil error:nil];
dict_data = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.ary_data = [dict_data objectForKey:#"album"];
NSLog(#"%#",self.ary_data);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [ary_data count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#""];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
NSMutableDictionary *dic= [[ary_data objectAtIndex:indexPath.row] mutableCopy];
AlbumCellController *albumCell = [[AlbumCellController alloc]init];
[cell.contentView addSubview:albumCell.view];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
albumCell.Img_album.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:#"cover_photo"]]]];
});
albumCell.lbl_name.text = [dic objectForKey:#"title"];
albumCell.lbl_releasedate.text = [dic objectForKey:#"release_date"];
NSString *SongNo=[dic objectForKey:#"no_of_songs"];
NSLog(#"%#",SongNo);
//albumCell.lbl_songno.text=SongNo;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableDictionary *dic= [[ary_data objectAtIndex:indexPath.row] mutableCopy];
SongsViewController *songList = [[SongsViewController alloc]init];
songList.imgURL = [dic objectForKey:#"cover_photo"];
songList.Album_id = [dic objectForKey:#"album_id"];
[self.navigationController pushViewController:songList animated:YES];
}

Error Drawing JSOn into UITableviewCell

I have json like this (have dictionary and array).
I want draw all json into UItableviewcell, but its not draw there
{ data: [
{
featured: true,
price: {
currency: "IDR",
amount: 5557679,
formatted: "Rp5.558.000"
},
] }
and this is my viewcontroller.h file
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController{
IBOutlet UITableView *mainTableView;
NSURL *URL;
NSDictionary *Deals;
NSArray *Deals_array;
NSMutableData *data;
}
#end
and this is my .m file
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title=#"SOme Apps";
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
URL = [NSURL URLWithString:[NSString stringWithFormat:#"http://someurl.com"]];
NSURLRequest *request=[NSURLRequest requestWithURL:URL];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
/*dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: URL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});*/
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
data=[[NSMutableData alloc] init];
NSLog(#"%#",data);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError* error;
Deals= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Deals_array = [Deals objectForKey:#"data"]; //2
NSDictionary* loan = [Deals_array objectAtIndex:0];
NSString *test=[loan objectForKey:#"featured"];
NSLog(#"%#",test);
[mainTableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"Error");
}
////set minimum section oftableview
-(int)numberOfTableviewSection : (UITableView *) tableView
{
return 1;
}
////set length uitableview
-(int) tableView :(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [Deals_array count];
}
///declaring uitableview
-(UITableViewCell *)tableView :(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell==nil){
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
cell.textLabel.text=[[Deals_array objectAtIndex:indexPath.row] objectForKey:#"featured"];
return cell;
}
#end
but its not draw the objectkey #test, can someone help me why?
Try doing the allocation
Deals_array = [[NSArray alloc] initWithArray:[Deals objectForKey:#"data"]];

UITableView is loaded multiple times, I need help please - I don't understand why

Here is ALL my code for this specific view controller. As the title of this question states, I am seeing my UITableView loaded with the same 9 values over and over again. If I place a breakpoint in connectionDidFinishLoading and wait one second I only see the data rendered to the table view once. I have tried all sorts of things to solve this; help is very much appreciated.
#implementation MasterViewController
#synthesize response;
NSMutableData* receivedData;
NSString* hostName;
NSInteger portNumber = 9999;
NSMutableDictionary* dictionary;
NSInteger maxRetryCount = 5;
int count = 0;
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"Succeeded! Received %d bytes of data",[data length]);
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failed! Error - %# %#",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
receivedData = nil;
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
if ([result isKindOfClass:[NSArray class]]) {
for (NSArray *item in result) {
NSArray *category = [item valueForKey:#"CategoryName"];
[dataArray addObject:category];
}
}
else {
NSDictionary *jsonDictionary = (NSDictionary *)result;
for(NSDictionary *item in jsonDictionary)
NSLog(#"Item: %#", item);
}
connection = nil;
[self.tableView reloadData];
NSLog(#"Finished");
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return YES;
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
return YES;
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSString* username = #"test";
NSString* password = #"testPwd";
NSLog(#"Attempting connection with username: %#", username);
NSMutableString *loginString = (NSMutableString*)[#"" stringByAppendingFormat:#"%#:%#", username, password];
NSString *authHeader = [#"Basic " stringByAppendingFormat:#"%#", loginString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#:%i%#", hostName, portNumber, #"/api/categories"]];
NSLog(#"URL: %#", url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 1.0];
[request addValue:authHeader forHTTPHeaderField:#"Authorization"];
[NSURLConnection connectionWithRequest:request delegate:self];
if ([challenge previousFailureCount] <= maxRetryCount) {
NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
NSLog(#"Failure count %d",[challenge previousFailureCount]);
}
}
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(addNewItem)];
self.navigationItem.rightBarButtonItem = addButton;
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
- (void)addNewItem
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Product"
message:#"Enter the new product name"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[dataArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert)
{
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *object = [dataArray objectAtIndex:indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
UITextField *textField = [alertView textFieldAtIndex:0];
[dataArray addObject:textField.text];
[self.tableView reloadData];
NSLog(#"Plain text input: %#",textField.text);
NSLog(#"Alert View dismissed with button at index %d",buttonIndex);
}
- (void)viewWillAppear:(BOOL)animated {
self.title = #"Categories";
receivedData = [[NSMutableData alloc] init];
hostName = [[NSString alloc] initWithString:#"12.234.56.123"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#:%i%#", hostName, portNumber, #"/api/categories"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 1.0];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
} else {
}
dataArray = [[NSMutableArray alloc] init];
}
#end
willSendRequestForAuthenticaiton is a delegate method. Yet inside your delegate method, you are generating a brand new URL request, which in turn gets handled by the willSendRequest delegate, which generates another request, etc, which continually populates your dataArray with data.
Get rid of the url request inside the delegate method and it should fix things for you.

Resources