I am trying to upload a UIImage to .Net server by converting the image into base 64 and NSData. But I am getting the response null. Here is my code.
NSString *base64Encoded = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSString *post= [NSString stringWithFormat:#"myServerSideUrl?Image=%#",base64Encoded];
NSLog(#"PostData: %#",post);
NSString* webStringURL = [post stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:webStringURL];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSData *responseData = [[NSData alloc]initWithData:urlData];
if ([response statusCode] >=200 )
{
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData: responseData options:0 error:nil];
NSLog(#"%#",jsonData);
}
After some time, I just checked in postman showing like url too long HttpResponseCode:414. Also I tried to send the image in NSData format using AFNetwork, getting the same response. And I just googled about this, saying like send the base 64 string in body. When I tried to send image in body, server side can't get the image. They are creating the API like GET method but the actual method is POST. Is there any other solution about this. Any suggestions.
You are setting NSData to your request body without defining any key-value pair.
Try this code using AFNetworking...
- (void) uploadFileRequestWithHttpHeaders:(NSMutableDictionary*) headers
withServiceName:(NSString*) serviceName
withParameters:(NSMutableDictionary*) params
withFileData:(NSArray*) files
{
NSString *serviceUrl = [httpBaseURL stringByAppendingPathComponent:serviceName];
if (headers == nil)
{
NSDictionary *headers = [[NSDictionary alloc] initWithObjectsAndKeys:#"multipart/form-data",#"Content-Type",nil];
[self setHeaders:headers];
}
else
{
[headers setObject:#"multipart/form-data" forKey:#"Content-Type"];
[self setHeaders:headers];
}
[httpSessionManager POST:serviceUrl
parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (NSData *fileData in files)
{
[formData appendPartWithFileData:fileData name:#"userProfileImg" fileName:#"profile_pic.jpg" mimeType:#"image/jpeg"];
}
}
success:^(NSURLSessionDataTask *task, id responseObject) {
if (success != nil)
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
if (failure != nil)
}];
}
- (void) setHeaders:(NSDictionary*) headers
{
if (headers != nil)
{
NSArray *allHeaders = [headers allKeys];
for (NSString *key in allHeaders)
{
[httpSessionManager.requestSerializer setValue:[headers objectForKey:key] forHTTPHeaderField:key];
}
}
}
- (void) addQueryStringWithParams:(NSDictionary*) params
{
[httpSessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
__block NSMutableString *query = [NSMutableString stringWithString:#""];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&err];
NSMutableString *jsonString = [[NSMutableString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
query = jsonString;
return query;
}];
}
And call this method like this..
NSArray *objects = [NSArray arrayWithObjects:#"multipart/form-data",#"1.0",#"ios",token, nil];
NSArray *Keys = [NSArray arrayWithObjects:#"content-type",#"version",#"os",#"token", nil];
NSMutableDictionary *headers = [[NSMutableDictionary alloc]initWithObjects:objects forKeys:Keys];
NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
[paraDic setObject:self.userNameField.text forKey:#"name"];
NSData * userProfileImg = UIImageJPEGRepresentation(image, 0.8f);
imageDataArray = [NSArray arrayWithObjects:userProfileImg, nil];
[self uploadFileRequestWithHttpHeaders:headers withServiceName:#"updateProfile" withParameters:params withFileData:files];
You can try this code using NSURLSession-
- (void)postRequestForSubmitDataToServer {
//Put your action URL
NSURL *aUrl = [NSURL URLWithString:#"action_url.php?&attachment=att&submit=submit"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil) {
//change JSON type according to ur need.
NSArray *JSON = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"Data = %#",JSON);
} else {
NSLog(#"%#", error);
}
}];
[postDataTask resume];
}
My form data-
<form action="action_url.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="attachment" size="25" /><br>
<input type="submit" name="submit" value="Submit" /> </form>
I have gotten this JSON data back and I would like to parse it into the 3 categories: "guid", "exponent", and "modulus". How would I do that? Thank you for the help in advance!
2015-07-01 11:02:51.972 Acculunk KeyPad[4717:1667358] Response Body:
{"error_code":0,"error_message":"","exponent":"010001","guid":"855fd04f-0016-1805-a3be-84dbef17ffd6","modulus":"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5","tran_id":"cb2e8149-4961-458a-a6b2-7443bdb01509"}
2015-07-01 11:03:37.175 Acculunk KeyPad[4717:1674710] Terminating since there is no system app.
Here's the code:
NSString *temp2 = [NSString stringWithFormat:#"{\n \"partner_key\": \"%#\",\n \"auth_token\": \"QaU9QcFZ6xE7aiRRBge0wZ4p6E01GEbl\",\n \"payment_account_id\": \"%#\",\n \"card_number\": \"%#\",\n \"card_exp_date\": \"%#\",\n \"amount\": \"%#\",\n \"memo\": \"%#\",\n \"recipient\": {\n \"email\": \"%#\",\n \"mobile_phone\": \"%#\"\n }\n}",[Partner_Key text], [Payment_Account_ID text], [Card_Number text], [Card_Exp_Date text], [Amount text],[Memo text], [Recipient_Email text], [Recipient_Phone_Number text]];
NSLog(temp2);
NSURL *URL = [NSURL URLWithString:#"https://cert.payzur.com/payzurservices.svc/payment/send/initiate"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[temp2 dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// Handle error...
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
NSLog(#"Response HTTP Headers:\n%#\n", [(NSHTTPURLResponse *)response allHeaderFields]);
}
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
NSData *jsonData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:body options:nil error:&e];
if (res) {
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"];
NSString *modulus = res[#"modulus"];
}
else {
NSLog(#"Error: %#", error);
}
}];
[task resume];
Assuming, this data comes as type NSData, you can do the following:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:apiReturn options:0 error:&myError];
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"]; // Maybe also a NSNumber?
NSString *modulus = res[#"modulus"];
The Data will be available in the five variables:
errorCode
errorMessage
guid
exponent
modulus
Use + JSONObjectWithData:options:error: to create a NSDictionary of the JSON.
Then access the elements in the usual manner of accessing dictionary items.
Answer by Christopher Mäuer using the literal syntax:
NSError *error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:apiReturn options:0 error:&error];
if (res) {
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"]; // Maybe also a NSNumber?
NSString *modulus = res[#"modulus"];
}
else {
NSLog(#"Error: %#", error);
}
Updated for new question code:
Here is sample code, I have re-constructed the data received from the log out put in the question:
NSString *responseBody = #"{\"error_code\":0,\"error_message\":\"\",\"exponent\":\"010001\",\"guid\":\"855fd04f-0016-1805-a3be-84dbef17ffd6\",\"modulus\":\"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5\",\"tran_id\":\"cb2e8149-4961-458a-a6b2-7443bdb01509\"}";
NSData *data = [responseBody dataUsingEncoding:NSUTF8StringEncoding];
// The above was just to get `data` setup.
// The only function of the following two statements is to print the data as a string.
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
//
// NSData *jsonData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"res: \n%#", res);
if (res) {
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"];
NSString *modulus = res[#"modulus"];
NSLog(#"errorCode: %#\nerrorMessage: %#\nguid: %#\nexponent: %#\nmodulus: %#", errorCode, errorMessage, guid, exponent, modulus);
}
else {
NSLog(#"Error: %#", error);
}
Output:
Response Body:
{"error_code":0,"error_message":"","exponent":"010001","guid":"855fd04f-0016-1805-a3be-84dbef17ffd6","modulus":"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5","tran_id":"cb2e8149-4961-458a-a6b2-7443bdb01509"}
res:
{
"error_code" = 0;
"error_message" = "";
exponent = 010001;
guid = "855fd04f-0016-1805-a3be-84dbef17ffd6";
modulus = C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5;
"tran_id" = "cb2e8149-4961-458a-a6b2-7443bdb01509";
}
errorCode: 0
errorMessage:
guid: 855fd04f-0016-1805-a3be-84dbef17ffd6
exponent: 010001
modulus: C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5
I suggest you replacing the following two lines:
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
With the two code lines I provide:
NSError *error;
NSDictionary* responseData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
or with the following:
NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];
So now you have a NSDictionary, which is responseData, so now we can decode your JSON response as follows (I will put the whole code as follows):
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];
NSString *guid = [responseData valueForKey:#"guid"];
NSString *exponent = [responseData valueForKey:#"exponent"];
NSString *modulus = [responseData valueForKey:#"modulus"];
NSLog(#"Decoded Response :\n guide : %#,\n exponent : %#,\n modulus : %#", guid, exponent, modulus);
So your whole code which you have pasted above in your Question will look like following:
NSString *temp2 = [NSString stringWithFormat:#"{\n \"partner_key\": \"%#\",\n \"auth_token\": \"QaU9QcFZ6xE7aiRRBge0wZ4p6E01GEbl\",\n \"payment_account_id\": \"%#\",\n \"card_number\": \"%#\",\n \"card_exp_date\": \"%#\",\n \"amount\": \"%#\",\n \"memo\": \"%#\",\n \"recipient\": {\n \"email\": \"%#\",\n \"mobile_phone\": \"%#\"\n }\n}",[Partner_Key text], [Payment_Account_ID text], [Card_Number text], [Card_Exp_Date text], [Amount text],[Memo text], [Recipient_Email text], [Recipient_Phone_Number text]];
NSLog(temp2);
NSURL *URL = [NSURL URLWithString:#"https://cert.payzur.com/payzurservices.svc/payment/send/initiate"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[temp2 dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// Handle error...
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
NSLog(#"Response HTTP Headers:\n%#\n", [(NSHTTPURLResponse *)response allHeaderFields]);
}
NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];
NSString *guid = [responseData valueForKey:#"guid"];
NSString *exponent = [responseData valueForKey:#"exponent"];
NSString *modulus = [responseData valueForKey:#"modulus"];
NSLog(#"Decoded Response :\n guide : %#,\n exponent : %#,\n modulus : %#", guid, exponent, modulus);
}];
[task resume];
Well, you didn't say anything about how you got the data back, like if you already have it in a NSString or still in NSData, so I'm going to assume you have it in NSData.
NSData *json <- somehow I magically got jSON data into this
NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:json options:kNilOptions error:&error];
NSString guid = [NSString stringWithString:jsonDict[#"guid"];
NSString exponent = [NSString stringWithString:jsonDict[#"exponent"];
NSString modulus = [NSString stringWithString:jsonDict[#"modulus"];
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);
}
Some time when I call this piece of code *data is nil. It works most of the times except for certain situations which I'm not able to find.
Does anyone know why data could be nil and under which circumstances it could happen?
Some times *data isn't nil but it isn't what I'm expecting (for example I'm getting "login_okit_IT" instead of "login_ok")
Here is the code:
+ (NSDictionary *)eseguiRichiestaConURL:(NSString *)urlScript
{
NSString *rawStr = [NSString stringWithFormat:#""];
NSData *data = [rawStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:urlScript];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
//[request setTimeoutInterval:10000];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"%#", responseData);
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
//NSLog(#"%#", responseString);
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
if(responseData == nil)
NSLog(#"------ PARAMETRI VUOI -------");
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
return dict;
}
Thanks in advance.
This is my code for sending a post request to a nodejs backend.
CLLocation* location = [locationManager location];
CLLocationCoordinate2D coord = [location coordinate];
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://50.63.172.74:8080/points"]];
//[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSDictionary* jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:coord.latitude], #"lat", [NSNumber numberWithFloat:coord.longitude], #"lng", nil];//dictionaryWithObjectsAndKeys:coord.latitude, nil]
NSString *postString;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
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 {
postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
Using express I'm getting the request.body back on the server but it looks like this:
{ '{\n "lat" : 0.0,\n "lng" : 0.0\n}': '' }
and I can't access it by just saying request.body.lat since it comes back as undefined.
I want the body to look like:
{ "lat":0.0, "lng":0.0}
Any idea on how to do that using express?
May this help you.
Please replace 0.0 with your actual coordiantes
NSArray *keys = [NSArray arrayWithObjects:#"lat", #"lng", nil];
NSArray *objects = [NSArray arrayWithObjects:#"0.0",#"0.0", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData ;
NSString *jsonString;
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *requestString = [NSString stringWithFormat:
#"http://50.63.172.74:8080/points"];
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
NSLog(#"Error %#",errorReturned.description);
}
else
{
NSError *jsonParsingError = nil;
NSMutableArray *arrDoctorInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSLog(#"Dict %#",arrDoctorInfo);
}
The problem is that after you use NSJSONSerialization to obtain a NSData object containing your JSON data, you then create postString from that data. Eliminate that unnecessary step, and just do:
[request setHTTPBody:jsonData];
And you should get the expected JSON in your server-side code.