I am at a loss here, I thought I'd try something new with web services for my app.
I can pull data down no problem, but I am trying to post to the server and just can seem to get this to even fire.
What I am intending to happen is on submit button press the action be fired:
- (IBAction)didPressSubmit:(id)sender {
//JSON SERIALIZATION OF DATA
NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
[projectDictionary setObject:[projectName text] forKey:#"name"];
[projectDictionary setObject:[projectDescShort text] forKey:#"desc_short"];
[projectDictionary setObject:[projectDescLong text] forKey:#"desc_long"];
NSError *jsonSerializationError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
if(!jsonSerializationError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Serialized JSON: %#", serJSON);
} else {
NSLog(#"JSON Encoding Failed: %#", [jsonSerializationError localizedDescription]);
}
// JSON POST TO SERVER
NSURL *projectsUrl = [NSURL URLWithString:#"http://70.75.66.136:3000/projects.json"];
NSMutableURLRequest *dataSubmit = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[dataSubmit setHTTPMethod:#"POST"]; // 1
[dataSubmit setValue:#"application/json" forHTTPHeaderField:#"Accept"]; // 2
[dataSubmit setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"]; // 3
[dataSubmit setHTTPBody: jsonData];
[[NSURLConnection alloc] initWithRequest:dataSubmit delegate:self];
}
After that it runs through:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"DidReceiveResponse");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
NSLog(#"DidReceiveData");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"BLAH CHECK YOUR NETWORK" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
I am obviously missing something, but I don't even know where to look. All I need is a point in the right direction, any help would be great.
UPDATE
I was able to get the request to fire with the following.
Okay I was able to get the request to fire using the following:
- (IBAction)didPressSubmit:(id)sender {
NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
[projectDictionary setObject:[projectName text] forKey:#"name"];
[projectDictionary setObject:[projectDescShort text] forKey:#"desc_small"];
[projectDictionary setObject:[projectDescLong text] forKey:#"desc_long"];
NSError *jsonSerializationError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
if(!jsonSerializationError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Serialized JSON: %#", serJSON);
} else {
NSLog(#"JSON Encoding Failed: %#", [jsonSerializationError localizedDescription]);
}
NSURL *projectsUrl = [NSURL URLWithString:#"http://70.75.66.136:3000/projects.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:#"POST"]; // 1
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"]; // 2
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"]; // 3
[request setHTTPBody: jsonData]; // 4
(void) [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
But for some reason the post method only received a bunch of nil values, I am getting this from the server side. Processing by ProjectsController#create as JSON
Parameters: {"{\n \"desc_long\" : \"a\",\n \"name\" : \"a\",\n \"desc_small\" : \"a\"\n}"=>nil}
UPDATE 2
With a little read from here: http://elusiveapps.com/blog/2011/04/ios-json-post-to-ruby-on-rails/
I was able to see if missed the following line.
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
So final didPressSubmit code is as follows;
- (IBAction)didPressSubmit:(id)sender {
NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
[projectDictionary setObject:[projectName text] forKey:#"name"];
[projectDictionary setObject:[projectDescShort text] forKey:#"desc_small"];
[projectDictionary setObject:[projectDescLong text] forKey:#"desc_long"];
NSError *jsonSerializationError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
if(!jsonSerializationError) {
NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Serialized JSON: %#", serJSON);
} else {
NSLog(#"JSON Encoding Failed: %#", [jsonSerializationError localizedDescription]);
}
NSURL *projectsUrl = [NSURL URLWithString:#"http://70.75.66.136:3000/projects.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:#"POST"]; // 1
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"]; // 2
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"]; // 3
[request setHTTPBody: jsonData]; // 4
(void) [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
I got same issue but I resolved it by setting the options to nil.
Replace
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];
by
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:nil error:&jsonSerializationError];
Use option to nil if you are sending json to server, if you are displaying json use NSJSONWritingPrettyPrinted.
Hope this will help you.
Related
I have made a login form. Fields r email and password. Now i want to POST the data from fields to specific url how it can be done. I'm totally new to IOS. Can anybody help me?? How to do HTTP request and JSON parsing?
/*********See this**********/
-(void)webServiceCall{
NSString *dataToSend = [NSString stringWithFormat:#"Username=%#&Password=%#“,<userIdEnter Here>,<Password enter here>];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *Length = [NSString stringWithFormat:#"%d",[postData length]];
[request setURL:[NSURL URLWithString:#“WEBURL”]];
[request setHTTPMethod:#"POST"];
[request setValue:Length forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
// check connection if you want
/*****get response in delegates*******/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:
(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
/**************/
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
// NSArray* latestLoans = [json objectForKey:#"loans"];
NSLog(#"json: %#", json);
[_responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error --> %#",error.localizedDescription);
/***************/
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
// use Result
self.responseData = nil;
}
I am using NSURLConnection method to call the web services what I want is to replace it with 3rd party library AFNetworking how shall I achieve this I am calling the web Services with data first time here is what I am doing currently.
- (void)viewDidLoad {
[super viewDidLoad];
NSURL * linkUrl = [NSURL URLWithString:#URLBase];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:linkUrl];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[str length]];
[theRequest addValue: #"text/plain; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [str dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData alloc] init];
}
else
{
NSLog(#"theConnection is NULL");
}
}
#pragma mark -- Connection Delegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//NSLog(#"%#",response);
//[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"\nERROR with theConenction");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseDataString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"Converted NSData %# ",responseDataString);
}
here
[theRequest setHTTPBody: [str dataUsingEncoding:NSUTF8StringEncoding]];
str is my encrypted data like username and password.
thanks in advance.!
You need to send POST request to your web services. You can use below code snippet for old way.
NSString *post = [NSString stringWithFormat:#"%#&value=%#&value=%#&value=%#&value=%#&value=%#",self.Comment_Memberid,self.SharedID,self.Post_Ownerid,self.commentText.text,email_stored,password_stored];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://.../api/json/postcomment/"]]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/plain; charset=utf-8" forHTTPHeaderField:#"Content-type"];
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:postData];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %ld", (long)[urlResponse statusCode]);
if ([urlResponse statusCode] == 200)
{
}
And if you want to send POST request using with AFNetworking you can use below code:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = #{#"34": x,
#"130": y};
[manager POST:#"https://../api/json/cordinates" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I am calling odata post api having HTTP header filed is "form-data". Below is my code :-
NSURL *restURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:restURL];
[request setHTTPMethod: getorpost];
if (jsonData != nil) {
[request setValue:#"application/form-data" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
}
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
responseData = [[NSMutableData alloc] init];
}
And i am getting below response:-
Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details
But, it is working fine in Postman. Can anyone please suggest where is the fault in my code.
Thanks,
Use this
NSURL *url = [NSURL URLWithString:url_str];
NSLog(#"%#",datastring);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSMutableData *requestBody = [[NSMutableData alloc] initWithData:[datastring dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"no-cache" forHTTPHeaderField:#"Cache-Control"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestBody length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestBody];
httpResponse=[[NSHTTPURLResponse alloc]init];
receivedData=[[NSMutableData alloc]init];
connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(connection)
{
NSLog(#"%# calling with datastring: %#", url, datastring);
}
delegates
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%d", httpResponse.statusCode);
NSLog(#"%#",[httpResponse description]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
receivedData = [[NSMutableData alloc]init];
httpResponse=[[NSHTTPURLResponse alloc]init];
NSLog(#"%#",[NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSString *retVal = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"retVal=%#",retVal);
}
-(void)ViewDidLoad
{
NSMutableDictionary *postData = [[NSMutableDictionary alloc]init];
[postData setObject:uid forKey:#"id"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postData options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"%#",jsonInputString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"YOUR URL "]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *jsonDict;
if (responseData != nil)
{
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"jsonDoct == %#",jsonDict);
}
else
{
NSLog(#"RESONPSE IS NULL");
}
if (error)
{
NSLog(#"error %#",error.description);
}
}
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
I am trying to post some data to the web service using JSON POST method, I have tried so many ways to do this, but none is working. Here is my code, please check:
NSArray *objects=[NSArray arrayWithObjects:#"value1", #"value2",#"value3", #"value4",#"value5", #"value6",#"value7", #"value8",#"value9", nil] ;
NSArray *keys=[NSArray arrayWithObjects:#"FirstName", #"LastName",#"UserName", #"Password",#"Email", #"Gender",#"DeviceId", #"DeviceName",#"ProfileImage", nil];
NSData *_jsonData=nil;
NSString *_jsonString=nil;
NSURL *url=[NSURL URLWithString:urlstring];
NSDictionary *JsonDictionary=[NSDictionary dictionaryWithObjects:objects forKeys:keys];
if([NSJSONSerialization isValidJSONObject:JsonDictionary]){
_jsonData=[NSJSONSerialization dataWithJSONObject:JsonDictionary options:0 error:nil];
_jsonString=[[NSString alloc]initWithData:_jsonData encoding:NSUTF8StringEncoding];
}
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
// [request setHTTPBody:_jsonData];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:[NSString stringWithFormat:#"%d", [_jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *finalString = [_jsonString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
[request setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
// //return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
Please check.
Here is a sample code am trying to register a user.
In the 'Register' button click,write the following code:
- (IBAction)registerButtonPressed:(id)sender
{
BOOL valid = FALSE;
valid=[self validateEntry];
if(valid)
{
NSString *bytes = [NSString stringWithFormat:#"{\"UserName\":\"%# %#\",\"Email\":\"%#\",\"UserType\":\"normaluser\",\"Password\":\"%#\"}",firstName,lastName,email,password];
NSURL *url=[NSURL URLWithString:urlstring];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[bytes dataUsingEncoding:NSUTF8StringEncoding]];
[self setUrlConnection:[NSURLConnection connectionWithRequest:request delegate:self]];
[self setResponseData:[NSMutableData data]];
[self.urlConnection start];
}
}
Then add the following as Connection delegate methods:
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Network Status"
message:#"Sorry,Network is not available. Please try again later."
delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == self.urlConnection)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSError *error;
NSDictionary *jsonString=[NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error];
if(jsonString != nil)
{
if ([[[jsonString objectForKey:#"data"] objectForKey:#"id"] length])
{
[[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:#"data"] objectForKey:#"id"] forKey:#"user_id"];
[[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:#"data"] objectForKey:#"UserName"] forKey:#"user_name"];
[[NSUserDefaults standardUserDefaults] synchronize];
[delegate userRegistrationViewControllerResponse:self];
}
else
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"Info" message:[jsonString objectForKey:#"statusText"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
}
}
else
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"Server Busy" message:#"Register after sometime" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
}
}
}
This will post the user information as JSON.
Try this one....
NSURL *aUrl = [NSURL URLWithString:#"https://www.website.com/_api/Login/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:0.0];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"EmailAddress=%#&UserPassword=%#",uName.text,pwd.text];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
-Than call the NSURLConnection delegate methods.. dot forgot to alloc the responseData....
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseData = nil;
json =[[responseString JSONValue] retain];
NSLog(#"Dict here: %#", json);
}
The request should be something along these lines...
NSURL * url = [NSURL URLWithString:#"your_url"];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError * error = nil;
NSData * postData = [NSJSONSerialization dataWithJSONObject:your_json_dictionary_here options:NSJSONReadingMutableContainers error:&error];
[request setHTTPBody:postData];
I also suggest to check your response to find out why is your request failing. Is it on the client side or server side (and why?)...