I am trying to post and JSON data to server.
My JSON is:
{
“username”:”sample”,
“password” : “password-1”
}
The way I am sending it to server is:
NSError *error;
NSString *data = [NSString stringWithFormat:#"{\"username\":\"%#\",\"password\":\"%#\"}",_textFieldUserName.text,_textFieldPasssword.text];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSData *jsonData = [NSJSONSerialization JSONObjectWithData:postData options:0 error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"My URL"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:requestHandler options:0 error:&error];
NSLog(#"resposne dicionary is %#",responseDictionary);
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
The JsonData that is created is a valid JSON accepted by the server.
But the app is crashing and the error is:
-[__NSCFDictionary length]: unrecognized selector sent to instance 0x1702654c0
what is wrong that i am doing here?
I always use this method in my apps to perform API calls. This is the post method. It is asynchronous so you can specify a callback to be called when the server answer.
-(void)placePostRequestWithURL:(NSString *)action withData:(NSDictionary *)dataToSend withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"%#", action];
NSLog(#"%#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataToSend options:0 error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
}
}
You can easily call it:
- (void) login:(NSDictionary *)data
calledBy:(id)calledBy
withSuccess:(SEL)successCallback
andFailure:(SEL)failureCallback{
[self placePostRequestWithURL:#"yourActionUrl"
withData:data
withHandler:^(NSURLResponse *response, NSData *rawData, NSError *error) {
NSString *string = [[NSString alloc] initWithData:rawData
encoding:NSUTF8StringEncoding];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"%ld", (long)code);
if (!(code >= 200 && code < 300)) {
NSLog(#"ERROR (%ld): %#", (long)code, string);
[calledBy performSelector:failureCallback withObject:string];
} else {
NSLog(#"OK");
NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:
string, #"id",
nil];
[calledBy performSelector:successCallback withObject:result];
}
}];
}
And finally, you invocation:
NSDictionary *dataToSend = [NSDictionary dictionaryWithObjectsAndKeys:
_textFieldUserName.text, #"username",
_textFieldPasssword.text, #"password", nil];
[self login:dataToSend
calledBy:self
withSuccess:#selector(loginDidEnd:)
andFailure:#selector(loginFailure:)];
Don't forget to define your callbacks:
- (void)loginDidEnd:(id)result{
NSLog(#"loginDidEnd:");
// Do your actions
}
- (void)loginFailure:(id)result{
NSLog(#"loginFailure:");
// Do your actions
}
First you create an NSString* that is supposed to contain JSON data. This doesn't work in general if the username and password contain any unusual characters. For example, I make sure that I have a quotation mark in my password to make sure that stupid software crashes.
You turn that string into an NSData* using ASCII encoding. So if my username contains any characters that are not in the ASCII character set, what you get is nonsense.
You then use the parser to turn this into a dictionary or array, but store the result into an NSData. Chances are that the parse fails and you get nil, otherwise you get an NSDictionary* or an NSArray*, but most definitely not an NSData*.
Here's how you do it properly: You create a dictionary, and then turn it into NSData.
NSDictionary* dict = #{ #"username": _textFieldUserName.text,
#"password": _textFieldPasssword.text };
NSError* error;
NSData* data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
That's it.
try this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:#"My URL"];
if (!request) NSLog(#"Error creating the URL Request");
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"text/json" forHTTPHeaderField:#"Content-Type"];
NSLog(#"will create connection");
// Send a synchronous request
NSURLResponse * response = nil;
NSError * NSURLRequestError = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&NSURLRequestError];
Related
I do synchronous post request and get xml. Now I need parse and save it in NSDictionary. I tried many solutions from the web. But nothing worked for me. Here's my code:
//Response data object
NSData *returnData = [[NSData alloc]init];
NSString *param = #"{params}";
NSString *postString = [NSString stringWithFormat:#"request=%#",param];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"url"]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
bool debug = YES;
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLFile:response];
if (debug && response) {
NSLog(#"Response >>>> %#", xmlDoc);
}
I used this xml reader. Here is result which I get in nslog:
2016-11-28 18:04:26.970 SyncPostReq[8667:305923] Response >>>> (null)
NSURL *url = [NSURL URLWithString:#"url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSError *parseError;
NSDictionary* xmlDict1 = [XMLReader dictionaryForXMLData:data error:&parseError];
NSDictionary *dictData = [xmlDict1 objectForKey:#"event_listing"];
arrData = [dictData objectForKey:#"event"];
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject:arrData
forKey:#"Keyupevent"];
[defaults setBool:YES forKey:#"KeyalldataLoad"];
[defaults synchronize];
uparrData =[[defaults objectForKey:#"Keyupevent"] mutableCopy];
[arrStoreAllEventsData addObjectsFromArray:uparrData];
[self.tblView reloadData];
[self loadPastEventdatafromxml];
}] resume];
I am new to JSON and I am trying to send a post I am wondering if how can I check if I did it properly or check the return value of it. Here's what I've done
NSURL *url = [NSURL URLWithString:#"http://json.myurl.com/.....];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postdata];
For a beginner, I would recommend using third party framework, widely used by iOS developers across the world, called AFNetworking.
By using AFNetworking, HTTP requests are simple as that:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
// TODO: Parse success here!
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// TODO: Parse failure here!
}];
In given example, object responseObject is a representation of API response JSON object.
Installation and further usage instructions of AFNetworking can be found in their website.
To check JSON POST return value:
NSString *strUrl=[NSString stringWithFormat:#"http://json.myurl.com/....."];
NSString *webStringURL = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError* error;
NSData* postData = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error: &error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *jsonData, NSError *error)
{
if (!error)
{
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"jsonResponse--->%#",jsonResponse);
});
}
else
{
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"error--->%#",error.description);
});
}
}];
And to check you JSON format is correct or not go through this link
i am using iMessage bubble to create chat view working fine
https://github.com/kerrygrover/iMessageBubble
When i call my web service in my inside method this at end
- (IBAction)sendMessage:(id)sender
here is my web method calling function which gives result out put success and send my chat to the server, but my view freeze.
NSError *errorReturned = nil;
NSString *urlString = #"https://url/methodname”;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:employeeId forKey:#"employeeId"];
[dict setObject:employeename forKey:#"employeename"];
NSLog(#"dic=%#",dict);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&errorReturned];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
//...do something with the returned value
}
}
plz create a new queue not run this code on main queue . you are running the code on main queue plz use this
dispatch_queue_t myQueue = dispatch_queue_create("myQueue", NULL);
// execute a task on that queue asynchronously
dispatch_async(myQueue, ^{
NSError *errorReturned = nil;
NSString *urlString = #"https://url/methodname”;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:employeeId forKey:#"employeeId"];
[dict setObject:employeename forKey:#"employeename"];
NSLog(#"dic=%#",dict);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&errorReturned];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
//...do something with the returned value
}
});
I am trying to post data to server and send data json like this
data: {"userID":"AAAAA","token":"12345","type":"BBB","version":"45"}
here is image
NSDictionary *requestDictionary = #{#"data" : #{
#"{userID" : #"AAA", #"token ": #"12345",#"type":#"iOS",#"version":#"1}"}};
NSURL *urls =[NSURL URLWithString:[NSString stringWithFormat:#"http://URL/send_code"]];
self.request = [[NSMutableURLRequest alloc]init];
[self.request setURL:urls];
NSString *contentType = [NSString stringWithFormat:
#"application/json"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setHTTPMethod:#"POST"];
[request addValue:#"IOS" forHTTPHeaderField: #"X-Application-Platform"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil]];
NSData *postdata = [NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil];
urlconnection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:true];
i ve tried several times and get invalid data response
please help me.thanks in advance
Try to send using AFNetworking:
First try to convert Json into Dictionary.
NSError *error;
NSData *objectData = [#"{Your dictionary}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&error];
Then you can send this dictionary:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:#"your_URL" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"Complete");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Fail");
}];
I need to Parse below string to POST method in iOS
"jsonData":{"empId":"cxvd","password":"sfsd"}
But I m getting the error as
Res: Tomcat Error
HTTP Status 400 - Required String parameter 'jsonData' is not present
//------ Method I have used to Parse is ---------- //
+(void) requestToServerForLogin:(NSString*)userName andPassward: (NSString*)password onCompletion:(RequestCompletionHandler) handler
{
NSString *url = [Ip stringByAppendingString:#"login"];
NSString *jsonString = [NSString stringWithFormat:#"\"jsonData\":{\"empId\":\"%#\",\"password\":\"%#\"}",
userName,
password ];
NSURL *nsurl = [NSURL URLWithString:url];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:nsurl];
[urlRequest setTimeoutInterval:60.0f];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/json"
forHTTPHeaderField:#"Content-type"];
NSString *body = jsonString1;
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"urlRequest :%#",[body dataUsingEncoding:NSUTF8StringEncoding]);
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data1, NSError *error)
{
NSString *res = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
if(handler) handler(res,error);
}];
}
Thanks in advance
There is way to much code. The substringToIndex and substringFromIndex are wrong, should not be in the code.
Use the literal syntax for the dictionaries:
NSDictionary *jsonDict = #{#"jsonData":#{#"password":password, #"empId":userName}};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];