How to Post JSON Data in synchronously way? - ios

How to post JSON Data in synchronously way? Can use NSURLSession or AFNetworking or other way?

Sample basic code for posting data to server using synchronous
//PASS YOUR URL HERE
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"your URL"]];
//create the Method "POST" for posting data to server
[request setHTTPMethod:#"POST"];
//Pass The String to server like below
NSString *strParameters =[NSString strin gWithFormat:#"user_email=%#&user_login=%#&user_pass=%#& last_upd_by=%#&user_registered=%#&",txtemail.text,txtuser1.text,txtpass1.text,txtuser1.text,datestr,nil];
//Print the data that what we send to server
NSLog(#"the parameters are =%#", strParameters);
//Convert the String to Data
NSData *data1 = [strParameters dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}

In user3182143's answer, sendSynchronousRequest is deprecated in latest version iOS 9.
You can use NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSString *strResult = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
}] resume];

Here is my solution:
- (IBAction)postJSONSynchronization:(id)sender {
__block BOOL success = NO;
__block NSDictionary *jsonDic = nil;
NSURLSession *session = [NSURLSession sharedSession];
// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
request.HTTPMethod = #"POST"; // 请求方法
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:#13577766655 forKey:#"phoneNumber"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
request.HTTPBody = jsonData; // 请求体
NSCondition *condition = [[NSCondition alloc] init];
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Child Thread:%#",[NSThread currentThread]);
if (!error) {
jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
success = YES;
} else {
NSLog(#"%#",error);
}
[condition lock];
[condition signal];
[condition unlock];
}];
[task resume];
// 启动任务
NSLog(#"Main Thread:%#",[NSThread currentThread]);
[condition lock];
[condition wait];
[condition unlock];
NSLog(#"测试时机");
NSLog(#"josnDic:%#",jsonDic);}

Related

Got Null Value From the api in objective c

I am fetching JSON values from the API...but it showing the values as null... I checked it in the postman it's working there and I have the response...I have listed my sample code below please mention my mistakes. I'm new to this development
- (IBAction)PaymentButtonTapped:(id)sender {
[self PayuMoneyAdminValues];
}
-(void)PayuMoneyAdminValues{
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]init];
NSString *urlstring = [NSString stringWithFormat:#"%#admindatas",restSiteURLServices];
NSURL *url = [NSURL URLWithString:urlstring];
NSString *userUpdate = [NSString stringWithFormat:#"%#",restAuth];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setURL:url];
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//NSData *data1 = [NSData dataWithContentsOfURL:url];
//Apply the data to the body
[urlRequest setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data!=nil){
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (parseError) {
NSLog(#"Admin data: %#",responseDictionary);
}
}
}];
[dataTask resume];
}

How to post string data to API

I wanted to post a string data to API, I try to send it to server by using the below code. I've check api there by using the postman, it did not pass in the string data into the server. I do not know what is the problem and need help on this.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:reqURLStr]];
[request setHTTPMethod:#"POST"];
**//Pass The String to server**
NSString *userUpdate =[NSString stringWithFormat:#"service_type=%#&ParcelSize=%#&ReceiverName=%#&MobileNumber=%#&Email=%#&DropOffHub=%#&PickupHub=%#" ,serviceType,pSize,rName,rMobile,rEmail,dropHubID,pickHubID];
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data1];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[data makeRestAPICall:reqURLStr] forHTTPHeaderField:#"Authorization"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"fail to connect");
}
return resSrt;
Simple answer
-(void)postJsonDataToServer{
NSDictionary *parameters = #{
#"service_type": serviceType,
#"ParcelSize": pSize,
#"ReceiverName": rName,
#"MobileNumber": rMobile,
#"Email" : rEmail,
#"DropOffHub" : dropHubID,
#"PickupHub" : pickHubID
};
NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http:/api/order/add"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data != nil)
{
NSError *parseError = nil;
//If the response is in dictionary format
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
//OR
//If the response is in array format
NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The res is - %#",res);
}
else
NSLog(#"Data returned the parameter is nil here");
}];
[dataTask resume];
}

Not getting server response by using http post method & nsurlsession

