Error When Parsing Curl Api - ios

I Have implemented this code. When I run it for the first time, it gives a response. But When I Run it the Second time, it gives error like....
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No value.) UserInfo=0x178265540 {NSDebugDescription=No value.
But Whenever I uninstalled and rebuild it gives response.
NSMutableArray *data=[[NSMutableArray alloc]initWithObjects:#"type",#"st_eml",#"st_pwd",nil];
NSMutableArray *value=[[NSMutableArray alloc]initWithObjects:#"normal", #"Huhn",#"1234", nil];
//NSArray *keys = [[NSArray alloc ]initWithObjects:#"type", #"st_eml", #"st_pwd", nil];
//NSArray *objects = [[NSArray alloc]initWithObjects:#"normal", #"Huhn",#"123", nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:value forKeys:data];
// Serialize the data
NSError *error = NULL;
NSData *theJSONData = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary error:&error];
NSLog(#"Serialization Error: %#", error);
// Change the data back to a string
NSString* theStringObject = [[NSString alloc] initWithData:theJSONData encoding:NSUTF8StringEncoding];
// Determine the length of the data
NSData *requestData = [theStringObject dataUsingEncoding:NSUTF8StringEncoding];
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%lu", (unsigned long)[requestData length]];
// Create request to send to web service
NSString *strurl = #"http://testing.singletreffen.de/appapi/v1/login";
NSString* webStringURL = [strurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:webStringURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval:30.0];
// Deserialize the response
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error:&error];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

I have tried your code, made some changes in parsing and it's working properly and giving response also
NSMutableArray *data=[[NSMutableArray alloc]initWithObjects:#"type",#"st_eml",#"st_pwd",nil];
NSMutableArray *value=[[NSMutableArray alloc]initWithObjects:#"normal", #"Huhn",#"1234", nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:value forKeys:data];
// Serialize the data
NSError *error = nil;
NSData *theJSONData = [NSJSONSerialization dataWithJSONObject:theRequestDictionary options:0 error:&error];
NSLog(#"Serialization Error: %#", error);
// Change the data back to a string
NSString* theStringObject = [[NSString alloc] initWithData:theJSONData encoding:NSUTF8StringEncoding];
// Determine the length of the data
NSData *requestData = [theStringObject dataUsingEncoding:NSUTF8StringEncoding];
NSString* requestDataLengthString = [[NSString alloc] initWithFormat:#"%lu", (unsigned long)[requestData length]];
// Create request to send to web service
NSString *strurl = #"http://testing.singletreffen.de/appapi/v1/login";
NSString* webStringURL = [strurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:webStringURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[request setHTTPBody:requestData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:requestDataLengthString forHTTPHeaderField:#"Content-Length"];
[request setTimeoutInterval:30.0];
// Deserialize the response
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error:&error];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"LOG : %#", returnString);

Related

I want to pass the array inside the dictionary parameter with URL POST method

I am new to json, I want to pass the NSArray inside the NSDictionary as a parameter along with the url to server, how it can be done while method is post ? I had tried sample codes but not found my exact solution.below is my sample code
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:#"contact_name", #"kumar",#"designantion",#"sales", nil];
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:dict, #"OfficeContactPerson", nil];
NSString *post =[[NSString alloc]initWithFormat:#"name=%#&short_name=%#&shop_no=%#&door_no=%#&floor=%#&building=%#&street=%#&area=%#&main=%#&city=%#&state=%#&district=%#&pincode=%#&telephone=%#&contact_name=%#&designatio=%#&mobile=%#&email=%#&OfficeContactPerson=%#",self.txtshowroom.text,self.txtshortname.text,self.txtshop.text,self.txtdoor.text,self.txtfloor.text,self.txtbuilding.text,self.txtstreet.text,self.txtarea.text,self.txtmain.text,cityineger,stateintegervalue,districtintegervalue,self.txtpincode.text,self.txttel.text,self.txtname.text,self.txtdesign.text,self.txtmbl.text,self.txtemail.text,finalDict];
NSLog(#"postdata :%#",post);
NSURL *url=[NSURL URLWithString:#"http://139.59.252.34:1337/office"];
NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding 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:#"Content-Type"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error=[[NSError alloc]init];
NSHTTPURLResponse *response=nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (!urlData){
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Error"message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else
{
NSString *responseData=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response data ----->%#",responseData);
NSError *error=nil;
NSDictionary *jsonData=[NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error];
);
}
OfficeContactPerson": [
{
"office": 29,
"contact_name": "Priya",
"designation": "Prop",
"department": "ALL",
"mobile": "1231231231",
"email": "priya#yopmail.com",
"incharge_status": null,
"created_by": null,
"modified_by": null,
"id": 14,
"createdAt": "2016-04-19T13:43:59.000Z",
"updatedAt": "2016-04-19T14:25:36.000Z"
}
]
Convert array into json string or make dictionary of post data than convert it into json string and post string to server. I hope below code will work for you. This code is works fine for me-
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:#"contact_name", #"kumar",#"designantion",#"sales", nil];
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:dict, #"OfficeContactPerson", nil];
NSURL *url=[NSURL URLWithString:#"http://139.59.252.34:1337/office"];
NSData *postData=[[[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:finalDict options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] dataUsingEncoding:NSUTF8StringEncoding 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:#"Content-Type"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error=[[NSError alloc]init];
NSHTTPURLResponse *response=nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (!urlData){
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Error"message:[NSString stringWithFormat:#"%ld",(long)(error.code)]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else
{
NSString *responseData=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response data ----->%#",responseData);
NSError *error=nil;
NSDictionary *jsonData=[NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error];
}
I'm new in ios app development but I try to solve.lets assume that these are your string.Try this code:
NSString *messages-getModuleMessages=#"messages-getModuleMessages";
NSString * authtincateToken=#"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtSMDxxxxxxx";
NSString *accessSecretkey =#"WWc3ZFZCcEtWcGxLTk1hZHhEb2hMelFNZzdGcXgwdTBxeU51NWFwUE44TnkrcnF5SCtxxxxxxxx";
NSString *inboxvalue =#"hai thios is textmessage";
// this is your dictionary value are you passed
NSDictionary * callDict = [NSDictionary dictionaryWithObjectsAndKeys:messages-getModuleMessages,#"call",authtincateToken,#"authToken", accessSecretkey, #"accessSecret",inboxvalue,#"calotype",#"json",#"format",nil];
// convert your dictionary to NSData
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callDict options:kNilOptions error:nil];
// this is your service request url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xxxxxxxx"]];
// set the content as format
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
// this is your response type
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
// send the synchronous connection
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
// here add your server response NSJSONSerialization
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
// if u want to check the data in console
NSString *tmp=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", tmp);
Try below line of code and put them place of first two line of line code. Problem is only there.
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:#"contact_name", #"kumar",#"designantion",#"sales", nil];
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSArray arrayWithObject:dict], #"OfficeContactPerson", nil];
NSData *POST_Params = [NSJSONSerialization dataWithJSONObject:urlParams options:NSJSONWritingPrettyPrinted error:nil]; // Pass these post data in request
Hope this will work for you!!

How to send an object as a parameter for a POST request in iOS?

I need to bind parameters in an object and pass the object as a POST request to receive a successful piece of information from an API.
{
customer = {
"auth_token" = "";
"device_id" = 3e708bf1a49cdd06;
"email_address" = "abc#xyz.in";
name = abc;
number = 1234567890;
"resend_token" = true;
};
}
This is the object that I need to send along with the post request. But when I convert it into a string and post it, the entire object becomes the key and the value becomes nil. It gets posted as {"{customer.....}=>nil}.
The object should be posted as
{"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc#xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}
This my current attempt:
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setHTTPMethod:#"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
A lot of the code used here was used without a proper understanding and directly taken from other StackOverflow answers, so please excuse any bad programming practice.
How can I do this? Any help is appreciated. Thank you.
you can try below code.Instead of converting data to string set it as HTTPBody like
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = temp;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Following is the sample code for sending a POST request to server.
-(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
requestDic = [NSDictionary dictionaryWithDictionary:data];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Request Object:\n%#\n",data);
NSLog(#"Request String:\n%#\n",jsonString);
NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[theReq addValue: #"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theReq setHTTPMethod:#"POST"];
[theReq addValue:[NSString stringWithFormat:#"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:#"Content-Length"];
[theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
}
May this help lot and resolve your problem.
NSString *post =[[NSString alloc] initWithFormat:#"id=%d&restaurant_name=%#", restaurnt_Id, _rest_NameTxt.text];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];
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];
_responseData = [[NSMutableData alloc] init];
[NSURLConnection connectionWithRequest:request delegate:self];
pragma mark - connection methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_responseData setLength:0];
[_responseCityData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
[_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[COMMON showErrorAlert:#"Internet Connection Error!"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
NSLog(#"%#", responseString);
}
Make your task in connectionDidFinishLoading method

iOS 5 Json Serialization

I have used JSON Serialization to get json response, here i'mn getting all fine, but when i need to post some values as key value pair with the URL. I have done like this, but didn't get the result.
NSArray *objects = [NSArray arrayWithObjects:#"uname", #"pwd", #"req",nil];
NSArray *keys = [NSArray arrayWithObjects:#"ann", #"ann", #"login", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:keys forKeys:objects];
if ([NSJSONSerialization isValidJSONObject:dict]) {
NSError *error;
result = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error == nil && result != nil) {
// NSLog(#"Success");
}
}
NSURL * url =[NSURL URLWithString:#"URL_address_VALUE/index.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[result length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:result];
NSURLResponse *res = nil;
NSError *error = nil;
NSData *ans = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&error];
if (error == nil) {
NSString *strData = [[NSString alloc]initWithData:ans encoding:NSUTF8StringEncoding];
NSLog(#"%#",strData);
}
I don't know what goes wrong here... Please dudes help me..
There are multiple Errors in your Code, Use my Code as a Reference and compare it to yours and you'll get the Errors done by you.
The Below code is working correctly from the Point of View of Objective-C. There are some Errors regarding your URL or Service Side.
Working Code :
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"ann",#"uname",#"ann",#"pwd",#"login",#"req", nil];
NSLog(#"dict :: %#",dict);
NSError *error2;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error2];
NSString *post = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"postLength :: %#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://exemplarr-itsolutions.com/dbook/index.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error3;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error3];
NSString *str = [[NSString alloc] initWithData:POSTReply encoding:NSUTF8StringEncoding];
NSLog(#"str :: %#",str);

Send JSON post data from iPhone Application Expressjs/Nodejs backend

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.

Getting JSON data From a URL Which contains .SVC?wsdl file in iOS 5?

Someone please help me in this query.
How to Get JSON data From a URL Which contains .SVC file in iphone (ios5)?
The link is like : http://156.160.45.118/api/Login.svc?wsdl (not original)
and parameters are: email and password.
So how can I verify the login credentials?
My code :
NSString *username = emailField.text;
NSString *password = passwordField.text;
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:username forKey:#"user_email"];
[dictionnary setObject:password forKey:#"user_password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"http://156.160.45.118/api/Login.svc?wsdl";
NSURL *url = [NSURL URLWithString:urlString];
// Prepare the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"json" forHTTPHeaderField:#"Data-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&theResponse
error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
}
Finally i got my answer By researching lot of things.
NSString *username = emailField.text;
NSString *password = passwordField.text;
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:username forKey:#"user_email"];
[dictionnary setObject:password forKey:#"user_password"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = http://156.160.45.118/api/Login.svc/login;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
NSLog(#"%#", responseString);

Resources