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!!
NSString *Str = #"Basic YnRwaXhlbDoxMjM0NQ==";
NSArray *keys = [NSArray arrayWithObjects: #"Authorization",nil];
NSArray *objects = [NSArray arrayWithObjects:Str,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONReadingMutableContainers error:&error];
NSURL *urlStr1 = [NSURL URLWithString:#"http://192.168.0.49/bubbletop/index.php?route=feed/rest_api/gettoken&grant_type=client_credentials"];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] initWithURL:urlStr1];
[request1 setHTTPMethod:#"POST"];
[request1 setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request1 setHTTPBody: jsonData];
_connection = [[NSURLConnection alloc]initWithRequest:request1 delegate:self startImmediately:YES];
NSData *data1 = [NSData dataWithContentsOfURL:urlStr1];
NSDictionary *fashionJson = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:nil];
NSLog(#"requestReply: %#", fashionJson);
Here i'm passing the header field parameter as Basic YnRwaXhlbDoxMjM0NQ== for the key Authorization but getting the data as nil and getting log as
requestReply: (null)
I think you were added header field as wrong
not like
NSString *Str = #"Basic YnRwaXhlbDoxMjM0NQ==";
NSArray *keys = [NSArray arrayWithObjects: #"Authorization",nil];
NSArray *objects = [NSArray arrayWithObjects:Str,nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONReadingMutableContainers error:&error];
do like as HTTP token authentication
[request1 addValue:#"Basic YnRwaXhlbDoxMjM0NQ==" forHTTPHeaderField:#"Authorization"];
Note
no need of append body in here
[request1 setHTTPBody: jsonData];
for sample request see this
Since you are using NSData *data1 = [NSData dataWithContentsOfURL:urlStr1]; method, it will not take your httpbody from the url request you created. Either implement NSURLConnection delegate methods or use NSURLSession to load the data. Since NSURLConnection API is deprecated, I would recommend NSURLSession.
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);
I have used SBJsonParser and ASIFormDataRequest for Posting and JSON Parsing, like
NSString *urlStr = #"http:facebookpage/second/index.php";
NSURL *log_Url = [NSURL URLWithString:urlStr];
request = [ASIFormDataRequest requestWithURL:log_Url];
[ASIHTTPRequest setSessionCookies:nil];
[request setPostValue:uName.text forKey:#"uname"];
[request setPostValue:passWord.text forKey:#"pwd"];
[request setPostValue:#"login" forKey:#"req"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
response = [request responseString];
}
NSLog(#"%#",response);
Then For Parsing:
parser = [[SBJsonParser alloc]init ];
json_dic_values = [parser objectWithString:response error:nil];
NSString *status = [json_dic_values objectForKey:#"status"];
Url_pathforPages = [json_dic_values objectForKey:#"url"];
NSString *sessionID = [json_dic_values objectForKey:#"session_id"];
Here I need to know how can i do this same in NSJsonSerialization.
Everything is working fine in above method....
There are really only a few methods in NSJSONSerialization. Take a look at the documentation.
json_dic_values = [NSJSONSerialization JSONObjectWithData: [response dataUsingEncoding: NSUTF8StringEncoding] options: 0 error: &error];
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);