Unable to reload the UItableview - ios

I had some data in my UITableView with four labels (Project,tasks, subtasks and hours), I changed my data from the backend (going to database and changed the data). I changed number of hours from 12 to 10. But I was only seeing the old data (12 hours instead of 10 hours) in my UITableView. Can any one suggest what is the reason behind that. I tried to clean, restart the computer which doesn't load the correct data that is in database. Other thing I can add is I was retrieving the data with the help of web service. and converting the data from JSONSerialization format to NSArray. When I ping my web service in browser URL, it gives me the correct data. Here is the below code :
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadprojects];
}
NSString *strwebsite = [[NSUserDefaults standardUserDefaults] valueForKey:#"website"];
NSString *websitemethods = #"Timesheet.svc/GetTimesheet";
NSString *projecturltemp = [strwebsite stringByAppendingString:websitemethods];
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#/%#",projecturltemp,usrid,eventDate];
NSURL *url = [NSURL URLWithString:projecturl];
[self.tableView reloadData];
NSLog(#"url : %#", url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//NSLog(#"urlData : %#",urlData);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseDatatest = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSLog(#"responseDatatest : %#",responseDatatest);
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseDatatest dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
NSLog(#"Entries : %#", entries);
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projectNames = [entries valueForKey:#"NM_PROJECT"];
taskNames = [entries valueForKey:#"TASk_NAME"];
subtaskNames = [entries valueForKey:#"SUBTASK_NAME"];
timesheetid = [entries valueForKey:#"ID_TIMESHEET_DTLS"];
projId = [entries valueForKey:#"ID_PROJECT"];
taskId = [entries valueForKey:#"ID_TASK"];
subtaskId = [entries valueForKey:#"ID_SUB_TASK"];
totalhours = [entries valueForKey:#"No_Hours"];
approve = [entries valueForKey:#"FL_APPROVE"];
leaves = [entries valueForKey:#"NM_LEAVE"];
}
}
} else {
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [projectNames count];
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identitifier = #"Cell";
TableViewCell * cell = [tableView
dequeueReusableCellWithIdentifier:identitifier
forIndexPath:indexPath];
if ([[[timesheetid objectAtIndex:indexPath.row] stringValue] isEqualToString:#"0"])
{
cell.lblProjects.text = [NSString stringWithFormat:#"%#",#"No Projects Filled"];
cell.lblTasks.text = [NSString stringWithFormat:#"%#",#"No Tasks Filled"];
cell.lblSubTasks.text = [NSString stringWithFormat:#"%#",#"No SubTasks Filled"];
cell.lblHours.text = [NSString stringWithFormat:#"%#",#"0 Hours Filled"];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else if ([[leaves objectAtIndex:indexPath.row] isEqualToString:#"0"])
{
cell.lblProjects.text = [projectNames objectAtIndex:indexPath.row];
cell.lblTasks.text = [taskNames objectAtIndex:indexPath.row];
cell.lblSubTasks.text = [subtaskNames objectAtIndex:indexPath.row];
cell.lblHours.text = [[totalhours objectAtIndex:indexPath.row] stringValue];
//NSLog(#"cell :%#",cell.lblHours.text);
}
else
{
cell.lblProjects.text = [leaves objectAtIndex:indexPath.row];
cell.lblTasks.text = [NSString stringWithFormat:#"%#",#"No Projects/Tasks on this Date"];
cell.lblSubTasks.text = [NSString stringWithFormat:#"%#",#"No Sub Tasks on this Date"];
cell.lblHours.text = [[totalhours objectAtIndex:indexPath.row] stringValue];
}
cell.editingAccessoryType = UITableViewCellAccessoryDetailDisclosureButton;
NSNumber *myProjectArrayString = [timesheetid objectAtIndex:indexPath.row];
cell.hdbrowcount = [NSString stringWithFormat:#"%#",myProjectArrayString];
return cell;
}

I don't see this line
[self.tableview reloadData];

use postnotification whenever change data.
[[NSNotificationCenter defaultCenter] postNotificationName:#"refresh" object:self];

Related

how to create picker view did select row can be passed as parameter for post method

I am new to IOS i need to create parameter for POST method using picker view did select row.
Picker view did select row:
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if(pickerView.tag ==2){
txtText.text = (NSString *)[arrMsg objectAtIndex:row];
NSLog([arrmsg1 objectAtIndex:row]);
}else if(pickerView.tag ==1){
currency1.text = (NSString *)[currencyname1 objectAtIndex:row];
NSLog([id1 objectAtIndex:row]);
}
else
{
currency2.text = (NSString *)[from_currency objectAtIndex:row];
NSLog([id2 objectAtIndex:row]);
}
}
post method:
here str is considered as parameter for post method but i struggling how to call picker view did select row array as my parameter str.
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[str length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
NSLog(#"%#",str);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
mutableData = [[NSMutableData alloc]init];
}
}
viewdidload:
coding :
- (void)viewDidLoad {
[super viewDidLoad];
NSString *parseURL =#"Url1";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
arrMsg = [json valueForKeyPath:#"Branches.branch_name"];
//NSLog(#"%#",json);
arrmsg1 =[json valueForKeyPath:#"Branches.id"];
firststr = [arrmsg1 componentsJoinedByString:#","];
NSLog(#"%#",arrmsg1);
arrMsg.count!=0;
if (arrMsg.count >0)
{
txtText.text = (NSString *)[arrMsg objectAtIndex:0];
}
}
//second textfield and third textfield
NSString *parseURL1 =#"url2";
NSString *encodeurl1 =[parseURL1 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url1 = [NSURL URLWithString:encodeurl1];
NSData *data1 = [NSData dataWithContentsOfURL:url1];
if(data1){
NSError *error1;
NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:data1 options: kNilOptions error:&error1];
//NSLog(#"%#",json1);
currencyname1 = [json1 valueForKeyPath:#"Currencies.currency_name"];
id1 = [json1 valueForKeyPath:#"Currencies.id"];
NSLog(#"%#",id1);
from_currency = [json1 valueForKeyPath:#"Currencies.currency_name"];
id2 = [json1 valueForKeyPath:#"Currencies.id"];
secondstr = [id1 componentsJoinedByString:#","];
thirdstr = [id2 componentsJoinedByString:#","];
NSLog(#"%#",secondstr);
NSLog(#"%#",thirdstr);
//NSLog(#"%#",json1);
currencyname1.count!=0;
if (currencyname1.count >0)
{
currency1.text = (NSString *)[currencyname1 objectAtIndex:0];
}
from_currency.count!=0;
if (from_currency.count >0)
{
currency2.text = (NSString *)[from_currency objectAtIndex:0];
}
}
str = [NSString stringWithFormat:#"branch_id=%#&from_curr=%#&to_curr=%#&value=%#",firststr,secondstr,thirdstr,fourthstr];
pktStatePicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
pktStatePicker .delegate = self;
pktStatePicker .dataSource = self;
txtText.delegate = self ;
currency1.delegate = self;
currency2.delegate = self;
[ pktStatePicker setShowsSelectionIndicator:YES];
You should set tag to your text fields.
Then on button click you can get text of your textfields and call sendDataToServer method from this button click not from did select row.
Hope this will help :)

Unable to retrieve the Data from web service to UITableView

I was Unable to retrieve the data from web service and display the same in my UITableView cell. I was able to see the data that was added in the past. When I go to my application, add a record I was not able to see any thing. Here is the below code. To make sure I was using IOS 8, Xcode 6. I worked on this application in the recent past and use to work fine in IOS 7 or IOS 6. When I upgraded there are few problems like not displaying the data in UITabelView
-(void)loadprojects
{
NSString *eventDate = self.StringfromTextField3;
[[NSUserDefaults standardUserDefaults] setObject:eventDate forKey:#"Eventdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.tableView dataSource]];
NSString *strwebsite = [[NSUserDefaults standardUserDefaults] valueForKey:#"website"];
NSString *websitemethods = #"Timesheet.svc/GetTimesheet";
NSString *projecturltemp = [strwebsite stringByAppendingString:websitemethods];
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#/%#",projecturltemp,usrid,eventDate];
NSURL *url = [NSURL URLWithString:projecturl];
//NSLog(#"url : %#", url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projectNames = [entries valueForKey:#"NM_PROJECT"];
taskNames = [entries valueForKey:#"TASk_NAME"];
subtaskNames = [entries valueForKey:#"SUBTASK_NAME"];
timesheetid = [entries valueForKey:#"ID_TIMESHEET_DTLS"];
projId = [entries valueForKey:#"ID_PROJECT"];
taskId = [entries valueForKey:#"ID_TASK"];
subtaskId = [entries valueForKey:#"ID_SUB_TASK"];
totalhours = [entries valueForKey:#"No_Hours"];
approve = [entries valueForKey:#"FL_APPROVE"];
leaves = [entries valueForKey:#"NM_LEAVE"];
}
}
} else {
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [projectNames count];
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identitifier = #"Cell";
TableViewCell * cell = [tableView
dequeueReusableCellWithIdentifier:identitifier
forIndexPath:indexPath];
if ([[[timesheetid objectAtIndex:indexPath.row] stringValue] isEqualToString:#"0"])
{
cell.lblProjects.text = [NSString stringWithFormat:#"%#",#"No Projects Filled"];
cell.lblTasks.text = [NSString stringWithFormat:#"%#",#"No Tasks Filled"];
cell.lblSubTasks.text = [NSString stringWithFormat:#"%#",#"No SubTasks Filled"];
cell.lblHours.text = [NSString stringWithFormat:#"%#",#"0 Hours Filled"];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else if ([[leaves objectAtIndex:indexPath.row] isEqualToString:#"0"])
{
cell.lblProjects.text = [projectNames objectAtIndex:indexPath.row];
cell.lblTasks.text = [taskNames objectAtIndex:indexPath.row];
cell.lblSubTasks.text = [subtaskNames objectAtIndex:indexPath.row];
cell.lblHours.text = [[totalhours objectAtIndex:indexPath.row] stringValue];
NSLog(#"cell :%#",cell.lblHours.text);
NSLog(#"lblProjects :%#",cell.lblProjects.text);
}
else
{
cell.lblProjects.text = [leaves objectAtIndex:indexPath.row];
cell.lblTasks.text = [NSString stringWithFormat:#"%#",#"No Projects/Tasks on this Date"];
cell.lblSubTasks.text = [NSString stringWithFormat:#"%#",#"No Sub Tasks on this Date"];
cell.lblHours.text = [[totalhours objectAtIndex:indexPath.row] stringValue];
}
cell.editingAccessoryType = UITableViewCellAccessoryDetailDisclosureButton;
NSNumber *myProjectArrayString = [timesheetid objectAtIndex:indexPath.row];
cell.hdbrowcount = [NSString stringWithFormat:#"%#",myProjectArrayString];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//NSLog(#"index :%#",[timesheetid objectAtIndex:[self.tableView indexPathForSelectedRow].row]);
[self performSegueWithIdentifier:#"segueName" sender:indexPath];
//[tableView setEditing:YES animated:YES];
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:#"segueNameforAddPage"])
{
UINavigationController *segueNameNavController=segue.destinationViewController;
AddProjectDetails *NavWeekScreen = (AddProjectDetails*)segueNameNavController.topViewController;
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NavWeekScreen.projidstocancel = self.StringfromTextField3;
NavWeekScreen.StringfromProjectsTasksscreenuser=str;
NSInteger appoved = [[approve valueForKeyPath:#"#sum.integerValue"] intValue];
NavWeekScreen.ApprovalorNot = appoved;
NSInteger sumArray = [[totalhours valueForKeyPath:#"#sum.integerValue"] floatValue];
NavWeekScreen.totalhrsAdd = sumArray;
}
}

Use ASIHTTPRequest to startAsynchronous and update UITableView but failed with EXC_BAD_ACCESS

in viewDidLoad
{
[super viewDidLoad];
postjson = [[PostJson alloc] init];
[postjson startpost];
_table = [[UITableView alloc] init];
FOOTPRINT;
_table.delegate = self;
_table.dataSource =self;
[self.view addSubview:_table];
}
in startpost
-(NSMutableArray*)startpost:(NSString *)title category_id:(NSString *)category_id limits:(NSNumber *)limits blog_id:(NSString*)blog_id pull_direction:(NSString *)pull_dirction
{
__block NSMutableArray *dataToBeShown =[[NSMutableArray alloc] init];
__block NSMutableDictionary *resultsDictionary;
NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:title, #"title",category_id,#"category_id",limits,#"limits",blog_id,#"blog_id", pull_dirction,#"pull_direction",nil];
if ([NSJSONSerialization isValidJSONObject:userDictionary])
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &error];
NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
NSURL *url = [NSURL URLWithString:[[PropertyPlist getValue:#"RootURL"] stringByAppendingString:#"/rest/blog/search"]];
ASIHTTPRequest *_request = [ASIHTTPRequest requestWithURL:url];
__weak ASIHTTPRequest* request = _request;
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request setRequestMethod:#"POST"];
[request setPostBody:tempJsonData];
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *response = [request responseString];
NSLog(#"Test:%#",response);
NSData* jsonData = [response dataUsingEncoding:NSUTF8StringEncoding];
FOOTPRINT;
resultsDictionary = [jsonData objectFromJSONData];
NSArray *dataArray = [resultsDictionary objectForKey:#"data"];
NSLog(#"即将进入FOR循环");
int i =0;
for ( NSDictionary *dict in dataArray){
NSMutableArray *tempArray =[[NSMutableArray alloc] init];
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"id"]];//取出ID
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"thumb"]];//取出缩略图地址
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"title"]];//取出title
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"auto_id"]];//取出auto_id
[dataToBeShown addObject:tempArray];
tempArray=nil;
i++;
}
NSLog(#"跳出FOR循环");
}];
[request setFailedBlock:^{
NSError *error1 = [request error];
NSLog(#"ERROR IS %#",error1);
}];
[request startAsynchronous];
[ASIHTTPRequest setDefaultUserAgentString:kUserAgentString];
}
return dataToBeShown;
METHOD_END;
}
in cellForRowAtIndexPath
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *indentifier=#"indentifier";
RecommedTableViewCell *cell =(RecommedTableViewCell *)[tableView dequeueReusableCellWithIdentifier:indentifier];
if (cell == NULL)
{
cell=[[RecommedTableViewCell alloc]init]; }
NSInteger row=[indexPath row];
cell.titleLabel.text =[[dataToBeShown objectAtIndex:row] objectAtIndex:2];
[cell.image setImageWithURL:[[dataToBeShown objectAtIndex:row] objectAtIndex:1] ];
return cell;
}
It will crash as soon as the app is started for EXC_BAD_ACCESS.When I commit out
cell.titleLabel.text =[[dataToBeShown objectAtIndex:row] objectAtIndex:2];
[cell.image setImageWithURL:[[dataToBeShown objectAtIndex:row] objectAtIndex:1] ];
,not crash.So I found the dataToBeShown is null.How can I do it?
Please check the array before assigning
if(row
[cell.image setImageWithURL:[[dataToBeShown objectAtIndex:row] objectAtIndex:1] ];
}
or do the checking in numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return dataToBeShown.count;
}
This will remove the EXC_BAD_ACCESS.

Display the selected value in uipickerview

I had a uipickerview in my detailed page. I want to get the value selected by default when I edit the respective record which comes from my tableviewcell. In short I had a tableview with 10 records. When I select a record from tableview cell it navigates to detailed page which contains three picker views with one component each. I want the picker view to load the selected value by default. Here is the below code how Iam loading the data. How can I display the selected value in -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row and one more thing is I am using UINavigationcontroller for this page? Guys Can u please help me out
-(void)loadprojects
{
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
//NSString *pickername = [self.projectpicker dataSource];
//NSString *key = #"Da9s^a2Rp4na6R$ikiAsav3Is#niWsa";
//NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];
// Code for Project loading
NSString *projecturltemp = #"http://xxx.xxx/GetAssignedProjects";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#",projecturltemp,usrid];
NSURL *url = [NSURL URLWithString:projecturl];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projID = [entries valueForKey:#"ID_PROJECT"];
projectNames = [entries valueForKey:#"NM_PROJECT"];
}
randomSelection=[BenefitNames arrayByAddingObjectsFromArray:projectNames];
randomSelectionID = [benID arrayByAddingObjectsFromArray:projID];
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
}
-(void)loaddata
{
NSString *eventDate = self.projidstocancel;
[[NSUserDefaults standardUserDefaults] setObject:eventDate forKey:#"Eventdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString *post =[[NSString alloc] initWithFormat:#"username : %#&Password :%#",[self.projectpicker dataSource],[self.projectpicker delegate]];
//NSString *pickername = [self.projectpicker dataSource];
//NSString *key = #"Da9s^a2Rp4na6R$ikiAsav3Is#niWsa";
//NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];
// Code for Project loading
NSString *projecturltemp = #"http://xxx.xxxx/GetDetailsByID";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#",projecturltemp,self.hdnRowcount];
NSURL *url = [NSURL URLWithString:projecturl];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projectNames = [entries valueForKey:#"NM_PROJECT"];
taskNames = [entries valueForKey:#"TASk_NAME"];
subtaskNames = [entries valueForKey:#"SUBTASK_NAME"];
hdnlblProjects.text = [[entries valueForKey:#"NM_PROJECT"]componentsJoinedByString:#""];
hdnlblTasks.text = [[entries valueForKey:#"TASk_NAME"]componentsJoinedByString:#""];
hdnlblSubTasks.text = [[entries valueForKey:#"SUBTASK_NAME"]componentsJoinedByString:#""];
txthours.text = [[entries valueForKey:#"No_Hours"]componentsJoinedByString:#""];
txtstatus.text = [[entries valueForKey:#"STATUS"]componentsJoinedByString:#""];
lblBenefitsLeaves.text = [[entries valueForKey:#"NM_LEAVE"]componentsJoinedByString:#""];
BenefitNames = [entries valueForKey:#"NM_LEAVE"];
projID = [entries valueForKey:#"ID_PROJECT"];
taskID = [entries valueForKey:#"ID_TASK"];
subtskID = [entries valueForKey:#"ID_SUB_TASK"];
}
lblProjects.text = [[projID valueForKey:#"description"] componentsJoinedByString:#""];
taskstring = [[taskID valueForKey:#"description"] componentsJoinedByString:#""];
subtaskstring = [[subtskID valueForKey:#"description"] componentsJoinedByString:#""];
bentest = [[BenefitNames valueForKey:#"description"] componentsJoinedByString:#""];
hrsdiff1 = [txthours.text floatValue];
}
} else {
}
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
int numberofRows = 0;
if([pickerView isEqual: _projectpicker]){
numberofRows = [randomSelection count];
return numberofRows;
}
else if([pickerView isEqual: _taskspicker]){
numberofRows = [taskNames count];
return numberofRows;
}
else if([pickerView isEqual: _subtaskspicker]){
numberofRows = [subtaskNames count];
return numberofRows;
}
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *title = #"Test";
if([pickerView isEqual: _projectpicker]){
title = [randomSelection objectAtIndex:row];
return title;
}
else if ([pickerView isEqual: _taskspicker]){
title = [taskNames objectAtIndex:row];
return title;
}
else if ([pickerView isEqual: _subtaskspicker]){
title = [subtaskNames objectAtIndex:row];
return title;
}
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//NSLog(#"%#",myArrayString);
//NSLog(#"%#",myTaskArrayString);
if([pickerView isEqual: _projectpicker]){
NSNumber *myProjectArrayString = [randomSelectionID objectAtIndex:row];
lblProjects.text = [NSString stringWithFormat:#"%#",myProjectArrayString];
lblProjects.hidden = YES;
lblBenefitsLeaves.text = [randomSelection objectAtIndex:row];
hdnlblProjects.text = [randomSelection objectAtIndex:row];
rownoedit = row;
lblTasks.text = #"0";
hdnlblTasks.text = #"--Select--";
lblSubTasks.text = #"0";
hdnlblSubTasks.text = #"--Select--";
[self loadtasks];
}
//lblProjects.hidden = YES;
else if([pickerView isEqual: _taskspicker])
{
NSNumber *myTaskArrayString = [taskID objectAtIndex:row];
lblTasks.text = [NSString stringWithFormat:#"%#",myTaskArrayString];
lblTasks.hidden = YES;
hdnlblTasks.text = [taskNames objectAtIndex:row];
lblSubTasks.text = #"0";
hdnlblSubTasks.text = #"--Select--";
[self loadsubtasks];
}
else if([pickerView isEqual: _subtaskspicker])
{
NSNumber *mysubtaskArrayString = [subtskID objectAtIndex:row];
lblSubTasks.text = [NSString stringWithFormat:#"%#",mysubtaskArrayString];
lblSubTasks.hidden = YES;
hdnlblSubTasks.text = [subtaskNames objectAtIndex:row];
//lblTasks.text = [taskNames objectAtIndex:[pickerView selectedRowInComponent:1]];
//lblTasks.text = [NSString stringWithFormat:#"%#", myTaskArrayString];
//lblSubTasks.text = [subtaskNames objectAtIndex:[pickerView selectedRowInComponent:2]];
}
}
First define a static variable and give it initial value you like to first on load
ex : static int selectedRow = 3
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component{
selectedRow = [pickerView selectedRowInComponent:0];
}
and then where you show pickerView place this line
[self selectRow:selectedRow inComponent:0 animated:YES];
Try with following code
[self.yourPickerViewName selectRow:self.valueName inComponent:0 animated:YES];
Where
self.valueName is value that select record from tableview cell. and Put above code after creation of your UIPickerView.
You can refer this to fetch selected value from pickerview
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if([pickerView isEqual:StatePicker])
{
stateName = [StateArray objectAtIndex:row]; //StateName is NSString, StateArray is Array
}
}

EXC_BAD_ACCESS with worldweatheronline API

In my iOS app I'm using the weather APIs of worldweatheronline.com but I get a random "EXC_BAD_ACCESS" error oh this row (not always but sometimes) :
temperature.text = [NSString stringWithFormat:#"%# °C", tempC];
Here is my code:
- (void)showWeatherFor:(CLLocation *)newLocation
{
NSString *myRequestString = [[NSString alloc] initWithFormat:#"http://api.worldweatheronline.com/free/v1/weather.ashx?q=%f,%f&format=json&num_of_days=5&key=ydvgep8jn5m846upd8kb2qp6", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myRequestString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *JsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *theDictionary = [NSDictionary dictionaryWithJSONString:JsonString error:&error];
NSDictionary *data = [theDictionary objectForKey:#"data"];
NSArray *currentDictionary = [data objectForKey:#"current_condition"];
NSDictionary *temp = [currentDictionary objectAtIndex:0];
if ([temp objectForKey:#"temp_C"] == nil || [temp objectForKey:#"temp_F"] == nil)
{
return;
termometro.alpha = 0;
}
else
{
if (temp != nil)
{
if ([mainDelegate.gradi isEqualToString: #"°C"])
{
NSNumber *tempC = [temp objectForKey:#"temp_C"];
temperature.text = [NSString stringWithFormat:#"%# °C", tempC];
mainDelegate.temperature = [[temp objectForKey:#"temp_C"]intValue];
}
else
{
NSNumber *tempF = [temp objectForKey:#"temp_F"];
temperature.text = [NSString stringWithFormat:#"%# °F", tempF];
mainDelegate.temperature = [[temp objectForKey:#"temp_F"]intValue];
}
termometro.alpha = 1;
}
}
}

Resources