how to POST UIPickerview Value to JSON url - ios

I have two UITextFields(cityNames,collageNames).I get data for JSON url.I get and Placed data to UIPickerview based on UITextFields. when select cityName that city name placed into UITextFields but now I need that particular index value post to JSON URL and same as collage name
. I know about String value Post to JSON url. But I don't know about How to post UIPickerview Index Value to JSON url.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog(#"select row is %d",row);
if(pickerView.tag==1){
CityName.text = [secondArray objectAtIndex:row];
string1=
[NSString stringWithFormat:#"%d",[yourpicker selectedRowInComponent:0]];
NSLog(#"string ring %#",string1);
}
else if(pickerView.tag==2){
CollageName.text = [firstArray objectAtIndex:row];
string2=
[NSString stringWithFormat:#"%d",[yourpicker selectedRowInComponent:0]];
}
}
String1 and String2 is get IndexValue .But i don't how to pass that particular Stringvalue to JSON.I tired but When i Print String 1 and 2 using NSLog outSide of Did-select Method it's showing null Values.When i Print String values in Didselect method it's showing select Index value
NSString *post =[NSString stringWithFormat:#"?&citynames=%#&collageNames=%#",cityname.text,collagename.text];
or
NSString *post =[NSString stringWithFormat:#"?&citynames=%#&collageNames=%#",string1,string2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.3.35:8090/SaveDollar/rest/users/add"]]];
NSLog(#"getData%#",request);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSLog(#"getData%#",request);
con3 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(con3)
{ webData3=[NSMutableData data];
NSLog(#"Connection successfull");
NSLog(#"GOOD Day My data %#",webData3);
}
else
{
NSLog(#"connection could not be made");
}
I tired like this (above code).i not getting.So Please give me any idea about How to post UIPickerView indexValue to JSON Url.
Thanks in Advanced .

You have two different pickerViews so no issue.
Get the actual values from two different arrays as:
NSString *collegeName=[collegeArray objectAtIndex:[self.dataPicker1 selectedRowInComponent:0]];
OR:
If you are able to see textField values, you can use them also as:
NSString *collegeName=collegeTextField.text;
One more way to get index i.e. from textField:
int index=[collegeNameArray indexOfObject:collegeName];
then you can pass index to your urlString.
To get the pickerView selected index use:
[self.dataPicker1 selectedRowInComponent:0]
You can build a urlString as:
urlString=[NSString stringWithFormat:#"?&citynames=%#&collageNames=%#",[self.dataPicker1 selectedRowInComponent:0],[self.dataPicker2 selectedRowInComponent:0]];

Related

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];
}

IOS: Dictionary Return null value/Data

in my project i am using JSON parsing to display data for this i created 2 NSDictionary dictionary 1 return success response but when i call it in second dictionary it return Null value.
i am sharing my code please help me to correct it
-(void)hdata
{
NSString *post = [NSString stringWithFormat:#"data[Users][ref_id]=%#&api_key=bf45c093e542f057c123ae7d6",refidstr];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.20/hspCh/api/user_diagnose_list"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
[request setHTTPBody:postData];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6); <=======it gives correct responce
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
[diagnosisdict setValue:refidstr forKey:#"data[Users][ref_id]"];
NSLog(#" for ref id =%# , data is= %#",refidstr, diagnosisdict); <======Gives null responce
}
Output of the above in console is as follows
2015-12-09 10:34:16.935 HcH[2841:32315] str : {"response":200,"diagnoses":[{"DiagnosesHospitals":{"hospital_id":"3341","id":"163075","discharges":"100.00","charge_amt":"1200.00","total_amt":"1500.00","medicare_amt":"1200.00"},"Diagnoses":{"diagnosis_name":"TRANSIENT ISCHEMIA"}}]}
2015-12-09 10:34:16.935 HcH[2841:32315] str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1200.00";
discharges = "100.00";
"hospital_id" = 3341;
id = 163075;
"medicare_amt" = "1200.00";
"total_amt" = "1500.00";
};
}
);
response = 200;
}
2015-12-09 10:34:16.936 HcH[2841:32315] for ref id =3341 , data is= (null)
Replace this
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
with
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
There is no entry in dict6 for "data[Users][ref_id]".
Using that string as a key is completely nonsensical, by the way. A key in this context is just a string, not a series of accesses in dictionaries.
It seems like what you want is dict6[#"data"][#"Users"][#"ref_id"].
However, this will also fail, because there is no entry for "data" in dict6.
It is possible that your cleanJSONToObject: method is stripping out the value of the "data" key. However, based on your statement that printing the value of dict6 gives the correct response, I assume that what you actually want to access is the value of "id" in "DiagnosesHospitals", since it sounds the most like a "ref_id".
Based on the output of the debugger, it seems as though you have a dictionary (dict6) with a "diagnoses" key pointing to an array with two dictionaries.
So, You would access the "id" field with dict6[diagnoses][0][#"DiagnosesHospitals"][#"id"], assuming that "id" is a string (I'm not sure why it has no quotes around it).
Somethings that you can get:
NSDictionary * diagnoses = dict6[#"diagnoses"];
NSString * diagnosis_name = diagnoses[0][#"Diagnoses"][#"diagnosis_name"];
NSDictionary * diagnosisdict = diagnoses[0][#"DiagnosesHospitals"];
NSString * hospital_id = diagnosisdict[#"hospital_id"];

How can we pass multiple urls in collectionview

I am creating a social networking application, in that am using Horizontal collection view cell displaying for post.
my requirements are,
I have 10 differnt url api but in that see (initWithFormat:#"acc_id=104 && method=getHomeContents && start_limit=0" ) if i increase start_limit then i can get another post details.
I need to pass this data at the time of viewdidload
but how can get this post data at the time of viewdidload and collectionView numberOfItemsInSection how can i declare this suggest any ideas
if(indexPath.item==3)
{
NSString *post = [[NSString alloc] initWithFormat:#"acc_id=104 && method=getHomeContents && start_limit=0"];
// NSLog(#"%# ",post);
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http:vblive/APIFiles/Services.php?"]]];
[request setHTTPMethod:#"POST"];
// NSLog(#"request is %#",request);
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
_myConnection2 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
// NSLog(#"%#",conn);
if(_myConnection2)
{
NSLog(#"connction sucess");
}
else
{
NSLog(#"unsucess");
}
}
Thanks
Sravan
Try some thing like this
1. create a tag or you can use variable like
NSString *startLimitValue;
2. Then Assign the startLimit value in View did load or where ever you want like
startLimitValue=#"one"
3 then use indexPath to assign Start limit value to different collection view cell
You can use Tags for specific item also
then dynamically set the no of items using Count method
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
if(check your condtion)
{
return [yourObject count];
}
else
if(check your conditon)
{
return [yourObject count];
}
}
I guess start limit has the integer value.
I would suggest for each view give the tag in collection view as 0 or 1 or 2....as the start limit values.
Then when user tap on item then using initWithFormat format the string using tag value of the item.

Appending two components in a single component in UIPickerView

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

Add key/value pairs to NSMutableURLRequest

Although there are many related questions, I don't see one that addresses adding multiple key/value pairs to an NSURLRequest.
I want to add a simple username and password to a request. I'm unsure of how to add multiple pairs, and also of the encoding. I get a valid connection and response, but the response indicates it hasn't been able to interpret the request properly.
Here's what I've got. Thanks in advance.
NSURL *authenticateURL = [[NSURL alloc] initWithString:#"https://www.the website.com/authenticate"];
NSMutableURLRequest *authenticateRequest = [[NSMutableURLRequest alloc] initWithURL:authenticateURL];
[authenticateRequest setHTTPMethod:#"POST"];
NSString *myRequestString = #"username=";
[myRequestString stringByAppendingString:username];
[myRequestString stringByAppendingString:#"&"];
[myRequestString stringByAppendingString:#"password="];
[myRequestString stringByAppendingString:password];
NSData *requestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];
[authenticateRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[authenticateRequest setHTTPBody: requestData];
[authenticateRequest setTimeoutInterval:30.0];
connection = [[NSURLConnection alloc] initWithRequest:authenticateRequest delegate:self];
You're not using NSString correctly (your myRequestString, in fact, will read "username="). Instead, try this:
NSMutableString *myRequestString = [NSMutableString stringWithString:#"username="];
[myRequestString appendString:username];
[myRequestString appendString:#"&password="];
[myRequestString appendString:password];
Further to this great answer, just a typical example code:
-(NSString *)buildKeyValuePostString
{
NSString *username = #"boss#apple.com";
NSString *password = #"macintosh";
NSMutableString *r = [NSMutableString stringWithString:#""];
[r appendString:#"command=listFileNames"];
[r appendString:#"&"];
[r appendString:#"name=blah"];
[r appendString:#"&"];
[r appendString:#"user="];
[r appendString: [username stringByUrlEncoding] ];
[r appendString:#"&"];
[r appendString:#"password="];
[r appendString: [password stringByUrlEncoding] ];
return r;
}
and here's the category to do the difficult/annoying job of url encoding
-(NSString *)stringByUrlEncoding
{
return (NSString *)CFBridgingRelease(
CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8)
);
// with thanks to http://www.cocoanetics.com/2009/08/url-encoding/
// modified for ARC use 2014
}
Hope it helps someone.
Assuming that you mean that you want to add HTTP header fields to the request, use:
-addValue:forHTTPHeaderField:

Resources