Why doesn't my program work in NSURLConnection before tableView?
// MyLoxFileTVContoller.m
#import "MyLoxFileTVContoller.h"
#import "xml_myloxfile.h"
#import "DetailViewController.h"
#implementation MyLoxFileTVContoller
#synthesize myloxfileArray;
#synthesize exportId_data_Array,readFG_data_Array,receiverId_data_Array,referenceId_data_Array,referenceName_data_Array,reportFullPath_data_Array,reportName_data_Array,senderId_data_Array,senderName_data_Array,sentDate_data_Array,subject_data_Array;
#synthesize detailViewController;
#synthesize window = _window;
#synthesize navigationController;
#synthesize delegate;
#synthesize unReadCount;
#synthesize webData;
-(void)doParse{
NSLog(#"doParse"); //debug
[myloxfileArray removeAllObjects];
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:con=\"http://controller.exportingreportwebservice.lox.org/\">\n"
"<soapenv:Header/>\n"
"<soapenv:Body>\n"
"<con:getReport>\n"
"<arg0>%#</arg0>\n"
"</con:getReport>\n"
"</soapenv:Body>\n"
//"</soapenv:Envelope>\n", nameInput.text
"</soapenv:Envelope>\n", #"2711"
];
//NSLog(soapMessage);
NSURL *url = [NSURL URLWithString:#"http://iloxley.loxley.co.th:8081/ExportingReportWebservice/ExportingReportWebservice?wsdl"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
NSLog(#"if theConnection"); //debug
webData = [NSMutableData data];
}
else
{
NSLog(#"theConnection is NULL");
}
NSLog(#"end doParse"); //debug
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"connection didReceiveResponse"); //debug
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"connection didReceiveData"); //debug
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading"); //debug
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
//NSLog(#"theXML = %# ", theXML);
//NSLog(#"webData = %# ", webData);
//NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:theXML];
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithData: webData];
// create and init our delegate
xml_myloxfile_Parser *parser = [[xml_myloxfile_Parser alloc] initXMLParser];
//set delegate
[nsXmlParser setDelegate:parser];
//parsing...
BOOL success = [nsXmlParser parse];
if (success) {
NSLog(#"if success"); //debug
exportId_data_Array = [parser getExportId_data_Array];
readFG_data_Array = [parser getReadFG_data_Array];
receiverId_data_Array = [parser getReceiverId_data_Array];
referenceId_data_Array = [parser getReferenceId_data_Array];
referenceName_data_Array = [parser getReferenceName_data_Array];
reportFullPath_data_Array = [parser getReportFullPath_data_Array];
reportName_data_Array = [parser getReportName_data_Array];
senderId_data_Array = [parser getSenderId_data_Array];
senderName_data_Array = [parser getSenderName_data_Array];
sentDate_data_Array = [parser getSentDate_data_Array];
subject_data_Array = [parser getSubject_data_Array];
items_exportId = exportId_data_Array;
items_readFG = readFG_data_Array;
items_receiverId = receiverId_data_Array;
items_referenceId = referenceId_data_Array;
items_referenceName = referenceName_data_Array;
items_reportFullPath = reportFullPath_data_Array;
items_reportName = reportName_data_Array;
items_senderId = senderId_data_Array;
items_senderName = senderName_data_Array;
items_sentDate = sentDate_data_Array;
items_subject = subject_data_Array;
NSLog(#"items_subject = %# ", items_subject);
} else {
NSLog(#"fail");
}
}
-(void) loadView
{
NSLog(#"loadView"); //debug
if (items_subject == nil) {
//items_subject = [NSMutableArray arrayWithObjects:#"1",#"2",#"3",nil];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(#"numberOfSectionsInTableView"); //debug
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"tableView numberOfRowsInSection"); //debug
// Return the number of rows in the section.
NSLog(#"[items_subject count] = %d ", [items_subject count]);
return [items_subject count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"tableView cellForRowAtIndexPath"); //debug
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
//cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"%#" ,[items_subject objectAtIndex:indexPath.row]];
// Populate the cell's detail text label.
NSString *detailText = [NSString stringWithFormat:#"date: %# from: %# reference: %#",
[[items_sentDate objectAtIndex:indexPath.row] lowercaseString],[[items_senderName objectAtIndex:indexPath.row] lowercaseString],[[items_referenceName objectAtIndex:indexPath.row] lowercaseString]];
[[cell detailTextLabel] setText:detailText];
//CGAffineTransform translate = CGAffineTransformMakeTranslation(10.0, 0.0);
//[[cell detailTextLabel] setTransform:translate];
//unReadCount = 0;
if([[items_readFG objectAtIndex:indexPath.row] isEqualToString:#"N"]){
cell.textLabel.textColor = [UIColor redColor];
unReadCount = unReadCount+1;
}else{
cell.textLabel.textColor = [UIColor blackColor];
unReadCount = unReadCount;
}
NSLog(#"unReadCount = %d ",unReadCount);
//Adding A Badge Number
//[[UIApplication sharedApplication] setApplicationIconBadgeNumber:unReadCount];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"tableView didSelectRowAtIndexPath"); //debug
//sof2
DetailViewController *detailController = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:nil];
[detailController changeExportIdText:[exportId_data_Array objectAtIndex:indexPath.row]];
[detailController changeReadFGText:[readFG_data_Array objectAtIndex:indexPath.row]];
[detailController changeReceiverIdText:[receiverId_data_Array objectAtIndex:indexPath.row]];
[detailController changeReferenceIdText:[referenceId_data_Array objectAtIndex:indexPath.row]];
[detailController changeReferenceNameText:[referenceName_data_Array objectAtIndex:indexPath.row]];
[detailController changeReportFullPathText:[reportFullPath_data_Array objectAtIndex:indexPath.row]];
[detailController changeReportNameText:[reportName_data_Array objectAtIndex:indexPath.row]];
[detailController changeSenderIdText:[senderId_data_Array objectAtIndex:indexPath.row]];
[detailController changeSenderNameText:[senderName_data_Array objectAtIndex:indexPath.row]];
[detailController changeSentDateText:[sentDate_data_Array objectAtIndex:indexPath.row]];
[detailController changeSubjectText:[subject_data_Array objectAtIndex:indexPath.row]];
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
if([delegate respondsToSelector:#selector(showItemDetails:)])
{
//[delegate showItemDetails:[subject_data_Array objectAtIndex:indexPath.row]];
[delegate showItemDetails:[NSString stringWithFormat:#"%#||%#||%#||%#||%#||%#||%#||%#||%#||%#||%#"
,[exportId_data_Array objectAtIndex:indexPath.row]
,[readFG_data_Array objectAtIndex:indexPath.row]
,[receiverId_data_Array objectAtIndex:indexPath.row]
,[referenceId_data_Array objectAtIndex:indexPath.row]
,[referenceName_data_Array objectAtIndex:indexPath.row]
,[reportFullPath_data_Array objectAtIndex:indexPath.row]
,[reportName_data_Array objectAtIndex:indexPath.row]
,[senderId_data_Array objectAtIndex:indexPath.row]
,[senderName_data_Array objectAtIndex:indexPath.row]
,[sentDate_data_Array objectAtIndex:indexPath.row]
,[subject_data_Array objectAtIndex:indexPath.row]
]];//test multi var'
}
// Alert will pop up when using Simulator or iPod Touch for example
/*
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[note_subject_data_Array objectAtIndex:indexPath.row] message:#"Test" delegate:nil cancelButtonTitle:#"Close" otherButtonTitles:nil];
[alert show];
*/
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
NSLog(#"viewDidLoad"); //debug
[self doParse];
[super viewDidLoad];
}
- (void)viewDidUnload
{
NSLog(#"viewDidUnload"); //debug
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
The log:
2012-09-11 15:27:15.377 MyLoxFile[2698:f803] loadView
2012-09-11 15:27:15.378 MyLoxFile[2698:f803] viewDidLoad
2012-09-11 15:27:15.379 MyLoxFile[2698:f803] doParse
2012-09-11 15:27:15.382 MyLoxFile[2698:f803] if theConnection
2012-09-11 15:27:15.382 MyLoxFile[2698:f803] end doParse
2012-09-11 15:27:15.385 MyLoxFile[2698:f803] numberOfSectionsInTableView
2012-09-11 15:27:15.386 MyLoxFile[2698:f803] tableView numberOfRowsInSection
2012-09-11 15:27:15.391 MyLoxFile[2698:f803] [items_subject count] = 0
2012-09-11 15:27:15.454 MyLoxFile[2698:f803] connection didReceiveResponse
2012-09-11 15:27:15.455 MyLoxFile[2698:f803] connection didReceiveData
2012-09-11 15:27:15.455 MyLoxFile[2698:f803] connectionDidFinishLoading
2012-09-11 15:27:15.455 MyLoxFile[2698:f803] DONE. Received Bytes: 1948
2012-09-11 15:27:15.457 MyLoxFile[2698:f803] if success
2012-09-11 15:27:15.457 MyLoxFile[2698:f803] items_subject = (
"Surgical Report ",
"Genotype Report",
"HPV Report"
)
It has data in array but not have in tableView numberOfRowsInSection
Before this code i use XML (not WSDL) it's work
This is My Code -> http://www.vasuta.com/ios/MyLoxFile.zip
It seems like your tableview is load et call its delegates methods before your NSURLConnection finished downloading.
You have launch NSURLConnection by
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
so the connection is asynchronous. You can't be sure whether it finishes before or after your tableview loads its view.
But your can always do a check in your tableview methods to make your app work. For example:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int nbCount = [items_subject count];
if (nbCount == 0)
return 1;
else
return [items_subject count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
int nbCount = [items_subject count];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
if (nbCount ==0)
cell.textLabel.text == #"Loading";
else
{
// your configuration
cell.textLabel.text = [NSString stringWithFormat:#"%#" ,[items_subject objectAtIndex:indexPath.row]];
}
return cell;
}
In your method "ConnectionDidFinishLoading", then your can call [tableview reloaddata] to update your tableview.
[EDIT] on 12/09/2012
I've got your code work(not a nice solution), you should rethink how you organize your viewControllers.
add the IBOutlet TableView to myloxfileController.tableView.
add this line myloxfileContoller.tableView = myloxfileTable; after the line myloxfileContoller.view = myloxfileContoller.tableView; in - (void)viewDidLoad of the interface ViewController .
reload tableview data when connection finished.
add this line [self.tableView reloadData]; after the line items_subject = subject_data_Array; in -(void)connectionDidFinishLoading:(NSURLConnection *)connection of the interface MyLoxFileTVController .
This will work because when the download finished, you reloadData of the IBOutlet TableView.
Have you used [uitableview reloadData] after updating your NSArray?
replace with
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"tableView numberOfRowsInSection"); //debug
// Return the number of rows in the section.
NSLog(#"[items_subject count] = %# ", [items_subject count]);
return [items_subject count];
}
Related
I am using this code for textfiled as search bar.Here is my code. but i am getting crash for range on textfield.if i start entering then its crashing.Even not able to handle case sensitive text also
#import "ViewController.h"
#import "AFNetworking.h"
#import <QuartzCore/QuartzCore.h>
#interface ViewController ()
{
NSMutableArray *countryArray;
NSMutableArray *searchArray;
NSString *searchTextString;
BOOL isFilter;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_countryView.hidden = true;
self->countryArray = [[NSMutableArray alloc] init];
[self makeRestuarantsRequests];
_tableView.layer.borderColor = [UIColor lightGrayColor].CGColor;
_tableView.layer.borderWidth = 1;
_tableView.layer.cornerRadius=5;
[self.searchTextField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self
name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - AFNetworking
-(void)makeRestuarantsRequests{
NSURL *url = [NSURL URLWithString:#"example url"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
self->countryArray = [responseObject objectForKey:#"data"];
[self.tableView reloadData];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
#pragma mark - Tableview Delegate and Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isFilter)
{
return [searchArray count];
}
else
return [countryArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *tempDictionary= [self->countryArray objectAtIndex:indexPath.row];
if(isFilter)
{
cell.textLabel.text=[searchArray objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = [tempDictionary objectForKey:#"name"];
}
// cell.textLabel.text = [tempDictionary objectForKey:#"name"];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[_SelectCountryButton setTitle:cell.textLabel.text forState:UIControlStateNormal];
_countryView.hidden = true;
}
-(void)textFieldDidChange:(UITextField *)textField
{
searchTextString=textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText
{
if(searchText.length==0)
{
isFilter=NO;
}
else{
isFilter=YES;
searchArray=[[NSMutableArray alloc]init];
for(NSString *string in countryArray){
NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArray addObject:string];
}
}
[self.tableView reloadData];}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#pragma mark UITextFieldDelegates
- (IBAction)SelectCountry:(id)sender {
_countryView.hidden = false;
}
#end
Getting crash error :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI rangeOfString:options:]: unrecognized selector sent to instance 0x10128b4f0
error code :
-(void)updateSearchArray:(NSString *)searchText
{
if(searchText.length==0)
{
isFilter=NO;
}
else{
isFilter=YES;
searchArray=[[NSMutableArray alloc]init];
for(NSString *string in countryArray){
NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArray addObject:string];
}
}
[self.tableView reloadData];}
}
Please help me out.How can i solve this issues.
Thanks in advance !
UPDATE :
{"response":true,"message":"country.","data":[{"id":1,"name":"Afghanistan"},{"id":2,"name":"Albania"},{"id":3,"name":"Algeria"},{"id":4,"name":"American Samoa"},{"id":5,"name":"Andorra"},{"id":6,"name":"Angola"}]}
well i have good approach with predicate
well according to you jsonResponse
// so forEach loop should like this
for(NSDictionary *Dic in CountryArray){
NSString*str=[NSString stringWithFormat:#"%#",[dic objectForKey:#"name"]];
}
// well i am not using for each loop instead of that i have nsmutablearray name as _searchArraySingle is same like your countryArray with predicate
// if you are using textfield in place of default Searchbar so use this then use NSPredicate
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(textFieldTextDidChangeOneCI:)
name:UITextFieldTextDidChangeNotification
object:searchTxt];
SearchBar.delegate = (id)self;
}
-(void)textFieldTextDidChangeOneCI:(NSNotification *)notification {
UITextField *textfield=[notification object];
[self predicatChangeText:textfield.text];
// NSLog(#"%#",textfield.text);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
-(void)predicatChangeText:(NSString*)text{
// myJSON.array
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"%K contains[cd] %#", #"name", text];
_filteredArray = [NSMutableArray arrayWithArray:[_searchArraySingle filteredArrayUsingPredicate:predicateString]];
NSLog(#"_filteredArray=%lu",(unsigned long)[_filteredArray count]);
[self.tableView reloadData];
}
- (IBAction)cancleSearch:(id)sender {
searchTxt.text=#"";
if (_filteredArray) {
_filteredArray=nil;
}
[self.searchTxt resignFirstResponder];
_filteredArray = myJSON.array;
[self.tableView reloadData];
}
Might this will help you out !!!! GoodLuck
Hi My data is getting duplicated every time I use the pull to refresh.. for eg. 5 initial entries in the table view are doubled to 10 with one pull to refresh and adding 5 more in the subsequent pull to refresh. How can I stop the duplication.. I would like to make sure that only new items are downloaded and existing data in the table is not downloaded again.
#implementation RootViewController
#synthesize allEntries = _allEntries;
#synthesize feeds = _feeds;
#synthesize queue = _queue;
#synthesize webViewController = _webViewController;
#pragma mark -
#pragma mark View lifecycle
- (void)addRows {
RSSEntry *entry1 = [[[RSSEntry alloc] initWithBlogTitle:#"1"
articleTitle:#"1"
articleUrl:#"1"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry2 = [[[RSSEntry alloc] initWithBlogTitle:#"2"
articleTitle:#"2"
articleUrl:#"2"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry3 = [[[RSSEntry alloc] initWithBlogTitle:#"3"
articleTitle:#"3"
articleUrl:#"3"
articleDate:[NSDate date]] autorelease];
[_allEntries insertObject:entry1 atIndex:0];
[_allEntries insertObject:entry2 atIndex:0];
[_allEntries insertObject:entry3 atIndex:0];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Songs";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:
#"http://hindisongs.bestofindia.co/?feed=rss2",
nil];
self.refreshControl = [UIRefreshControl new];
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Pull to refresh"];
[self.refreshControl addTarget:self action:#selector(bindDatas) forControlEvents:UIControlEventValueChanged];
[self bindDatas]; //called at the first time
}
-(void)bindDatas
{
//GET YOUR DATAS HERE…
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
//update the tableView
[self.tableView reloadData];
if(self.refreshControl != nil && self.refreshControl.isRefreshing == TRUE)
{
[self.refreshControl endRefreshing];
}
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseAtom:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSString *blogTitle = [rootElement valueForChild:#"title"];
NSArray *items = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = nil;
NSArray *links = [item elementsForName:#"link"];
for(GDataXMLElement *link in links) {
NSString *rel = [[link attributeForName:#"rel"] stringValue];
NSString *type = [[link attributeForName:#"type"] stringValue];
if ([rel compare:#"alternate"] == NSOrderedSame &&
[type compare:#"text/html"] == NSOrderedSame) {
articleUrl = [[link attributeForName:#"href"] stringValue];
}
}
NSString *articleDateString = [item valueForChild:#"updated"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC3339];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
cell.textLabel.text = entry.articleTitle;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - %#", articleDateString, entry.blogTitle];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (_webViewController == nil) {
self.webViewController = [[[WebViewController alloc] initWithNibName:#"WebViewController" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController.entry = entry;
[self.navigationController pushViewController:_webViewController animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
self.webViewController = nil;
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[_allEntries release];
_allEntries = nil;
[_queue release];
_queue = nil;
[_feeds release];
_feeds = nil;
[_webViewController release];
_webViewController = nil;
[super dealloc];
}
The issue is that you keep inserting object to _allEntries without ever reseting it. You will want to empty it out at some point, either when the user pulls to refresh or when the new data comes in before you add any new objects to it.
[_allEntries removeAllObjects];
Try putting it at the start of bindDatas.
Error creating row in tableview.
My table view is loaded with a json.
I saw many examples here, however none were able to solve
my code
NSMutableArray *myArray = [NSMutableArray arrayWithArray:news];
[myArray insertObject:#"teste" atIndex:0];
NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count]-1 inSection:1]];
[self.tableView insertRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];
error displayed
2013-05-30 23:15:17.345 lerJson[1141:c07] * Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2380.17/UITableView.m:908
2013-05-30 23:15:17.347 lerJson[1141:c07] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 11 into section 1, but there are only 1 sections after the update'
** First throw call stack:
(0x1c95012 0x10d2e7e 0x1c94e78 0xb68665 0xb670b 0xc4945 0xc4973 0x476d 0x76d78 0x789eb 0x2e185a 0x2e099b 0x2e20df 0x2e4d2d 0x2e4cac 0x2dca28 0x49972 0x49e53 0x27d4a 0x19698 0x1bf0df9 0x1bf0ad0 0x1c0abf5 0x1c0a962 0x1c3bbb6 0x1c3af44 0x1c3ae1b 0x1bef7e3 0x1bef668 0x16ffc 0x26ad 0x25d5)
libc++abi.dylib: terminate called throwing an exception
My full code j2_ViewController.h
#import "j2_ViewController.h"
#interface j2_ViewController ()
#end
#implementation j2_ViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self carregaDados];
}
-(void)carregaDados
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url2 = [[NSURL alloc] initWithString:[#"http://localhost:3000/json.aspx?ind=0&tot=12" stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url2];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void)carregaDados2
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url2 = [[NSURL alloc] initWithString:[#"http://localhost:3000/json.aspx?ind=12&tot=12" stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url2];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSMutableData *myData = [[NSMutableData alloc]init];
[myData appendData:response];
NSMutableArray *news2;
news2 = [NSJSONSerialization JSONObjectWithData:myData options:nil error:&jsonParsingError];
//NSLog(#"LOG: %#", news2);
NSMutableArray *myArray = [NSMutableArray arrayWithArray:news];
[myArray addObjectsFromArray:news2];
NSLog(#"LOG: %#", myArray);
news = myArray;
//NSLog(#"Erro: %#", jsonParsingError);
[tableViewjson reloadData];
}
- (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;
NSError *e = nil;
news = [NSJSONSerialization JSONObjectWithData:data options:nil error:&e];
[tableViewjson reloadData];
//NSLog(#"erro=%#",e);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Erro" message:#"Não foi possivle fazer o download - cheque sua conexão 3g ou wi-fi" delegate:nil cancelButtonTitle:#"cancelar" otherButtonTitles:nil];
[alert show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSInteger teste = [news count];
return teste;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"celula";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:#"nome"];
return cell;
}
//chama essa função quando o scroll atinge seu final
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
NSInteger currentOffset = scrollView.contentOffset.y;
NSInteger maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;
if(maximumOffset - currentOffset <= -40)
{
//carega mais dados
//[self carregaDados2];
[self.tableView beginUpdates];
NSMutableArray *myArray = [NSMutableArray arrayWithArray:news];
[myArray insertObject:#"teste" atIndex:0];
NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count]-1 inSection:1]];
[self.tableView insertRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];
}
}
#end
My delegation has not changed
You also need to update your datasource like this:
[news insertObject:#"teste" atIndex:0];
I assume you only have 1 section.
change this code: NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count] inSection:1]];
to this code: NSMutableArray *path = [NSMutableArray arrayWithObject:[NSIndexPath indexPathForRow:[news count] inSection:0]];
sections and rows starts at 0.
I have a UITableView that has to be populated with the contents stored in an array. I have displayed the array in the NSLog which comes out just fine but it is not visible in the uitableview. The problem is that the program does not enter the cellForRowAtIndexPath method. I am not sure as to which code i should be adding to this question to make it easier to understand so please ask me for the code.
#import "SubList.h"
#import "SubListParser.h"
#import "LoginParser.h"
#implementation SubList
#synthesize theXML1,FolderID,UserID;
NSString *loginUserId;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
self.FolderID=FolderID ;
self.UserID=UserID;
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self initWithData];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)initWithData{
//[self GetChilds:FolderID UserID:loginUserId];
}
-(void)GetUserLoginId:(NSString *)UserIdReceved{
loginUserId=UserIdReceved;
}
-(void)GetChilds:(NSString*)FolderIDRecvd UserID:(NSString*)userID{
NSString *_FolderID=FolderIDRecvd;
NSString *_UserID=loginUserId;
//?? what to do here? aa gye bhai yha pe folder id nad user id? try out now ok
// NSLog(#"hi yaar response toh aa rha ha that mean s values toh ha hmare pass haan storyboard ka koi laucha hai ny yaar do min de dekhta hu",FolderIDRecvd,loginUserId);
NSString *soapMsg=[NSString stringWithFormat:#"<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><TreeDataSubFolder xmlns='http://tempuri.org/'><FolderID>%#</FolderID><UserId>%#</UserId></TreeDataSubFolder></soap:Body></soap:Envelope>",_FolderID,_UserID];
NSLog(#"%#",soapMsg);
NSURL *url=[NSURL URLWithString:#"http://192.168.1.5/interlogicsmobile/interlogics.asmx?op=TreeDataSubFolder"];
xmlparser1 = [[NSXMLParser alloc] initWithContentsOfURL:url];
NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url];
NSString *msgLength=[NSString stringWithFormat:#"%d",[soapMsg length]];
NSLog(#"Message Length=%#",msgLength);
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://tempuri.org/TreeDataSubFolder" forHTTPHeaderField:#"SOAPAction"];
[req addValue:#"length" forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
//[activityIndicator startAnimating];
conn1=[[NSURLConnection alloc]initWithRequest:req delegate:self];
if(conn1){
webdata1=[NSMutableData data] ;
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
int responseStausCode = [httpResponse statusCode];
NSLog(#"code: %d", responseStausCode);
[webdata1 setLength: 0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
[webdata1 appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"DONE. Received Bytes: %d", [webdata1 length]);
theXML1 = [[NSString alloc]
initWithBytes: [webdata1 mutableBytes]
length:[webdata1 length]
encoding:NSUTF8StringEncoding];
//---shows the XML---
//NSLog(#"%#",theXML1);
SubListParser *parserObjForData1=[[SubListParser alloc]init];
SubFolderData=[[NSMutableArray alloc]init];
SubFolderData=[parserObjForData1 UserXMLParser1:webdata1];
[SublistSet reloadData];
}
- (void)viewDidUnload
{
[SublistSet reloadData];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[SublistSet reloadData];
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [SubFolderData count]/2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"*******************called tablevied did load*********************");
int row = [indexPath row]*2;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
for (int i=0; i<=[SubFolderData count]/2; i++) {
NSString *filename = [SubFolderData objectAtIndex:row];
NSString *ext = [filename pathExtension];
if ([ext isEqualToString:#"doc"] || [ext isEqualToString:#"DOC"]) {
[cell.imageView setImage:[UIImage imageNamed:#"DOC.png"]];
} else if ([ext isEqualToString:#"jpg"]|| [ext isEqualToString:#"JPG"]) {
[cell.imageView setImage:[UIImage imageNamed:#"JPG.png"]];
}else if([ext isEqualToString:#"pdf"]|| [ext isEqualToString:#"PDF"]){
[cell.imageView setImage:[UIImage imageNamed:#"PDF.png"]];
}else if([ext isEqualToString:#""]){
[cell.imageView setImage:[UIImage imageNamed:#"Folder2.png"]];
}else if([ext isEqualToString:#"docx"]|| [ext isEqualToString:#"DOCX"]){
[cell.imageView setImage:[UIImage imageNamed:#"DOCX.png"]];
}else if([ext isEqualToString:#"TIF"]|| [ext isEqualToString:#"tif"]){
[cell.imageView setImage:[UIImage imageNamed:#"TIFF.png"]];
}else if([ext isEqualToString:#"png"]|| [ext isEqualToString:#"PNG"]){
[cell.imageView setImage:[UIImage imageNamed:#"PNG.png"]];
}else if([ext isEqualToString:#"gif"]|| [ext isEqualToString:#"GIF"]){
[cell.imageView setImage:[UIImage imageNamed:#"GIF.png"]];
}else if([ext isEqualToString:#"jpeg"]|| [ext isEqualToString:#"JPEG"]){
[cell.imageView setImage:[UIImage imageNamed:#"JPG.png"]];
}
}
// Configure the cell...
cell.textLabel.text=[SubFolderData objectAtIndex:row];
cell.detailTextLabel.text =[SubFolderData objectAtIndex:row+1];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
return cell;
}
/*
// Override to support conditional editing of the table view.
#end
I'm usin Kal https://github.com/klazuka/Kal to implement a calendar. I'm using storyboard, so I add KalViewController as a child to the container view controller.
kal.delegate = self;
kal.dataSource = dataSource;
dataSource = [[CalendarDataSourceDelegate alloc] init];
kal = [[KalViewController alloc] init];
[self addChildViewController:kal];
[kal didMoveToParentViewController:self];
[self.calendarioView addSubview:kal.view];
[clickEvent insertPrintAdd:zona_competicion];
I use an external object as datasource delegate, but after fetching data from my backend by webservice, I don't know how to call delegates to load calendar with fetched data:
#implementation CalendarDataSourceDelegate
- (id)init
{
if ((self = [super init])) {
items = [[NSMutableArray alloc] init];
matches = [[NSMutableArray alloc] init];
buffer = [[NSMutableData alloc] init];
}
[self fetchHolidays];
return self;
}
- (eventMatch *)eventAtIndexPath:(NSIndexPath *)indexPath
{
return [items objectAtIndex:indexPath.row];
}
#pragma mark UITableViewDataSource protocol conformance
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"MyCell";
eventNoAddedCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[eventNoAddedCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:identifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
}
eventMatch *event = [self eventAtIndexPath:indexPath];
cell.escudoLocal.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#.png",event.equipoLocal ]];
cell.escudoVis.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#.png",event.equipoVisitante ]];
cell.equipoLocal.text = event.equipoLocal;
cell.equipoVisitante.text = event.equipoVisitante;
cell.competicion.text = event.competicion;
cell.jornada.text = event.jornada;
cell.hora.text = event.hora;
cell.canalesTV.text = event.canalesTV;
[self fetchHolidays];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
#pragma mark Fetch from the internet
- (void)fetchHolidays
{
NSString *urlStr = [NSString stringWithFormat:#"http://backend.exular.net/contenido/webservices/xlr_ws_calendario.php?idp=105"];
dataReady = NO;
[matches removeAllObjects];
conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]] delegate:self];
[conn start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[buffer setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[buffer appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error=nil;
NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:buffer options:kNilOptions error:&error];
NSArray *array = [tempDic valueForKey:#"nodes"];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init] ;
[fmt setDateFormat:#"dd/MM/yyyy"];
for (NSDictionary *jornada in array) {
NSDate *d = [fmt dateFromString:[jornada objectForKey:#"fecha"]];
[matches addObject:[eventMatch equipoVisitante:[jornada valueForKey:#"id_visitante"] equipoLocal:[jornada valueForKey:#"id_local"] resultadoVisitante:[jornada valueForKey:#"res_visitante"] resultadoLocal:[jornada valueForKey:#"res_local"] canalesTV:[jornada valueForKey:#"cadenas"] date:d time:[jornada valueForKey:#"hora"] jornada:[jornada valueForKey:#"jornada"] competicion:[jornada valueForKey:#"competicion"]]]; }
dataReady = YES;
[callback loadedDataSource:self];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"HolidaysCalendarDataSource connection failure: %#", error);
}
#pragma mark KalDataSource protocol conformance
- (void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{
/*
* In this example, I load the entire dataset in one HTTP request, so the date range that is
* being presented is irrelevant. So all I need to do is make sure that the data is loaded
* the first time and that I always issue the callback to complete the asynchronous request
* (even in the trivial case where we are responding synchronously).
*/
if (dataReady) {
[callback loadedDataSource:self];
return;
}
callback = delegate;
[self fetchHolidays];
}
- (NSArray *)markedDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
if (!dataReady)
return [NSArray array];
return [[self matchesFrom:fromDate to:toDate] valueForKeyPath:#"date"];
}
- (void)loadItemsFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
if (!dataReady)
return;
[items addObjectsFromArray:[self matchesFrom:fromDate to:toDate]];
}
- (void)removeAllItems
{
[items removeAllObjects];
}
#pragma mark -
- (NSArray *)matchesFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
NSMutableArray *matchesUpdate = [NSMutableArray array];
for (eventMatch *match in matches)
if (IsDateBetweenInclusive(match.date, fromDate, toDate))
[matchesUpdate addObject:match];
return matches;
}
- (void)dealloc
{
matches=nil;
}
First, I find strange that you alloc your KalViewController after using it, I would do it just in the opposite order:
kal = [[KalViewController alloc] init];
kal.delegate = self;
kal.dataSource = dataSource;
And then why don't you just call?:
[kal reloadData];