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?)...
Related
-(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);
}
I have 3 UITextfield and 1 Button, when I button click 3 UITextfield data sent to the database using forms.
my code is send the data to database but it's show in null values in database.
<form action="//http://192.168.3.171:8090/RestWebService/rest/person" id="suggestions" method="post">
<input id="name" name="name" type="text" >
<input id="suggestion" name="suggestion" type="text">
<input id="submitsuggestion" name="submitsuggestion" type="text">
</form>
Viewcontroller.M
#import "ViewController.h"
#interface ViewController ()
{
NSMutableData *recievedData;
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
NSMutableString *first;
}
#end
#implementation ViewController
#synthesize webview;
#synthesize firstName;
#synthesize lastName;
#synthesize email;
- (void)viewDidLoad
{}
- (IBAction)send:(id)sender
{
NSString *name = firstName.text;
NSLog(#" name is %# ",name);
NSString *lastname = lastName.text;
NSLog(#" name is %# ",lastname);
NSString *emailname = email.text;
NSLog(#" name is %# ",emailname);
if (name.length == 0 || lastname.length == 0 || email.text==0) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Message!" message:#"plz enter 3 fields " delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}else{
webData=[NSMutableData data];
NSURL *url = [NSURL URLWithString:#"http://192.168.3.128:8050/RestWebService/rest/person"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [#"name=firstName&suggestion=lastName&submitsuggestion=email" dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"requestData%#",requestData);
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//[request setValue:requestData forHTTPHeaderField:#"Content-Length"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSLog(#"requestData*******:%#",requestData);
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection successfull");
NSLog(#"GOOD Day My data %#",webData);
}
else
{
NSLog(#"connection could not be made");
}
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
NSLog(#"DidReceiveResponse");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
NSLog(#"DidReceiveData");
NSLog(#"DATA %#",data);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error is");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[webData length]);
NSLog(#"Data is %#",webData);
// NSLog(#"receivedData%#",_receivedData);
NSString *responseText = [[NSString alloc] initWithData:webData encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);//holds textfield entered value
NSLog(#"");
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
NSLog(#"ResponesText %#",responseText);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
my UITextfield data will be stored in database but it's null.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.appListData = [NSMutableData data]; // start off with new data
}
or
How to pass web service
NSString *post = [NSString stringWithFormat:#"first_name=%#&last_name=%#",firstName.text,lastName.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://localhost/promos/index.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
// indicator.hidden = NO;
mutableData = [[NSMutableData alloc]init];
}
your PHP code
<?php
$first name = $_POST['first_name'];
$last name=$_POST['last_name'];
echo $username;
?>
Exact answer here for your above Question[FOR POSTING DATA IN YOUR URL(SERVER)]
//Here YOUR URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://192.168.3.128:8050/RestWebService/rest/person"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString strin gWithFormat:#"user_email=%#&user_login=%#&user_pass=%#& last_upd_by=%#&user_registered=%#&",txtemail.text,txtuser1.text,txtpass1.text,txtuser1.text,datestr,nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
/* ViewController *view =[[ViewController alloc]initWithNibName:#"ViewController" bundle:NULL];
[self presentViewController:view animated:YES completion:nil];*/
}
else
{
NSLog(#"faield to connect");
}
Make life easy on yourself and use AFNetworking. Instructions for how to post form data are here: https://github.com/AFNetworking/AFNetworking
declared in .h file
NSString *extractUsersGRC;
.m file
{
..
extractUsersGRC=[[NSString alloc]init];
extractUsersGRC = [[resultsGRC objectForKey:#"d"] retain];
NSDictionary *dict1 =[[NSDictionary alloc]init];
dict1=[[extractUsersGRC JSONValue]retain];
}
I am using json to get data from web service and web service is ok
replaying my request, but some times I am getting dict1 as nil.
jsonvalue returns me null.So where i am making mistake.
extractUsersGRC holding data but Jsonvalue returns null..? why ? I am
not getting Help me.
SBJSON *jsonGRC = [SBJSON new];
jsonGRC.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"/GET_Recent_Activity";
NSString *flagval=#"C";
double latval=[[[NSUserDefaults standardUserDefaults]valueForKey:#"LATITUDE"]doubleValue];
double longval=[[[NSUserDefaults standardUserDefaults]valueForKey:#"LONGITUDE"]doubleValue];
NSString *userid=[[NSUserDefaults standardUserDefaults]valueForKey:#"UserID"];
long u_id= [userid longLongValue];
NSLog(#"%ld",u_id);
NSString *requestString = [NSString stringWithFormat:#"{\"flag\":\"%#\",\"current_Lat\":\"%f\",\"current_Long\":\"%f\",\"userid\":\"%ld\"}",flagval,latval,longval,u_id];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
fileContentsGRC = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
urlLocGRC = [fileContentsGRC objectForKey:#"URL"];
urlLocGRC = [urlLocGRC stringByAppendingString:service];
NSLog(#"URL : %#",urlLocGRC);
requestGRC = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLocGRC]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[requestGRC setHTTPMethod: #"POST"];
[requestGRC setValue:postLength forHTTPHeaderField:#"Content-Length"];
[requestGRC setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestGRC setHTTPBody: requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: requestGRC returningResponse: nil error: &respError ];
Declare #property (nonatomic, strong) NSMutableData *returnData; at .h file and
follow me
change your NSURLConnection declaration
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection)
self.returnData = [[NSMutableData alloc] init];
else
NSLog(#"Connection Failed!");
and delegate method of NSURLConnection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.returnData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.returnData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Network Error" message:#"Connection failed." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonString = [[NSString alloc] initWithData:self.returnData encoding:NSUTF8StringEncoding];
NSMutableDictionary *jsonDictionary = [jsonString JSONValue];
NSLog(#"%#", jsonDictionary);
}
I am using JSON to get data from web service.The problem is When i call web service and due to slow response my app become unresponsive for few seconds and some times crash.
I search a lot and found that by making Asynchronous call instead of Synchronous call can solve problem. But how to use asynchronous call that i don't know.
My code is like..
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"/Get_NearbyLocation_list";
double d1=[[[NSUserDefaults standardUserDefaults]valueForKey:#"LATITUDE"] doubleValue];
NSLog(#"%f",d1);
double d2=[[[NSUserDefaults standardUserDefaults]valueForKey:#"LONGITUDE"] doubleValue];
NSLog(#"%f",d2);
NSString *requestString = [NSString stringWithFormat:#"{\"current_Lat\":\"%f\",\"current_Long\":\"%f\"}",d1,d2];
NSLog(#"request string:%#",requestString);
// NSString *requestString = [NSString stringWithFormat:#"{\"GetAllEventsDetails\":\"%#\"}",service];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
// self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSError *respError = nil;
NSData *returnData= [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
if (respError)
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Internet connection is not Available!" message:#"Check your network connectivity" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
[alt release];
[customSpinner hide:YES];
[customSpinner show:NO];
}
else
{
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#" %#",responseString);
NSDictionary *results = [[responseString JSONValue] retain];
NSLog(#" %#",results);
thanks in advance..
NSData *returnData= [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
this line makes the call a synchronous one.
Use this
-(void)downloadWithNsurlconnection
{
//MAke your request here and to call it async use the code below
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse: (NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
//Here in recieved data is the output data call the parsing from here and go on
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
this is how u can send asynchronous url request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
//date received
else if ([data length] == 0 && error == nil)
//date empty
else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
//request timeout
else if (error != nil)
//error
}];
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.