Appending two components in a single component in UIPickerView - ios

I had very minute problem since yesterday. I had 2 tables in the database one with Projects and other with Benefits. I want to add the two tables data in Single PickerView Component. For example Projects has pro1, proj2, proj3 and Benefits table has benefits1, benefits2. So I want to append both projects table dat and Benefits table data in a single PickerView component.
-(void)loadprojects
{
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
// Code for Project loading
NSString * BenefitString =#"http://test.com/GetBenefitTypes";
NSURL *Benefiturl = [NSURL URLWithString:BenefitString];
NSString *projecturltemp = #"http://test.com/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:Benefiturl];
[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];
NSURLRequest *urlRequestBenifits = [NSURLRequest requestWithURL:Benefiturl
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
urlData = [NSURLConnection sendSynchronousRequest:urlRequestBenifits
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"];
BenefitsNames = [entries valueForKey:#"NM_LEAVES"];
}
//Combined = [BenefitsNames arrayByAddingObjectsFromArray:projectNames];
NSLog(#"Combined : %#", projectNames);
//NSLog(#"projID : %#", projID);
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
}

Are projects and benefits NSArray instances? If so why not just combine them into one array and use that moving forward?
NSArray *projects = #[#"pro 1", #"pro 2"];
NSArray *benefits = #[#"benefit 1", #"benefit 2"];
NSArray *combined = [projects arrayByAddingObjectsFromArray:benefits];
NSLog(#"Combined: %#", combined);
Combined prints out:
Combined: (
"pro 1",
"pro 2",
"benefit 1",
"benefit 2" )
Then in your - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component method just return the [combined objectAtIndex:row];

base on my understanding, you wanna have something like above? am i correct? so multiple component in a UIPickerView?
if so, 1st thing, you need to set delegations to your ViewController ->
<UIPickerViewDataSource, UIPickerViewDelegate>
then you implement the following methods in your ViewController.m file:
(I assume you have "NSArray *data" for projects and benefits ready...)
//Number of rows to display in each component
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component==0) {
return [self.listOfProjectsOfLeftCol count];
}
return [self.listOfBenefitsOfRightCol count];
}
//Number of columns to display
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
//define what to display in each rows and columns
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component==0) {
return [self.listOfProjectsLeftCol objectAtIndex:row];
}
return [self.listOfBenefitsOfRightCol objectAtIndex:row];
}
//when the row is selected , do something...
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component==0) {
//selected items in left column, now write your own code to do something...
}
else {
//selected items in right column, now write your own code to do something...
}
}

