how to pass string as parameter in post method - ios

I am new to IOS i need to know how to pass NSString as parameter in nsurlconnection POST method,i passed string but it become empty
viewdidload:
NSString *parseURL =#"http:url";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
arrMsg = [json1 valueForKeyPath:#"Branches.branch_name"];
arrmsg1 =[json1 valueForKeyPath:#"Branches.id"];
NSString *str = [arrmsg1 componentsJoinedByString:#","];
NSLog(#"%#",str);
[self sendDataToServer :#"POST"];
}
post method:
In post method i passed the string as parameter
-(void) sendDataToServer : (NSString *) method{
//NSString *str = [arrmsg1 componentsJoinedByString:#","];
NSString *post = [NSString stringWithFormat:#"branch_id=%#",str];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post 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 ){
// indicator.hidden = NO;
mutableData = [[NSMutableData alloc]init];
}
}

you can do like
arrMsg = [json1 valueForKeyPath:#"Branches.branch_name"];
arrmsg1 =[json1 valueForKeyPath:#"Branches.id"];
NSString *str = [arrmsg1 componentsJoinedByString:#","];
NSLog(#"%#",str);
// call the method like
[self sendDataToServer :#"POST" params:str];
// create the method like
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
NSString *post = [NSString stringWithFormat:#"branch_id=%#",str];
.... continue your work
}

Related

Three parameter in Post method using nsurlconnection

I am new to IOS i need to pass three parameter in POST method.my parameter are (1)str (2)str1 (3)str2.this three parameter are fetch from different url in string format.
coding for POST method:
i need to add these parameter in method?i already added str parameter but i am struggling to pass other two(str1,str2) parameter.
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
NSString *post = [NSString stringWithFormat:#"branch_id=%#",str];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post 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];
}
}
Viewdidload:
here also i want to str1 and str2 parameter.
[self sendDataToServer :#"POST" params:str];
you can implement in multiple ways
Choice-1
-(void) sendDataToServer : (NSString *) method firstparams:(NSString *)firststr secondparam:(NSString *)secondstr thirdparam:(NSString *)thirdstr{
NSString *post = [NSString stringWithFormat:#"branch_id=%#&xxxx=%#&yyyyy=%#",firststr,secondstr,thirdstr];
// continue your works as its same flow
call method like
[self sendDataToServer :#"POST" firstparams:#"yourbranchID" secondparam:#"xxxValue" thirdparam:#"yyyyvalue"];
Choice-2
what ever you did is correct, just modify some code in viewdidload or else
// add all values in one string using stringWithFormat
NSString *str = [NSString stringWithFormat:#"branch_id=%#&xxxx=%#&yyyyy=%#",firststr,secondstr,thirdstr];
// and pass the param to web call
[self sendDataToServer :#"POST" params:str];
call method as
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
// no need of this line
// NSString *post = [NSString stringWithFormat:#"branch_id=%#",str];
// directly called the str in her
NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
/.... as its is continue the same work
instead of passing it as NSString just add the three string in a globally declared array and add objects to it and send it to web service.
or create them as NSDictionary and convert them as json string to web service.
NSDictionary *params = #{#"param1": str1, #"param2": str2, #"param3": str3 };
[self sendDataToServer :#"POST" params:params];
-(void) sendDataToServer : (NSString *) method params:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:jsonString forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
mutableData = [[NSMutableData alloc]init];
}
}
}

how to convert nsaaray into nsstring using nsurlconnection Post method

I am using two links.First link i created nsaaray for "id".This "id" i need to pass as parameter in nsurlconnection using POST method by second link.i tried lots but i stuck in while passing parameter "id".
nsaaray for id:
- (IBAction)button_drop:(id)sender {
NSString *parseURL =#"first_link";
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"];
arrmsg1 =[json valueForKeyPath:#"Branches.id"];
[_picker2 reloadAllComponents];
}
}
POST method using nsurlconnection:
NSString *Branchid=#"3";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#\n", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( connection )
{
mutableData = [NSMutableData new];
}
Try to create a "POST" method like this:-
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
Branchid, #"branch_id", nil];
NSString *newRequest = [dict JSONRepresentation];
NSData *requestData = [newRequest dataUsingEncoding:NSUTF8StringEncoding];
//If you are not using SBJsonParser Library then try the following:
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *urlString = #"YOUR URL String";
NSURL *requestURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long) [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
mutableData = [NSMutableData new];
}
Also, You can follow this link if you don't find out the answer working properly:-
Data in POST or GET methods
Send data in POST methods

passing parameter in nsurlconnection Post method

I tired picker view with array of four element from url link "branch_name"
(1) with button action.
Button action:
- (IBAction)picker_button:(id)sender {
NSString *parseURL =#"url(1)";
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"];
[_pickerdata1 reloadAllComponents];
}
}
Then I used url link(2) passing parameter using POST NSURLConnection and successfully displayed in tableview.
Post method coding:
here i am passing parameter as Branchid=#"1" only but i want to pass parameter as entire branchid value. help me
-(void) sendDataToServer : (NSString *) method{
NSString *Branchid =#"1" ;
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( connection )
{
mutableData = [NSMutableData new];
}
}
connection did finish loading:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error;
json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error];
NSLog(#"%#",json);
sellArray = [json valueForKeyPath:#"BranchByList.sell"];
buyArray = [json valueForKeyPath:#"BranchByList.buy"];
updataedArray = [json valueForKeyPath:#"BranchByList.updated"];
imageArray = [json valueForKeyPath:#"BranchByList.flag_image"];
currency =[json valueForKeyPath:#"BranchByList.currency"];
[ _dataview reloadData];
}

Change from synchronous to Asynchronous

Here i use GET method to fetch data from one Url and display the data in table view.I used synchronous to get data to display.
Needed:
I need to change this code to Asynchronous to display same data in table view.Here i just use my console to display data.
Here my code:
#import "ViewController.h"
#import <CommonCrypto/CommonDigest.h>
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self getdata];
}
-(NSString*)sha256HashFor:(NSString*)input
{
const char* str = [input UTF8String];
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(str, strlen(str), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
{
[ret appendFormat:#"%02x",result[i]];
}
return ret;
}
-(void)getdata {
NSString *userName = #"user#gmail.com";
NSString *password = #"passer";
//encoding
NSData *Data = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [Data base64EncodedStringWithOptions:0];
base64String=[self sha256HashFor: base64String];
NSString *urlString = #"https://api.exampleurl/user23/doc";
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", userName, base64String];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
}
In this code i used base64 and shaa256 encoding.
Can any one help me to do with Asynchronous. I don't know how to do
that. please help me with code explain.
Thanks in advance!
For making Asynchronous http request you can use :
[NSURLConnection sendAsynchronousRequest:httpRequest queue:[AppDelegate connectionQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
....
}];
or you can implement NSURLConnectionDataDelegate protocol
Updated Answer :
First create a connection queue in app delegate file
+ (NSOperationQueue *)connectionQueue
{
dispatch_once(&once, ^{
connectionQueue = [[NSOperationQueue alloc] init];
[connectionQueue setMaxConcurrentOperationCount:2];
[connectionQueue setName:#"com.XYZ.connectionqueue"];
});
return connectionQueue;
}
Here is updated getData Method :
-(void)getdata {
NSString *userName = #"user#gmail.com";
NSString *password = #"passer";
//encoding
NSData *Data = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [Data base64EncodedStringWithOptions:0];
base64String=[self sha256HashFor: base64String];
NSString *urlString = #"https://api.exampleurl/user23/doc";
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", userName, base64String];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
__block NSString *str;
[NSURLConnection sendAsynchronousRequest:httpRequest queue:[AppDelegate connectionQueue]completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];}];
NSLog(#"%#", str);
}

POST method receive duplicated in server

I'm sending a POST request to server but they receive it duplicated with the same date and even time. this is my code :
-(void) getTerms{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
User *mUser = [[User alloc]init];
NSString *appFile1 = [self getUserFile];
mUser = [NSKeyedUnarchiver unarchiveObjectWithFile:appFile1];
NSString *post = [NSString stringWithFormat:#"Method=GetFAQ&CustomerID=%#",mUser.customerID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[ServerName serverName]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
if( theConnection ){
// other codes
}
});
});
}
I just wonder what is wrong with my code ? thanks in advance
this is how i solved the problem :
-(void) getCredit{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *post = [NSString stringWithFormat:#"Method=%#",mMethod];
NSMutableURLRequest *request = [ServerName postToServer:post];
dispatch_async(dispatch_get_main_queue(), ^{
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSUTF8StringEncoding];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSDictionary *res1 = [res objectForKey:#"ServerResponse"];
});
});
}

Resources