objective c table view cell drawn before data source - ios

The data source for my UITableview cells is in:
- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
// We are just checking to make sure we are getting the XML
NSString *xmlCheck = [[[NSString alloc] initWithData:xmlData encoding:NSWindowsCP1252StringEncoding] autorelease];
// NSLog(#"xmlCheck2 = %#", xmlCheck);
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:xmlData];
for (int i=2; i<33; i++) {
NSString *link=[NSString stringWithFormat:#"/html/body/table/tr[%d]/td",i];
NSArray *elements = [xpathParser searchWithXPathQuery:link];
NSString *date = [NSString stringWithFormat:#"%#, %#",[elements[5]text],[elements[1]text]];
[times addObject:date];
[names addObject:[elements[2]text]];
[types addObject:[elements[3]text]];
[places addObject:[elements[4]text]];
NSLog(#"%#", elements);
NSLog(#"%#", [elements[0] text]);
}
}
But the method that draws the cell is called before the connection is finished even though the connection is started before I draw the cells. How do I delay the draw cell method or make sure the connection is finished before I draw the cells?

You need to set tableview's datasource & delegate properties only after you finish loading data.
If you have set delegate & datasource of tableview from IB or Storyboard, remove it. Set delegate & datasource properties of tableview after you finish loading data. And reload table as well.
- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
// We are just checking to make sure we are getting the XML
NSString *xmlCheck = [[[NSString alloc] initWithData:xmlData encoding:NSWindowsCP1252StringEncoding] autorelease];
// NSLog(#"xmlCheck2 = %#", xmlCheck);
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:xmlData];
for (int i=2; i<33; i++) {
NSString *link=[NSString stringWithFormat:#"/html/body/table/tr[%d]/td",i];
NSArray *elements = [xpathParser searchWithXPathQuery:link];
NSString *date = [NSString stringWithFormat:#"%#, %#",[elements[5]text],[elements[1]text]];
[times addObject:date];
[names addObject:[elements[2]text]];
[types addObject:[elements[3]text]];
[places addObject:[elements[4]text]];
NSLog(#"%#", elements);
NSLog(#"%#", [elements[0] text]);
}
[tableView setDelegate:self];// set delegate, datasource & reload data.
[tableView setDatasource:self];
[tableView reloadData];
}

that's the point of ASYNCHRONOUS networking :) Your main thread doesnt wait for it to finish! synchronous is there but it's bad
Have your UI handle the case that data isnt available yet.
a) set tableview hidden, show a spinning wheel and show and reload the table when connectionDidFinish is called
mock code
-viewWillAppear {
table.hidden = YES;
spinningActivity.hidden = NO;
networkConnection start];
}
-connectionDidFinish {
spinningActivity.hidden = YES;
[table reloadData];
table.hidden = NO;
}

The method that provides cell information is only called if you tell it there are rows ready to display. If you tell it the right thing in tableView:numberOfRowsInSection: -- which could be 0 if the connection hasn't finished -- there shouldn't be any incorrect calls to tableView:cellForRowAtIndexPath:.

Related

How do you properly implement async search results?

I made a clone of UITableView called TableView with its own dataSource and delegate that mimics the original UITableView but is intended to do some things differently. I also made a GoogleSuggest class with its own delegate that requests google autocomplete suggestions from a known URL.
The GoogleSuggest class has this method:
- (void)requestSuggestionsForText:(NSString *)text {
[NSThread detachNewThreadSelector:#selector(asyncRequestSuggestionsForText:)
toTarget:self
withObject:text];
}
When called it dispatches this private background thread:
- (void)asyncRequestSuggestionsForText:(NSString *)text;
When it receives results it calls this delegate method:
- (void)googleSuggestDidReceiveResult:(GoogleSuggestResult *)result;
Everything worked fine with little controlled experiments until I put it all together in the main ViewController.
Initially, this method returned a "UI API called on a background thread" error:
#pragma mark - GoogleSuggestDelegate
- (void)googleSuggestDidReceiveResult:(GoogleSuggestResult *)result {
_googleSuggestions = result.suggestions;
[_tableView reloadData];
}
Then I replaced the last line with this and it worked:
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
Now, I'm getting a "-[__NSCFNumber length]: unrecognized selector sent to instance 0xbbe7252cd9143595" error.
The result.suggestions is a simple NSMutableArray with NSString variables, no NSNumbers anywhere.
This works and I get to see all results logged:
- (TableViewCell *)tableView:(tableView *)tableView cellAtIndex:(NSUInteger)index {
TableViewCell *cellView = [[TableViewCell alloc] init];
NSString *result = [_googleSuggestions objectAtIndex:index];
NSLog(#"Result: %#", result);
// cellView.titleLabel.text = result;
return cellView;
}
This also works and I get to see all results logged:
- (TableViewCell *)tableView:(tableView *)tableView cellAtIndex:(NSUInteger)index {
TableViewCell *cellView = [[TableViewCell alloc] init];
NSString *result = [_googleSuggestions objectAtIndex:index];
NSLog(#"Result: %#", result);
cellView.titleLabel.text = #"example text";
return cellView;
}
This fails when I try to assign the result to the titleLabel.text:
- (TableViewCell *)tableView:(tableView *)tableView cellAtIndex:(NSUInteger)index {
TableViewCell *cellView = [[TableViewCell alloc] init];
NSString *result = [_googleSuggestions objectAtIndex:index];
NSLog(#"Result: %#", result);
cellView.titleLabel.text = result;
return cellView;
}
It makes no sense, it's clearly an NSString variable assigned to an object that has no problem with NSString variables like shown in the working examples above.
How do you properly implement async search results?
How do you properly update UI elements from a background thread?

message from debugger:terminated due to memory pressure IOS?

in server side data i am getting 17000 users names.when i get 1000 user names ofter Xcode is crashing giving these error message from debugger:terminated due to memory pressure please help me how to get 17000 user names data how to handle without memory presser.i got these problem in real device.
why i am taking array in app delegate i need to use these 17000 user names in so many view controllers
I am declare array
AppDelegate.h
#property (nonatomic,retain) NSMutableArray *userNamesGettingArrayObj;
I am declare string
ModelClass.h
#property (nonatomic,strong) NSString *nameString;
ModelClass.m
// i am getting server data in these dictionary object
NSDictionary *dictobj=[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
for (int i = 0; i<=[[dictobj valueForKey:#"name"] count]-1;i++)
{
_nameString=[[dictobj valueForKey:#"name"]objectAtIndex:i];
[delegate.userNamesGettingArrayObj addObject:_nameString];
}
viewController.m
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [delegate.userNamesGettingArrayObj count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (_tableViewObj == tableView) {
static NSString *ide=#"ide";
UITableViewCell *cell=[_tableViewObj dequeueReusableCellWithIdentifier:ide];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ide];
}
cell.textLabel.text=[delegate.userNamesGettingArrayObj objectAtIndex:indexPath.row];
return cell;
}
}
I suspect that your repeated repeated repeated use of valueForKey may be the problem. Whether it is the problem or not, it is so inefficient it hurts my eyes. About 100 times faster:
NSArray* names = dictObj [#"name"];
NSMutableArray* userNames = delegate.userNamesGettingArrayObj;
for (NSString* nameString in names)
[names addObject:nameString];
17,000 names should be no problem whatsoever unless there's something wrong with your code.
valueForKey is a high-level method that is usually entirely inappropriate for processing JSON, or for accessing anything stored in a dictionary. Unless you have a very good reason (one that you could explain if asked about it), use objectForKey or just [#"someKey"].
Have to tried??
make response dict golable and
cell.textlable.text=[dictobj valueForKey:#"name"]objectAtIndex:indexpath.row];
Dont get that much data from sever at same time, use load more button or auto hit functions when your table reach at end of list.
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;{
if(nearByPlacesTableView.contentOffset.y >= (nearByPlacesTableView.contentSize.height - nearByPlacesTableView.bounds.size.height)) {
if (isPageRefresing) {
// [self performSelector:#selector(getRecords:) withObject:nextPageTokenString afterDelay:0.0f];
[self performSelectorInBackground:#selector(getRecords:) withObject:nextPageTokenString];
}
}
}
// HTTP Utility class
-(void)getRecords:(NSString *)token{
NSString *serverUrl;
if ([self.headStr isEqualToString:#"Nearby"])
{
serverUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=%#&key=AIzaSyCd2",token];
}else{
serverUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/textsearch/json?pagetoken=%#&key=AIzaSyCd2",token];
}
//Create URL and Request
NSURL * url = [NSURL URLWithString:serverUrl];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSURLResponse * response;
NSError * error = nil;
//Send Request
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error == nil)
{
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *nextpageArr = [NSMutableArray new];
nextpageArr = [[json valueForKey:#"results"] mutableCopy];
nextPageTokenString=[json valueForKey:#"next_page_token"];
for (id dict in [json valueForKey:#"results"])
{
NSMutableDictionary *mutableDict;
if ([dict isKindOfClass:[NSDictionary class]]) {
mutableDict=[dict mutableCopy];
}
else{
mutableDict=dict;
}
[mutableDict setValue:#"0" forKey:#"checked"];
[mutableDict setValue:#"0" forKey:#"is_favourite"];
[nextpageArr addObject:mutableDict];
}
NSString *status=[json valueForKey:#"status"];
if ([status isEqualToString:#"INVALID_REQUEST"]) {
isPageRefresing=NO;
}else if ([status isEqualToString:#"OK"]){
isPageRefresing=YES;
}
if (nextpageArr.count) {
[self.nearbyVenues addObjectsFromArray:nextpageArr];
}
[nearByPlacesTableView reloadData];
[SVProgressHUD dismiss];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet" message:#"Please check your internet connection." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
//i store all data into at time when i am using these code
delegate.userNamesGettingArrayObj=[[[NSArray arrayWithObject:dictobj]valueForKey:#"name"]objectAtIndex:0];

How to populate JSON data in UITableView using NSUrlConnection? [duplicate]

This question already has answers here:
populating a tableview with data using JSON and AFNetworking NSDictionary
(1 answer)
JSON data is not loading in slow internet connection? [closed]
(1 answer)
Closed 8 years ago.
I'm building an article reading app.I'm parsing JSON data using NSData in UITableView.
I'm facing an issue that is data is not load in slow internet speed(2g or 3g)means UI is empty.I want to implement NSUrlConnection
but i'm new in iOS development unable to implement NSUrlConnection in my code.
this is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
BOOL myBool = [self isNetworkAvailable];
if (myBool)
{
#try {
// for table cell seperator line color
self.tableView.separatorColor = [UIColor colorWithRed:190/255.0 green:190/255.0 blue:190/255.0 alpha:1.0];
UIBarButtonItem *backbutton1 = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStyleBordered target:nil action:nil];
[[self navigationItem] setBackBarButtonItem:backbutton1];
_Title1 = [[NSMutableArray alloc] init];
_Author1 = [[NSMutableArray alloc] init];
_Images1 = [[NSMutableArray alloc] init];
_Details1 = [[NSMutableArray alloc] init];
_link1 = [[NSMutableArray alloc] init];
_Date1 = [[NSMutableArray alloc] init];
NSData* data = [NSData dataWithContentsOfURL:ysURL];
NSArray *ys_avatars = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if(ys_avatars){
for (int j=0;j<ys_avatars.count;j++)
{
if( ys_avatars[j][#"title"]==[NSNull null] ){
[_Title1 addObject: #""];
}
else{
[_Title1 addObject:ys_avatars[j][#"title"]];
}
if( ys_avatars[j][#"author"]==[NSNull null] ){
[_Author1 addObject: #""];
}
[_Author1 addObject: ys_avatars[j][#"author"]];
if( ys_avatars[j][#"featured_img"]==[NSNull null] ){
[_Images1 addObject: #""];
}
else{
[_Images1 addObject: ys_avatars[j][#"featured_img"]];
}
if( ys_avatars[j][#"content"]==[NSNull null] ){
[_Details1 addObject: #""];
}else{
[_Details1 addObject:ys_avatars[j][#"content"]];
}
if( ys_avatars[j][#"permalink"]==[NSNull null] ){
[_link1 addObject: #""];
}
else{
[_link1 addObject:ys_avatars[j][#"permalink"]];
}
if( ys_avatars[j][#"date"]==[NSNull null] ){
[_Date1 addObject: #""];
}
else{
NSString *newStr=[ys_avatars[j][#"date"] substringToIndex:[ys_avatars[j][#"date"] length]-3];
[_Date1 addObject:newStr];
}
}
}
else
{
NSLog(#"asd");
}
}
#catch (NSException *exception) {
}
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Cellidentifier1 = #"ysTableViewCell";
ysTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];
long row = [indexPath row];
cell1.TitleLabel1.text = _Title1[row];
cell1.AuthorLabel1.text = _Author1[row];
NSString *StoryUrl = [_Images1[indexPath.row] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
if(StoryUrl) {
NSArray *subStringsUrl = [yourStoryUrl componentsSeparatedByString:#"/"];
NSString *stripedName = [subStringsUrl lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* filePath =[documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:#"%#",stripedName]];
if(filePath) {
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
if(image) {
ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
if(updateCell)
updateCell.ThumbImage1.image=image;
cell1.ThumbImage1.image=image;
} else {
dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(taskQ, ^{
NSURL *Imageurl = [NSURL URLWithString:yourStoryUrl];
NSData *data = [NSData dataWithContentsOfURL:Imageurl];
UIImage *images1 = [[UIImage alloc] initWithData:data];
NSData *imageData = UIImagePNGRepresentation(images1);
if (![imageData writeToFile:filePath atomically:NO])
{
NSLog((#"Failed to cache image data to disk"));
}
else
{
NSLog(#"the cachedImagedPath is %#",filePath);
}
dispatch_sync(dispatch_get_main_queue(), ^{
ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
if(updateCell)
updateCell.ThumbImage1.image=images1;
cell1.ThumbImage1.image=images1;
});
});
}
return cell1;
}
Help is appreciated.
Thanks in advance.
This looks really messy, and i suggest you change your whole design.
A basic and cleaner way (but probably not the best/cleanest way) :
Create class to handle outside-of-view related work (JSON parsing here)
Call that class in viewDidLoad to start parsing
Call a method that refreshes your table view with the newly parsed data when the parsing is done (in the JSON class).
That way, the table view will load your placeholders first and then reload itself when it has the data.
In my opinion, a better way would be to populate it before loading it so there is no wait time.
Can you find what you need yourself, or code it alone? or do you need help? If so, with what?
EDIT : You could/should also use the AFNetworking framework that will make your life 10 times easier with JSON/Internet related code.
I usually create a class that handles the load of my data, whether from a URL or local store. You could use AFNetworking, but there is a ton of extra stuff you might not need. The basics of using NSUrlConnection is really easy.
Try this tutorial, it will help you to understand how Apple's implementation works before you add a third party library that masks it for you.
NSUrlConnection Tutorial

Lack of Internet Connection Stops Cells from Being Created

I am creating an app that takes a JSON text from a server and translates it into a match schedule for a robotics tournament. I have custom cells that are filled with the data I receive from the site and they display the data for each individual match just fine. The problem is that when I put the matches into a .plist file ("data.plist") so that once the internet connection is established initially, the user doesn't necessarily need to reconnect to the internet once the app is killed in order to view the match schedule for the day. My code works perfectly until I don't connect to the internet. For some reason, the app never goes into the function that creates the cells once the internet connection fails. Please help!! Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
aRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://jrl.teamdriven.us/source/scripts/getElimMatchResultsJSON.php"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
aConnection = [[NSURLConnection alloc] initWithRequest:aRequest delegate:self];
if(aConnection){
receivedData = [NSMutableData data];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Connection!!" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
jrlDirectory = [paths objectAtIndex:0];
path = [jrlDirectory stringByAppendingPathComponent:#"data.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:#"data.plist"]) {
[[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle]pathForResource:#"data" ofType:#"plist"] toPath:path error:nil];
}
dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
// Prevents data from repeating itself
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData: data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection Failed" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
NSLog(#"Connection failed! Error - %# %#", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"Success! Received %d bits of data", [receivedData length]);
// Must allocate and initialize all mutable arrays before changing them
sweet16 = [[NSMutableArray alloc]init];
quarterfinals = [[NSMutableArray alloc]init];
semi = [[NSMutableArray alloc]init];
finals = [[NSMutableArray alloc]init];
dict = [[NSMutableDictionary alloc]init];
// The error is created and can be referred to if the code screws up (example in the "if(dict)" loop)
NSError *error;
dict = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&error];
matchNames = [[dict objectForKey:#"ElimMatchListResults"]allKeys];
matchNames = [matchNames sortedArrayUsingSelector:#selector(compare:)];
// Categorize the matches based on the first two letters of their match names
for (NSString *name in matchNames) {
if([[name substringToIndex:2]isEqual:#"16"]){
[sweet16 insertObject:[[dict objectForKey:#"ElimMatchListResults"] objectForKey:name] atIndex:sweet16.count];
}
else if([[name substringToIndex:2]isEqual:#"Q."]){
[quarterfinals insertObject:[[dict objectForKey:#"ElimMatchListResults"]objectForKey:name] atIndex:quarterfinals.count];
}
else if([[name substringToIndex:2]isEqual:#"S."]){
[semi insertObject:[[dict objectForKey:#"ElimMatchListResults"]objectForKey:name] atIndex:semi.count];
}
else if([[name substringToIndex:2]isEqual:#"F."]){
[finals insertObject:[[dict objectForKey:#"ElimMatchListResults"]objectForKey:name] atIndex:finals.count];
}
}
headers = [NSArray arrayWithObjects:#"Sweet 16", #"Quarterfinals", #"Semifinals", #"Finals", nil];
sections = [NSArray arrayWithObjects:sweet16, quarterfinals, semi, finals, nil];
// If the dictionary "dict" gets filled with data...
if (dict) {
[[self tableView]setDelegate:self];
[[self tableView]setDataSource:self];
// Now uses data storage so that the user only needs to initially connect to the internet and then they can keep the schedule afterwords
[dataDict setObject: [NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithArray:sections], #"sections",
[NSArray arrayWithArray:headers], #"headers",
nil]
forKey:#"Matches"];
[dataDict writeToFile:path atomically:YES];
}
else{
NSLog(#"%#", error);
}
}
// Set the number of sections based on how many arrays the sections array has within it
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [[[dataDict objectForKey:#"Matches"] objectForKey:#"sections"] count];
}
// Set the number of rows in each individual section based on the amount of objects in each array
// within the sections array
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[[dataDict objectForKey:#"Matches"] objectForKey:#"sections"] objectAtIndex:section] count];
}
// Set headers of sections from the "headers" array
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [[[dataDict objectForKey:#"Matches"] objectForKey:#"headers"] objectAtIndex:section];
}
// Create cells as the user scrolls
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"Entered Final Loop");
static NSString *cellIdentifier = #"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(!cell){
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.matchNum.text = [[[[[dataDict objectForKey:#"Matches"] objectForKey:#"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"MatchID"];
cell.red1.text = [NSString stringWithFormat:#"%#",[[[[[dataDict objectForKey:#"Matches"] objectForKey:#"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"Red 1"]];
cell.red2.text = [NSString stringWithFormat:#"%#",[[[[[dataDict objectForKey:#"Matches"] objectForKey:#"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"Red 2"]];
cell.redScore.text = [NSString stringWithFormat:#"%#", [[[[[dataDict objectForKey:#"Matches"] objectForKey:#"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"Red Score"]];
cell.blue1.text = [NSString stringWithFormat:#"%#",[[[[[dataDict objectForKey:#"Matches"] objectForKey:#"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"Blue 1"]];
cell.blue2.text = [NSString stringWithFormat:#"%#",[[[[[dataDict objectForKey:#"Matches"] objectForKey:#"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"Blue 2"]];
cell.bluescore.text = [NSString stringWithFormat:#"%#", [[[[[dataDict objectForKey:#"Matches"] objectForKey:#"sections"] objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:#"Blue Score"]];
return cell;
}
I apologize for the lengthy code, I'm just trying to make sure I got all the details in. Please ask any questions you need to in order to clarify, I'm just really stuck and flustered right now as to why it never enters the function that creates cells if it doesn't have an internet connection.
A couple of reactions:
Your fileExistsAtPath doesn't look right. Surely you should have fully qualified path, e.g.:
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle]pathForResource:#"data" ofType:#"plist"] toPath:path error:nil];
}
I'd also probably suggest you check the success of copyItemAtPath (either the return value or use the error parameter).
I assume you know that the data.plist will never be successfully refreshed before viewDidLoad finishes (because the connection is initiated asynchronously and you return immediately from initWithRequest). This code is just loading the last data.plist values while retrieving the new data proceeds (the previous error notwithstanding). Is that your expectation?
On top of my prior point, your connectionDidFinishLoading does not appear to be issuing a reloadData call for the table, so it seems like you'll always see the previous data. When the connection is done, connectionDidFinishLoading should call reloadData for the UITableView.
Minor, unrelated detail, but I'd probably initialize receivedData in the NSURLConnectionDataDelegate method didReceiveResponse (and only if that response was successful, too). It doesn't really belong in viewDidLoad.
I might also encourage you to check for failure of JSONObjectWithData. Some networking failures manifest themselves as a successful NSURLConnection request that returns an HTML page (!) reporting an error. That HTML page will fail JSONObjectWithData processing. You might want to abort your parsing routine if JSONObjectWithData returns nil or if the error object is not nil.
Found my solution. The
[[self tableView]setDelegate:self];
[[self tableView]setDataSource:self];
Was only located in the "connectionDidFinishLoading:" function, so the data sources were never set if there was no internet connection.
I really appreciated everyone's help in this problem and I have edited a lot of my code to make it work better based off of those suggestions. Thanks!

Update data in iOS TableView cells from webserver (ASIHTTPRequest, PHP, mysql)

I have tableview where is name and status. Status is changed when come apple push notification (APNS).
But I have this problem. What can I do, if notification didn't come? Or if user tap on close button of this message.
I try to update table by using ASIHTTPRequest:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
HomePageTableCell *cell = (HomePageTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
cell.nameLabel.text = [device valueForKey:#"name"];
if ([[device valueForKey:#"status"] isEqualToNumber:#1])
{
cell.status.text = #"Not configured";
cell.stav.image = [UIImage imageNamed:#"not_configured.png"];
}
if ([[device valueForKey:#"status"] isEqualToNumber:#2])
{
//some other states
}
return cell;
}
I try this to change status before cell is loading...
- (void) getStatus:(NSString *)serialNumber
{
NSURL *url = [NSURL URLWithString:#"link to my server"];
__block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
__weak ASIHTTPRequest *request_b = request;
request.delegate = self;
[request setPostValue:#"updatedevice" forKey:#"cmd"];
[request setPostValue:serialNumber forKey:#"serial_number"]; //get status of this serial number
[request setCompletionBlock:^
{
if([self isViewLoaded])
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
if([request_b responseStatusCode] != 200)
{
ShowErrorAlert(#"Comunication error", #"There was an error communicating with the server");
}
else
{
NSString *responseString = [request_b responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *result = [parser objectWithString:responseString error:nil];
status = [result objectForKey:#"status"];
NSInteger statusInt = [status intValue]; //change to int value
//here I want to change cell status in SQLite, but don't know how
//something with indexPath.row? valueForKey:#"status"???
}
}
}];
[request setFailedBlock:^
{
if ([self isViewLoaded])
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
ShowErrorAlert(#"Error", [[request_b error] localizedDescription]);
}
}];
[request startAsynchronous];
}
Or it is better way to change status in my table view if apple notification didn't come or user didn't tap on notification message? Thanks
EDIT:
I don't know how to store data to NSManagedObject *device. Can you help me with this?
I try this, but it didn't works: (on place where you write)
NSInteger statusInt = [status intValue]; //change to int value
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
[device setValue:statusInt forKey:#"status"];
EDIT2:
I get it, but problem is with reload table data
NSString *responseString = [request_b responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *result = [parser objectWithString:responseString error:nil];
NSString *status = [result objectForKey:#"status"];
NSInteger statusInt = [status intValue]; //change to int value
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
[device setValue:statusInt forKey:#"status"]; //there is problem in save statusInt
// [device setValue:#5 forKey:#"status"]; //if I do this it is ok status is integer16 type
and second problem is in that reload table data. I put there this
[self.tableView reloadData]
but It reloading again and again in loop, what is wrong? I thing there is infinite loop, if I didn't reload table data changes will be visible in next app load. I think problem is that I call
- (void) getStatus:(NSString *)serialNumber atIndexPath:(NSIndexPath *)indexPath
{}
in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
}
Better should be in viewDidLoad or viewDidApper, but I don't know how make loop for all devices and call
[self getStatus:[device valueForKey:#"serialNumber"] atIndexPath:indexPath];
on that place.
EDIT3:
what if I do it like this:
- (void)viewDidLoad
{
[self updateData];
[self.tableView reloadData];
}
-(void)updateData
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Device"];
request.returnsDistinctResults = YES;
//request.resultType = NSDictionaryResultType;
request.propertiesToFetch = #[#"serialNumber"];
NSArray *fetchedObjects = [self.managedObjectContext
executeFetchRequest:request error:nil];
NSArray *result = [fetchedObjects valueForKeyPath:#"serialNumber"];
//there I get all serialNumbers of my devices and than I call method getStatus and get "new" status and than update it in Core Data.
}
Is that good way to solve this problem? I think better will be if I call getStatus method only one times and get array of statuses.
Maybe I can set all serialNubers in one variable ('xxx','yyyy','zzz') and on server do SELECT * FROM Devices WHERE serialNumber in (serialNuber).
Do you think this could work? I don't have experience how to take data from array to string like ('array_part1','array_part2'....)
Where in your code do you call [UITableView reloadData]?
You should call reloadData on your tableview once you have retrieved the new data from the server. As your server call is async the server call will run on a separate thread while the main thread continues, therefore I presume you have the following problem...
- (void) ...
{
[self getStatus:#"SERIAL_NUMBER"];
[self reloadData]; // This will be called before the async server call above has finished
}
Therefore you are reloading the original data and therefore the new data, which may have loaded a few seconds after, wont be shown.
To fix this, adjust the [getStatus:] method to call the [UITableView reloadData] method on server response.
[request setCompletionBlock:^
{
if([self isViewLoaded])
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
if([request_b responseStatusCode] != 200)
{
ShowErrorAlert(#"Comunication error", #"There was an error communicating with the server");
}
else
{
NSString *responseString = [request_b responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *result = [parser objectWithString:responseString error:nil];
status = [result objectForKey:#"status"];
NSInteger statusInt = [status intValue]; //change to int value
// Store the server response in NSManagedObject *device,
// which will be used as the data source in the tableView:cellForRowAtIndexPath: method
// Once stored, check the tableview isn't NULL and therefore can be accessed
// As this call is async the tableview may have been removed and therefore
// a call to it will crash
if(tableView != NULL)
{
[tableView reloadData];
}
}
}
}];
ASIHTTPRequest is also no longer supported by the developers, I suggest you look into AFNetworking.
Update
In response to the problem you are now having with setting the statusInt within the device NSManagedObject
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
[device setValue:statusInt forKey:#"status"]; //there is problem in save statusInt
This is caused as statusInt is an NSInteger which is a primary datatype and not an NSObject as expected by [NSManagedObject setValue:forKey:]. From the documentation for [NSManagedObject setValue:forKey:], the methods expected parameters are as follows.
- (void)setValue:(id)value forKey:(NSString *)key
Therefore you need to pass, in this case, an NSNumber. The problem with NSInteger is that it's simply a dynamic typedef for the largest int datatype based on the current system. From NSInteger's implementation you can see the abstraction.
#if __LP64__
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
If your current system is 64-bit it will use the larger long datatype.
Now, technically the returned status value from the server can be stored as it is without any conversion as an NSString. When you need to retrieve and use the primary datatype of int you can use the [NSString intValue] method you have already used.
Although it's best practice to use a NSNumberFormatter which can be useful for locale based number adjustments and ensuring no invalid characters are present.
NSString *status = [result objectForKey:#"status"];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
NSNumber * statusNumber = [f numberFromString:status];
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
[device setValue:statusNumber forKey:#"status"];
To retrieve the primary datatype when you wish to use the int within your code, simply call the [NSNumber intValue].
NSNumber *statusNumber = [device objectForKey:#"status"];
int statusInt = [statusNumber intValue];
As for the problem you are having with the infinite loop, this is caused by called [... getStatus:atIndexPath:], which contains the method call reloadData, from within [UITableView tableView:cellForRowAtIndexPath:].
This is because reloadData actually calls [UITableView tableView:cellForRowAtIndexPath:].
Therefore your code continuously goes as the following...
Initial UITableView data load -> tableView:cellForRowAtIndexPath: -> getStatus:atIndexPath: -> Server Response -> reloadData -> tableView:cellForRowAtIndexPath: -> getStatus:atIndexPath: -> Server Response -> reloadData -> ...
Unfortunately you cant just force one cell to update, you have to request the UITableView to reload all data using reloadData. Therefore, if possible, you need to adjust your server to return an unique ID for devices so you can adjust only the updated device within your NSManagedObject.
A suggested alteration for the getStatus method could be just to use the serialNumber if this is stored within the NSManagedObject as a key.
- (void) getStatus:(NSString*)serialNumber

Resources