Not clear what do you mean by the combine the two component into one.
But I guess you want combination of project and benefit as Project:Benefit
If so u can use following code snippet
NSArray *arrProject=[NSArray arrayWithObjects:#"Project1",#"Project2",nil];
NSArray *arrBenefits=[NSArray arrayWithObjects:#"Benefits1",#"Benefits2",nil];
NSMutableArray *arrCombined=[[NSMutableArray alloc]init];
for(int i=0;i<[arrProject count];i++)
{
[arrCombined addObject:[NSString stringWithFormat:#"%#:%#",[arrProject objectAtIndex:i],[arrBenefits objectAtIndex:i]]];
}
NSLog(#"Combined:%#",arrCombined);
Its gives you result as
Combined:(
"Project1:Benefits1",
"Project2:Benefits2"
)
And then use the arrCombined for the date picker data source

Related

Return NSMutableArray from completionHandler (Objective C)

I did post request to a web service and get response. I convert the response to NSMutableArray. My response in NSURLSessionDataTask and now I want to return NSMutableArray for using outside of NSURLSessionDataTask. Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"url"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *postString = #"params";
NSString *postLength = [NSString stringWithFormat:#"%lu", ( unsigned long )[postString length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *task = [[self getURLSession] dataTaskWithRequest:request completionHandler:^( NSData *data, NSURLResponse *response, NSError *error )
{
dispatch_async( dispatch_get_main_queue(),
^{
NSDictionary *dicData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
NSDictionary *values = [dicData valueForKeyPath:#"smth"];
NSArray * dataArr = [dicData objectForKey:#"smth"];
NSArray * closeArr = [values objectForKey:#"0"];
NSUInteger dataCount = [dataArr count] ;
NSUInteger closeCount = [closeArr count] ;
NSMutableArray * newData = [NSMutableArray new] ; //<-- THIS ARRAY
for(int i = 0 ; i<dataCount && i<closeCount ; i++)
{
NSMutableDictionary * temp = [NSMutableDictionary new] ;
NSString * dataString = [dataArr objectAtIndex:i];
NSString * closeString = [closeArr objectAtIndex:i];
[temp setObject:dataString forKey:#"smth"];
[temp setObject:closeString forKey:#"smth"];
[newData addObject:temp];
}
NSLog(#"%#", newData);
} );
}];
[task resume];
I need return NSMutableArray * newData = [NSMutableArray new];
Long story short, I get json data from web service, then transform it to appropriate json format for displaying it in the chart(I use shinobicontrols). Now, I display chart with the help of local json. Here is the code:
_timeSeries = [NSMutableArray new];
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"AppleStockPrices" ofType:#"json"];
NSData* json = [NSData dataWithContentsOfFile:filePath];
NSArray* data = [NSJSONSerialization JSONObjectWithData:json
options:NSJSONReadingAllowFragments
error:nil];
for (NSDictionary* jsonPoint in data) {
SChartDataPoint* datapoint = [self dataPointForDate:jsonPoint[#"smth1"]
andValue:jsonPoint[#"smth2"]];
[_timeSeries addObject:datapoint];
}
When I am trying to implement this code in NSURLSessionDataTask, the chart doesn't appear. So I need return NSMutableArray(where my data in appropriate json format) outside.
How can I do this? Any ideas?
Thank you!
You cannot add a return statement in the completion handler since it may not be called if the session return an error. As a matter of fact, Xcode will give you an "Incompatible pointer type" error if you try to do that.
The best way I found to go around it is to set up your newData array as a property and make it available to the other methods in the class. If a specific method will need to handle this array when the url session task is over, you can call that method from the completion handler or use a notification.
Alternatively, if for some reason you do not want to user a class property, you can use the NSNotificationCenter, and pass the newData to the listener in the notification object.
EDIT: code example using a property
If you need the newData outside the completion block, an easy way is declaring the array as a property. This is not the only approach and probably not the best. But it doesn't add much complexity to the code.
You can declare the newData array in your .m class file:
#interface "whatever class you are using"
#property (nonatomic, strong) NSMutableArray *newData;
#end
Your can initialize the array in your viewDidLoad method:
- (void)viewDidLoad {
_newdata = [[NSMutableArray alloc] init];
}
In Your completion block, you would remove the initialization and add data to the array.
//NSMutableArray * newData = [NSMutableArray new] ; // REMOVE THE INTIALIZATION
for(int i = 0 ; i<dataCount && i<closeCount ; i++) {
NSMutableDictionary * temp = [NSMutableDictionary new] ;
NSString * dataString = [dataArr objectAtIndex:i];
NSString * closeString = [closeArr objectAtIndex:i];
[temp setObject:dataString forKey:#"smth"];
[temp setObject:closeString forKey:#"smth"];
[_newData addObject:temp];
}
Again, this is not the best approach but it is relatively simple. One problem with doing this, is that since you have a strong reference to the array, if you need to perform another URL call, and load new data into the array, you will need to empty it. Otherwise, the new data will be appended to the old one. You can do it by calling [_newData removeAllObjects]; before the URL session is called again.
EDIT 2: changed code based on the user comment:
- (void)loadChartData {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"url"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *postString = #"params";
NSString *postLength = [NSString stringWithFormat:#"%lu", ( unsigned long )[postString length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *task = [[self getURLSession] dataTaskWithRequest:request completionHandler:^( NSData *data, NSURLResponse *response, NSError *error ) {
dispatch_async( dispatch_get_main_queue(), ^{
NSDictionary *dicData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSDictionary *values = [dicData valueForKeyPath:#"smth"];
NSArray * dataArr = [dicData objectForKey:#"smth"];
NSArray * closeArr = [values objectForKey:#"smth0"];
NSUInteger dataCount = [dataArr count] ;
NSUInteger closeCount = [closeArr count] ;
NSMutableArray * newData = [NSMutableArray new] ;
for(int i = 0 ; i<dataCount && i<closeCount ; i++) {
NSMutableDictionary * temp = [NSMutableDictionary new] ;
NSString * dataString = [dataArr objectAtIndex:i];
NSString * closeString = [closeArr objectAtIndex:i];
[temp setObject:dataString forKey:#"smth"];
[temp setObject:closeString forKey:#"smth"];
[newData addObject:temp];
}
NSLog(#"%#", newData);
_timeSeries = [NSMutableArray new];
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"AppleStockPrices" ofType:#"json"];
NSData* json = [NSData dataWithContentsOfFile:filePath];
NSArray* data = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingAllowFragments error:nil];
for (NSDictionary* jsonPoint in data) {
SChartDataPoint* datapoint = [self dataPointForDate:jsonPoint[#"smth"] andValue:jsonPoint[#"smth"]];
[_timeSeries addObject:datapoint];
}
});
}];
[task resume];
// Code here has a good chance of being executed before the completion block is complete
// _newdata = [[NSMutableArray alloc] init];
// NSLog(#"%#", _newdata);
}

user value in textfield become wrong while viewing

I am new to IOS i created textfield for enter value in integer.That integer convert into string then it can be passed to Post method and finally button action it can be viewed in alert view.if user given value to textfield means its value going wrong but constant value is given means its showing correct value i am struggling to get correct value when user enter in textfield.
Post method:
below coding showing post method with parameter(str)passing
-(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]];
[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];
}
}
picker view:
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if(pickerView.tag ==2){
txtText.text = (NSString *)[arrMsg objectAtIndex:row];
branchid1 = (NSString *)[arrmsg1 objectAtIndex:row];
NSLog([arrmsg1 objectAtIndex:row]);
}else if(pickerView.tag ==1){
currency1.text = (NSString *)[currencyname1 objectAtIndex:row];
currencyid1 = (NSString *)[id1 objectAtIndex:row];
NSLog([id1 objectAtIndex:row]);
}
else
{
currency2.text = (NSString *)[from_currency objectAtIndex:row];
currencyid2 = (NSString *)[id2 objectAtIndex:row];
NSLog([id2 objectAtIndex:row]);
}
//here i assign textfield value into string
fourthstr = [NSString stringWithFormat:#"%d",value1.text];
NSLog(#"%#",value1.text);
//here i created str as string to pass parameter to post method
str = [NSString stringWithFormat:#"branch_id=%#&from_curr=%#&to_curr=%#&value=%#",branchid1,currencyid1,currencyid2,fourthstr];
[self sendDataToServer :#"POST" params:str];
}

JSON data show on first cell

I am Developing An IOS App.On Button Click Show JSON Data In Tableview..But The Data Show ON Only First Cell Not On Other Cells..I Can Check The Data Through NSLog That Are Correct..But In Tableview Show In First Cells And Some Time App Crash And Error Data Parameters Are Nil..Warning Show on This Line
`"Incompatible Pointer Assigning To 'NSDictionary'
To
NSArray "[str = [BBServerJson sendPostRequest:json toUrl:url];]`
Any Help Or Advice Is Greatly Appreciated. Thanks In Advance.
//Button Click
BBAuthorViewController *BBAuthor =[[UIStoryboard storyboardWithName:#"Main" bundle:nil]instantiateViewControllerWithIdentifier:#"BBAuthor"];
BBAuthor.authorDetail=_adDetailsObj.authorDetail;
[self.navigationController pushViewController:BBAuthor animated:YES];
//Json
+(NSDictionary *)sendPostRequest:(NSDictionary *)params toUrl:(NSString *)urlString
{
NSMutableString *paramString =
[NSMutableString stringWithString:#""];
NSArray *keys = [params allKeys];
for (NSString *key in keys) {
[paramString appendFormat:#"%#=%#&",key,
[params valueForKey:key]];
}
NSString *postString = #"";
if ([paramString length] > 0)
postString = [paramString substringToIndex:
[paramString length]-1];
NSMutableURLRequest *request =[NSMutableURLRequest
requestWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *res;
NSError *error;
NSData *resp = [NSURLConnection sendSynchronousRequest:request
returningResponse:&res error:
&error];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)res;
int statusCode;
statusCode = [httpResponse statusCode];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:resp options:NSJSONReadingMutableContainers error:&error];
return jsonArray;
}
NSString *url = #"https://boatbrat.com/wp-app-handler-boatsales.php";
NSMutableDictionary *json = [[NSMutableDictionary alloc]init];
[json setObject:#"AuthorListing" forKey:#"method"];
[json setObject:_authorDetail forKey:#"author"];
str = [BBServerJson sendPostRequest:json toUrl:url];
//Tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return str.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
NSArray *array = [str objectForKey:#"results"];
NSDictionary *dic= [array objectAtIndex:indexPath.row];
cell.textLabel.text = [dic objectForKey:#"author_name"];
return cell;
}
I think you are returning wrong row count in numberOfRowsInSection: method.
Change the return statement to,
return [[str objectForKey:#"results"] count];

How to populate UITableView with JSON data?

I'm struggling to figure out what i am doing wrong. I am basically trying to populate the my UITableView with json data. In the console I can see the results but just don't know why the data is not displayed in the tableview. I have looked at similar questions and answers but none is a solution to my problem.
Advice or help please;
#pragma mark - Private method implementation
-(void)loadData{
// Form the query.
#try {
NSString *get =[[NSString alloc] initWithFormat:#""];
NSString *getRegions = [NSString stringWithFormat:#"JSON URL HERE",self.sessionId, self.companyId];
NSURL *url=[NSURL URLWithString:getRegions];
NSLog(#"Get regions: %#", url);
NSData *postData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Reponse code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
#try{
NSError *error = nil;
regionsJson = [[NSMutableArray alloc]init];
//[jsonData removeAllObjects];
regionsJson = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];
NSArray *tblArray = [NSArray arrayWithObject:regionsJson];
}
#catch (NSException *e){
NSLog(#"Try catch block: %#", e);
}
#finally{
// [self.tblRegion reloadData];
NSLog(#"finally");
}
structureJson =[regionsJson valueForKey:#"structure"];
companyJson =[structureJson valueForKey:#"company"];
_barBtnCompanyName.title = [companyJson valueForKey:#"company_name"];
NSLog(#"Get company name: %#", [companyJson valueForKey:#"company_name"]);
for (int i =0 ; i < regionsJson.count; i++){
regionsJson = [companyJson objectForKey:#"regions"];
NSString *regionName = [NSString stringWithFormat:#"%#", [regionsJson valueForKey:#"region_name"]];
NSLog(#"Region name: %#",regionName);
// [regionsJson addObject:regionName];
NSString *alarmCount = [NSString stringWithFormat:#"%#", [regionsJson valueForKey:#"alarm_cnt"]];
NSLog(#"Alarm count: %#", alarmCount);
// [regionsJson addObject:alarmCount];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
// Reload the table view.
[self.tblRegion reloadData];
}
#pragma mark - UITableView method implementation
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"Number of rows: %lu", (unsigned long)regionsJson.count);
return [regionsJson count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"CellRegions";
// Dequeue the cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Set the loaded data to the appropriate cell labels.
cell.textLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:#"region_name"];
cell.detailTextLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:#"alarm_cnt"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
NSLog(#"Table cell: %#", cell);
return cell;
}
My code is just fine, i did a stupid omission of this declaration.
-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tblRegion.delegate = self;
self.tblRegion.dataSource = self;
[self loadData];
}

Loading data in Component 2 after selecting component 1 picker View IOS

There are Three components (projects, tasks and sub tasks )in my pickerview when I select project, I was able to get the project name and respective project ID (Project ID is in label). My requirement is I want to send the project ID to NSURL so that I can load the respective tasks that are assigned to that project ID. Here is my Below Code.
ViewDidLoad:
// Code for Tasks loading
NSString *nsTaskurllocal = #"http://test.com/";
NSString *usrid = #"313";
NSString * productIdString =[NSString stringWithFormat:#"%#/%#",[self.lblProjects text],usrid];
NSLog(#"aString : %#", productIdString);
NSString *aString = [nsTaskurllocal stringByAppendingString:productIdString];
NSURL *nstaskurl = [NSURL URLWithString:aString];
NSLog(#"nstaskurl : %#", nstaskurl);
NSData *nstaskpostData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *nstaskpostLength = [NSString stringWithFormat:#"%lu", (unsigned long)[nstaskpostData length]];
NSMutableURLRequest *nstaskrequest = [[NSMutableURLRequest alloc] init];
[nstaskrequest setURL:nstaskurl];
[nstaskrequest setHTTPMethod:#"POST"];
[nstaskrequest setValue:nstaskpostLength forHTTPHeaderField:#"Content-Length"];
[nstaskrequest setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[nstaskrequest setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[nstaskrequest setHTTPBody:nstaskpostData];
NSError *nstaskerror = [[NSError alloc] init];
NSHTTPURLResponse *nstaskresponse = nil;
NSData *nstaskurlData=[NSURLConnection sendSynchronousRequest:nstaskrequest returningResponse:&nstaskresponse error:&nstaskerror];
NSURLRequest *nstaskurlRequest = [NSURLRequest requestWithURL:nstaskurl
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
nstaskurlData = [NSURLConnection sendSynchronousRequest:nstaskurlRequest
returningResponse:&nstaskresponse
error:&nstaskerror];
if ([nstaskresponse statusCode] >= 200 && [nstaskresponse statusCode] < 300)
{
NSString *nstaskresponseData = [NSJSONSerialization JSONObjectWithData:nstaskurlData
options:NSJSONReadingAllowFragments error:&nstaskerror];
NSArray *nstaskentries = [NSJSONSerialization JSONObjectWithData:[nstaskresponseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&nstaskerror];
if(!nstaskentries)
{
NSLog(#"Error : %#", nstaskerror);
}
else{
for (NSDictionary *nstaskentry in nstaskentries) {
taskID = [nstaskentries valueForKey:#"ID_TASK"];
taskNames = [nstaskentries valueForKey:#"TASk_NAME"];
//NSLog(#"Error : %#", taskNames); //log to see the result in console // by Kiran
}
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSNumber *myProjectArrayString = [projID objectAtIndex:row];
//NSNumber *myTaskArrayString = [taskID objectAtIndex:row];
//NSLog(#"%#",myArrayString);
//NSLog(#"%#",myTaskArrayString);
lblProjects.text = [NSString stringWithFormat:#"%#",myProjectArrayString];
//lblProjects.hidden = YES;
lblTasks.text = [taskNames objectAtIndex:[pickerView selectedRowInComponent:1]];
//lblTasks.text = [NSString stringWithFormat:#"%#", myTaskArrayString];
lblSubTasks.text = [subtaskNames objectAtIndex:[pickerView selectedRowInComponent:2]];
}
Thanks in Advance
Kiran Kumar
You need to differentiate between your total data, and your displayed data.
So, download all of your data and save it in projectNames, taskNames and subtaskNames. But also have 2 other properties: currentTaskNames and currentSubtaskNames (you don't need
cProjectNames because the user can always see all project names.
After the download:
self.currentTaskNames = taskNames;
self.currentSubtaskNames = subtaskNames;
Now, when the user selects a project, filter the tasks and subtasks that are available.
switch (component) {
case 0:
{
NSString *project = [projectNames objectAtIndex:row];
self.currentTaskNames = [taskNames filteredArrayUsingPredicate:...];
break;
}
case 1:
{
NSString *task = [taskNames objectAtIndex:row];
self.currentSubtaskNames = [subtaskNames filteredArrayUsingPredicate:...];
break;
}
case 2:
// do something interesting
break;
}
You need to fill in the predicates which filter out the tasks and subtasks that aren't appropriate based on the selected project and task.
Also, stop using labels for data storage...

Resources