I have a simple app which makes a POST request. And then data is returned. The problem is that the returned data is not JSON..... So how can I view it? Here is my code:
NSString *requestString = [NSString stringWithFormat:#"https://serveraddress.com"];
NSString *string = [NSString stringWithFormat:#"id=%#&olt_info=%#", #"test", #"renz"];
NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
NSLog(#"\n request str : %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"The responce:\n\n%#", responseData);
if (error == nil && response.statusCode == 200) {
NSLog(#"%li", (long)response.statusCode);
NSError *err;
id JSon = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (err) {
NSLog(#"%#",err);
}
else {
NSLog(#"Json %#",JSon);
}
}
else {
//Error handling
NSLog(#"%#", response);
}
This is the format of the returned data that I am trying to read:
new_token=509723045780uIRBWRBH24b
So I know the downloaded data gets stored in the NSData called "responseData". But if I print it using NSLog I just get this:
<61636365 73735f74 6f6b656e 3d313538 32353838 33343337 39343431 7c365f4d 6543436e 6b51716f 722d6e70 61746662 484d6458 526b3477>
So how do I read this???
Thank you for your time, Dan.
To get NSString from NSData use
NSString *decodedString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
maybe this string will have a valid JSON format.
NSString *requestString = [NSString stringWithFormat:#"https://serveraddress.com"];
NSString *string = [NSString stringWithFormat:#"id=%#&olt_info=%#", #"test", #"renz"];
NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
NSLog(#"\n request str : %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
*id json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];*
NSLog(#"%#", json);
if (error == nil && response.statusCode == 200) {
NSLog(#"%li", (long)response.statusCode);
NSError *err;
id JSon = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (err) {
NSLog(#"%#",err);
}
else {
NSLog(#"Json %#",JSon);
}
}
else {
//Error handling
NSLog(#"%#", response);
}
Related
In My code I want to convert NSData to NSDictionary but it returns nil I don't know what mistake I made,I Used NSJSONSerialization for convert data to dictionary, The NSData was received from server response.
Here I show my Full code what I am trying.
-(void)SendPushNotification:(NSString*)getUrl :(NSMutableDictionary *)getData withCompletionBlock:(void(^)(NSDictionary *))completionBlock
{
NSError *error;
NSLog(#"dict val: %#",getData);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:getData options:NSJSONWritingPrettyPrinted error:&error];// Pass 0 if you don't care about the readability of the generated string
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLengthas = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:getUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
NSString *chkRegDevice= [[NSUserDefaults standardUserDefaults] stringForKey:#"bearer"];
NSString *strfds=[NSString stringWithFormat:#"bearer %#",chkRegDevice];
[request setHTTPMethod:#"POST"];
[request setValue:postLengthas forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:strfds forHTTPHeaderField:#"Authorization"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *configg=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*sessionn=[NSURLSession sessionWithConfiguration:configg delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *taskk=[sessionn dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *responce,NSError *error){
if(error)
{
NSLog(#"%#", [error localizedDescription]);
completionBlock(nil);
}else{
NSError *jsonError;
NSString *clientDetail = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"clientDetail: %#", clientDetail);
NSData *objectDataaaaa = [clientDetail dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectDataaaaa options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"json %#",json);
if (![clientDetail isEqualToString:#"Object reference not set to an instance of an object."]) {
if (completionBlock) {
completionBlock(json);
}
}
else
{
completionBlock(nil);
}
}
}];
[taskk resume];
}
Here the following response I get to convert NSData to NSString.
"{\"multicast_id\":8856529321585625357,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1534479035021563%1dbdaa031dbdaa03\"}]}"
Pass NSData object(data) directly to JSONObjectWithData.
Also, to check the error, you can print jsonError.
Try the following code:
NSError* error;
NSData *objectDataaaaa = [clientDetail dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:objectDataaaaa
options:kNilOptions
error:&error];
NSLog(#"JSON DICT: %#", json);
Try this.
NSString* str = your string data;
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *decodeString = [[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding];
NSDictionary *dict = [self dictionaryWithJsonString:decodeString];
/////////////////////
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
return nil;
}
return dic;
}
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];
}
Firstly I have two text fields first is login and second is password and one login button. I am using a storyboard and login button connected to another view controller by push segue. This time working in my project, Put username and password in textfield and select login button and print server response in console.
I want to login successfully after move another view and login is failed don't move another view.
My php code
<?php
header('Content-type: application/json');
include('../conn.php');
if($_POST)
{
$loginid = $_POST['loginid'];
$loginpassword = $_POST['loginpassword'];
$schoolid = substr_id($loginid);
$table = tb3($schoolid);//profile
$sql=mysql_query("select * from $table where ID = '".$loginid."' AND PASSWORD = '".$loginpassword."'",$conn);
$row=mysql_fetch_assoc($sql);
if(mysql_num_rows($sql)>0)
{
echo '{"success":1}';
}
else
{
echo '{"success":0,"error_message":"UserID and/or password is invalid."}';
}
}
else
{
echo '{"success":0,"error_message":"UserID and/or password is invalid."}';
}
My viewcontroller code
- (IBAction)Login:(id)sender {
if([[self.user_id text] isEqualToString:#""] || [[self.password text] isEqualToString:#""] ) {
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate 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");
}
}
}
This line is wrong
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
you are additionally added the & in your params ,this is not in loginpassword=%#& , you need to call like loginpassword=%# remove and send the request
use like
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",_user_id.text,_password.text, nil];
The problem is you are not serlize your JSON
so remove this line in your NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
and I follow your Answer
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self performSegueWithIdentifier:#"login_success" sender:self];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
}
Ankur kumawat I tried your coding and Brother #Anbu.karthik answer in iOS 9.I got few warnings.First I post Anbu.Karthik brother answer.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *strUserId = #"1000710017";
NSString *strPassword = #"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",strUserId,strPassword, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate 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];
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:&error];
int success = [jsonData[#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self performSegueWithIdentifier:#"login_success" sender:self];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
Above is brother Anbu.Karthik answer.I tried that and it shows me the warnings.
Warnings are
'sendSynchronousRequest:returningResponse:error:' is deprecated: first
deprecated in iOS 9.0 - Use [NSURLSession
dataTaskWithRequest:completionHandler:] (see NSURLSession.h
Then
Implicit conversion loses integer precision: 'long _Nullable' to 'int'
As I get warning I want to remove warning and
I must use
NSURLSession with dataTask because sendSynchronousRequest:returningResponse:error:' is deprecated in iOS 9.0
Then I modified the code.
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
NSString *strUserId = #"1000710017";
NSString *strPassword = #"XM0MB";
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#",strUserId,strPassword, nil];
//create the Method "GET" or "POST"
[urlRequest setHTTPMethod:#"POST"];
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//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) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
}
else
{
NSLog(#"Login FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];
The printed result is
The response is - {
success = 1;
}
And
Login SUCCESS
Now above my code works perfectly:-)
Try this code in view Controller file:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSLog(#"%#",dict);
if (dict)
{
NSString *status = [NSString stringWithFormat:#"%#",[dict valueForKey:#"success"]];
}
output: 1 // successfully
or
0 // Unsccssfully
NSString *msg = [NSString stringWithFormat:#"%#",[dict valueForKey:#"error_message"]];
Replace your code with this :
- (IBAction)Login:(id)sender {
if([[self.user_id text] isEqualToString:#""] || [[self.password text] isEqualToString:#""] ) {
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://sixthsenseit.com/school/project/ios/login.php"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"loginid=%#&loginpassword=%#&",_user_id.text,_password.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate 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];
Dictionary *dictResponce = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if (dictResponce)
{
NSString *status = [NSString stringWithFormat:#"%#",[dict valueForKey:#"success"]];
if (status == "1"){
//Push to home view controller
[self performSegueWithIdentifier:#"Home_page" sender:self];
}
else{
NSLog([NSString stringWithFormat:#"%#",[dict valueForKey:#"error_message"]]);
}
}
else{
NSLog(#"faield to connect");
}
}
}
In my project i am passing this API: http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat with params: prod_id=25,var_id=140.
The problem is when i am pass this api in Rest Client it displays correct response but when i am trying to put it in my code it shows different response.
i am using the following code:
-(void)listofNotice
{
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
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://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"]];
[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];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
it display the following response:
str : {
business = 0;
"business-list" = "Business list empty.";
response = 401;
}
but the actual response is something like this
please help me.. Thanks In advance
Please change this
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
To:
NSString * post =[NSString stringWithFormat:#"prod_id=25&var_id=140"];
if possible use this:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = #{#"application/x-www-form-urlencoded" : #"Content-Type"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [post dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (data != nil){
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"Status Code: %ld", (long)code);
if (code == 200) {
NSError *error;
id responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
}
}];
[postDataTask resume];
OR
NSString *postString = [NSString stringWithFormat:#"prod_id=%#&var_id=%#",#"25",#"140"];
NSURL *urlPath = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlPath
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSData *requestData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
[APP_DELEGATE removeLoader];
if(data != nil) {
NSDictionary *responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#" %#", responseObject);
}
else {
}
}];
Hope this helps.
I think you need to change below code
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
to
NSDictionary *prodDict=#{#"prod_id":#"25",
#"var_id":#"140"};
Posted a query previously about JSON parsing not working properly. Did more looking into it with a packet sniffer and also with another client that works properly and found out it's a syntax thing, that I still can't seem to solve.
The code in the bottom makes the HTTP request to have the JSON in it as:
{"key":"value"}
And my server is actually looking for a JSON in the following syntax:
key=%22value%22
I tried to write some code that does this manually, but figured there must be something out of the box for iOS, and I don't want to have faults in the future.
I messed around with it for a while trying to find the right code for the job, but couldn't (you can see some code I tried commented out). Can anyone help me?
+ (NSString*)makePostCall:(NSString*)urlSuffix
keys:(NSArray*)keys
objects:(NSArray*)objects{
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
// NSString *dataString = [self getDataStringFromDictionary:params];
// NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:0
error:&error];
// id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
// NSLog(#"%#", jsonObject);
if (!jsonData) {
// should not happen
NSError *error;
NSLog(#"Got an error parsing the parameters: %#", error);
return nil;
} else {
// NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(#"%#", jsonRequest);
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", urlPrefix, urlSuffix]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: jsonData];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// TODO: handle error somehow
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return returnString;
}
}