NSError *error;
NSDictionary *dicData = [[NSDictionary alloc]initWithObjectsAndKeys:username,#"username",password,#"password",cpassword,#"cpassword",mobile,#"mobile",firstname,#"firstname",lastname,#"lastname",#"register",#"action",nil];
NSLog(#"parameter=%#",dicData);
NSURLComponents *components = [NSURLComponents componentsWithString:#"http://followerlikes.com/app_appoint/json/?action=register"];
NSMutableArray *queryItems = [NSMutableArray array];
for (NSString *key in dicData) {
[queryItems addObject:[NSURLQueryItem queryItemWithName:key value:dicData[key]]];
}
components.queryItems = queryItems;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:components.URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dicData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"%#",data);
NSLog(#"%#",response);
NSLog(#"%#",error);
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",strRes);
NSError *resultError;
NSDictionary *dicResult = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&resultError];
dispatch_async(dispatch_get_main_queue(), ^
{
if (error !=nil) {
NSLog(#"%#",error.description);
NSLog(#"%#",error.localizedDescription);
}
else {
completion(dicResult);
}
});
}];
[task resume];
}
In order send request for getting data, you have to add key in info.plist as follow :
And just update your code as below :
NSError *error;
NSDictionary *dicData = [[NSDictionary alloc] initWithObjectsAndKeys:#"user123", #"username", #"pass1234", #"password", #"pass1234", #"cpassword", #"0123456789", #"mobile", #"User", #"firstname", #"Name", #"lastname", #"register", #"action", nil];
NSLog(#"parameter=%#",dicData);
// NSURLComponents *components = [NSURLComponents componentsWithString:#"http://followerlikes.com/app_appoint/json/?action=register"];
//
// NSMutableArray *queryItems = [NSMutableArray array];
// for (NSString *key in dicData) {
// [queryItems addObject:[NSURLQueryItem queryItemWithName:key value:dicData[key]]];
// }
// components.queryItems = queryItems;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://followerlikes.com/app_appoint/json/?action=register"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dicData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Data : %#",data);
NSLog(#"RESPONSE : %#",response);
NSLog(#"ERROR : %#",error);
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",strRes);
NSError *resultError;
NSDictionary *dicResult = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&resultError];
NSLog(#"RESPONSE DICT : %#", dicResult);
dispatch_async(dispatch_get_main_queue(), ^ {
if (error !=nil) {
NSLog(#"ERROR : %#",error.description);
NSLog(#"ERROR : %#",error.localizedDescription);
}
else {
// completion(dicResult);
}
});
}];
[task resume];

how to handle response in json

I'm using this piece of code for hit data in url.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
value of uitextfield is not store in url when i clicked on button, what should i do here?
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
//NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
//_Email.text,#"email_id", _Password.text,#"password",nil];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"yyyyy",#"company_name",
#"karthik.saral#gmail.com",#"email_id", #"XXXXX",#"password",nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
NSLog(#"answewrv : %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
this is updated code after the amendments. i am getting the same error.
You are wrong here:
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
It should be
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
_Email.text,#"email_id", _Password.text,#"password",nil];
initWithObjectsAndKeys mean: object,key, object, key
I have done also this type work you can see this , may be it will help you.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#" your URL "];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=%#&password=%#&api_key=Your key", usernameField.text,passwordField.text];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSLog(#"%#", mapData);
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
[self saveLoginFileToDocDir:dictionary];
ItemManagement *i = [[ItemManagement alloc]init];
[self presentViewController:i animated:YES completion:Nil];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}

How to send POST data using JSON in iOS?

I tried to add an entry to db using a POST request in Objectve-C. My service is:
#RequestMapping(method = RequestMethod.POST, headers = "content-type=application/json")
public
#ResponseBody
boolean addEmployee(#ModelAttribute User user) {
try {
logger.log(Level.INFO, user.getCountry());
userDataService.addUser(user);
return true;
//return new Status(1, "Employee added Successfully !");
} catch (Exception e) {
e.printStackTrace();
return false;//new Status(0, e.toString());
}
}
When I try this on Postman, it's working fine with x-www-form-urlencoded. But when I try this in Objective-C, nothing happens. Here is what I tried:
NSString *jsonInputString = #"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/user"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:#"POST"];
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];
[rq setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[rq setValue:[NSString stringWithFormat:#"%ld", (long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"%#", [error localizedDescription]);
}];
In completion block, the log prints "Could not connect to the server". How can I call the service with JSON data?
Something like this should work
// 1: Create your URL, Session config and Session
NSString *jsonInputString = #"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/user"];
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2: Create NSMutableRequest object
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
// 3: Create Jsondata object
NSError *error = nil;
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
// Asynchronously Api is hit here
NSURLSessionUploadTask *dataTask =
[session uploadTaskWithRequest:request
fromData:data
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
NSLog(#"%#", data);
NSDictionary *json =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(#"%#", json);
success(json);
}];
[dataTask resume]; // Executed First

Resources