Calling web services with the help of AFNetworking in Objective C - ios

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);
}];

Related

Sending an HTTP POST with header form-data request on iOS

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);
}
}

nsurlsessiondatatask returns nil while sending a post request to REST based url ios

-(void)showData {
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"1", #"number",nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
NSLog(#"data is %#", data );
NSLog(#"response is %#" , response);
}];
[postDataTask resume];
}
when i execute the code the debugger jumps from the NSURLSessionDataTask and log generated is __NSCFLocalDataTask: 0x7ff061751960>{ taskIdentifier: 1 } { suspended } and does not come any data in NSData and NSResponse.
#interface UrClass:NsObject<NSURLConnectionDelegate>{ NSMutableData *_receivedData;
}
-(void)showData{
NSString * urlStr = [NSString stringWithFormat:#"%#", path];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setURL:[NSURL URLWithString:urlStr]];
NSString *requestStr = [dictionary JSONRepresentation];
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", (unsigned int)[requestData length]];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:requestData];
[theRequest addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setTimeoutInterval:REQUEST_TIME_OUT_SECS];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:NO];
[theConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[theConnection start];
if (theConnection)
_receivedData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
Try this code:
NSURL *url=[NSURL URLWithString:#"https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts"];
NSData *contactData=[NSData dataWithContentsOfURL:url];
NSMutableArray *allContectData=[NSJSONSerialization JSONObjectWithData:contactData options:0 error:nil];
NSLog(#"%#",allContectData);
Otherwise use this code
-(void)showData{
NSString *urlString = #"https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NO timeoutInterval:20.0f];
responseData = [[NSMutableData alloc] init];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
use NSURLConnectionDataDelegate Delegate Method
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSMutableArray *allContectData=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",allContectData);
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#",error);
}

unable to fetch data as Post when Sending it as Post From IOS NSMutableURLRequest

this is the snippet to my Code, i am sending the code to a PHP page, but when i do print_r($_POST); i get empty Array, but when i do print_r($_GET) i get the variable which i am using to post the data i.e name but it also is empty, can any 1 sort out what i am doing wrong here
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnFetchData1:(id)sender {
// NSString *urlString = [NSString stringWithFormat:#"http://localhost/adi/adnan.php?name=%#", [self.txtName text]];
NSString *urlString = [NSString stringWithFormat:#"http://localhost/adi/adnan.php"];
NSString *post = [NSString stringWithFormat:#"name=%#",#"adnan"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
delegate:self];
if (conn) {
_receivedData=[NSMutableData data];
} else {
//something bad happened
}
}
#pragma NSUrlConnectionDelegate Methods
-(void)connection:(NSConnection*)conn didReceiveResponse:(NSURLResponse *)response
{
if (_receivedData == NULL) {
_receivedData = [[NSMutableData alloc] init];
}
[_receivedData setLength:0];
NSLog(#"didReceiveResponse: responseData length:(%d)", _receivedData.length);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error {
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data",[_receivedData length]);
NSString *responseText = [[NSString alloc] initWithData:_receivedData encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
[self.lblData setText:responseText];
}
You created postLength but never used it, try this it might solve it:
//create URL for the request
NSString *urlString = [NSString stringWithFormat:#"http://localhost/adi/adnan.php"];
//Post data
NSString *post = [NSString stringWithFormat:#"name=%#",#"adnan"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding]
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
//the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Bind the request with Post data
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];

Trying to use native iOS code for connecting to .NET web service

I have just gone through a tutorial to connect to a .NET web service from iOS using the library AFNetworking (http://afnetworking.com/). My code works fine, however, I am wondering how I can achieve the same functionality using native code (like NSURLConnection) that comes by default in iOS?
Here is my code below:
NSURL *url = [NSURL URLWithString:#"http://www.blah.com"];
NSString *soapBody = #"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><Customers xmlns=\"http://tempuri.org/\" /></soap:Body></soap:Envelope>";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:[soapBody dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request addValue:#"http://tempuri.org/Customers" forHTTPHeaderField:#"SOAPAction"];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", [operation responseString]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failed");
}];
[operation start];
In particular, it is this block of code:
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", [operation responseString]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failed");
}];
[operation start];
that I would like to know how to replace, using NSURLConnection.
Thanks in advance to all who reply.
Try something like this
NSURL *url = [NSURL URLWithString:#"http://www.blah.com"];
NSString *soapBody = #"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><Customers xmlns=\"http://tempuri.org/\" /></soap:Body></soap:Envelope>";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:[soapBody dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request addValue:#"http://tempuri.org/Customers" forHTTPHeaderField:#"SOAPAction"];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = #"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] init];
(void)[conn initWithRequest:request delegate:self];
Use these delegate methods to get your response or handle error
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//create _responseData variable before only
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
If you want the request to be synchronous try this:
NSError * error = nil;
NSURLResposnse *response;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (error == nil)
{
// Parse data here
}

NSURLConnection JSON Submit to Server

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.

Resources