Hi I am facing problem in conversion of NSData to NSDictionary using NSJSONSerialization?
I got data using my code but unable to convert it into json.
Here is my code...
ViewController.h File
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<NSURLConnectionDelegate>
{
NSString *massage;
NSURL *url;
NSMutableURLRequest *request;
NSURLConnection *connection;
NSMutableData *httpbody;
NSMutableData *webData;
NSData *responceData;
NSDictionary *responceJson;
}
and ViewController.m File
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *mobile = #"123456789";
NSString *password = #"Welcome123";
NSString *deviceId = #"123sdfg15641ert321ret";
url = [NSURL URLWithString:#"http://203.109.87.34:8585/d-cab/web/app_dev.php/api/v1"];
massage = [NSString stringWithFormat:#"{\"action\":\"login\",\"data\":{\"contact\":\"%#\",\"password\":\"%#\",\"deviceId\":\"%#\"}}",mobile,password,deviceId];
//NSLog(#"Body = %#", massage);
httpbody = [ NSMutableData dataWithBytes: [ massage UTF8String ] length: [ massage length ] ];
request = [NSMutableURLRequest requestWithURL: url];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: httpbody];
[request setTimeoutInterval:10.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//[connection start];
if (connection) {
webData = [[NSMutableData alloc]init];
}
}
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[webData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
//NSLog(#"WebData = %#",webData);
//NSLog(#"=================================");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError* error = nil;
responceJson = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:&error];
NSLog(#"ResponceJSON = %#",responceJson);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Show error message
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error In connection" message:#"We are facing some problem in connection. Please Check your Internet Connection." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Please Check my code and tell me where and what change I have to make?
Hey Thanks to all who gave attention to my question.... But I found the problem in my question.
I am trying to send the parameter into string format instead of dictionary format and not specifying header to request. Here is my updated code...
NSDictionary *paramData = [[NSDictionary alloc]initWithObjectsAndKeys:mobile,#"contact",password,#"password",deviceId,#"deviceId", nil];
//NSLog(#"paramData = %#",paramData);
jsonParam = [[NSDictionary alloc]initWithObjectsAndKeys:#"login",#"action",paramData,#"data", nil];
//NSLog(#"jsonParam = %#",jsonParam);
httpbody = [NSJSONSerialization dataWithJSONObject:jsonParam options:0 error:nil];
request = [NSMutableURLRequest requestWithURL: url];
request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [httpbody length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: httpbody];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
webData = [[NSMutableData alloc]init];
}
It worked for me....
Try using the following code :
responceJson = [NSJSONSerialization JSONObjectWithData:webData
options:NSJSONReadingMutableContainers
error:&error];
Well the problem here is not in conversion problem is in this funtion
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//[webData setLength:0];
webdData = [[NSMutableData alloc] init];
}
It will help.Thanks
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection )
{
mdata = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
mdata.length=0;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mdata appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Data store in dictionary when connection proceed in background
dict=[NSJSONSerialization JSONObjectWithData:mdata options:kNilOptions error:nil];
NSLog(#"%#",dict);
}
This is working gooood...
Try to check, what your connection is load. Converting NSData to NSString. In didFinishLoading typing this:
NSString *tempString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"loaded data: %#",tempString);
Related
Little issue that's been bothering me. I've been making a POST request to my AWS RDB. The request should return a json output. The issue I'm having is that I'll receive bytes back, but sometimes it contains incomplete json, thus converting it to a dictionary won't work. Sometimes I also receive a null value for the nsdata received, but I can print out the length of the data. Any ideas? Here's my iOS code for requests:
#import "ServiceConnector.h"
#implementation ServiceConnector{
NSMutableData *receivedData;
}
-(void)getTest{
//Send to server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_WEBSITE"]];
[request setHTTPMethod:#"GET"];
//initialize an NSURLConnection with the request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection){
NSLog(#"Connection Failed");
}
}
-(void)postTest:(NSMutableArray *)carSearches{
//build up the request that is to be sent to the server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_WEBSITE"]];
[request setHTTPMethod:#"POST"];
NSError *writeError = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:carSearches options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON Output: %#", jsonString);
[request setHTTPBody:data]; //set the data as the post body
[request addValue:[NSString stringWithFormat:#"%lu",(unsigned long)data.length] forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection){
NSLog(#"Connection Failed");
}
}
#pragma mark - Data connection delegate -
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // executed when the connection receives data
if(!receivedData){
receivedData = [[NSMutableData alloc]init];
[receivedData appendData:data];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ //executed when the connection fails
NSLog(#"Connection failed with error: %#",error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"Request Complete,recieved %lu bytes of data",(unsigned long)receivedData.length);
NSString *tmp = [NSString stringWithUTF8String:[receivedData bytes]];
NSLog(#"%#",tmp);
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[receivedData bytes] length:[receivedData length]] options:NSJSONReadingAllowFragments error:&error];
[self.delegate requestReturnedData:dictionary];
}
In this section:
if(!receivedData){
receivedData = [[NSMutableData alloc]init];
[receivedData appendData:data];
}
You are only appending data if the object hasn't been created yet. You want to append every time. That if statement should read like this:
if(!receivedData){
receivedData = [[NSMutableData alloc]init];
}
[receivedData appendData:data];
I am trying to send multiple parameter for a registration usage. Here is my Code for Posting data :
-(void)PostRegistrationData:(NSString *)userEmail :(NSString *)Password{
NSDictionary *params = #{
#"username":#"something",
#"password":#"aFilter",
#"email":#"aCategory",
#"type":#"aCategory",
#"request_type":#"aCategory"
};
/* We iterate the dictionary now
and append each pair to an array
formatted like <KEY>=<VALUE> */
NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params) {
[pairs addObject:[NSString stringWithFormat:#"%#=%#", key, params[key]]];
}
/* We finally join the pairs of our array
using the '&' */
NSString *requestParams = [pairs componentsJoinedByString:#"&"];
NSData *postData = [requestParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://teknofolk.com/spisrett_admin/slave/signup.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;
NSMutableData *mutableData = [[NSMutableData alloc]init];
}
}
But no data i getting inserted . Am i missing something?
You have various choices what you want to use.
First option:
NSURLResponse *res = nil;
NSError *err = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&err];
(you have also the async way for this option).
or you can also follow your code and continue with this:
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
and the request will be async and will call this methods (you need that this view controller responds to the NSURLConnectionDelegate and NSURLConnectionDataDelegate):
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse
*)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
It was my mistake in the parameter.
NSDictionary *params = #{
#"username":#"something",
#"password":#"aFilter",
#"email":#"aCategory",
#"type":#"aCategory",
#"request_type":#"aCategory"
};
Worked with simply this :
#"type":#"1",
#"request_type":#"2"
};
In my insertion i was passing wrong value on type and request type. Thanks to all for all
I am sending a request to server using NSURLConnection, it worked for 2 times , since third time it is not working, delegates are not being called. What i found during debugging is connectionShouldUseCredentialStorage method is called for initial times, third time it was not called and rest of methods are also not called.
Here is my code:
NSString *requestString = [NSString stringWithFormat:#"%#", [serviceParameters JSONFragment], nil];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: strUrl]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:requestData];
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
[self.data appendData:aData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
SBJSON *jsonParser = [[SBJSON new] autorelease];
NSString *jsonString = [[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding] autorelease];
NSError *outError = nil;
id result = [jsonParser objectWithString:jsonString error:&outError];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
if( [[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust] )
{
return YES;
}
return NO;
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
return YES;
}
in .h
NSMutableData * data;
NSURLConnection *connection;
Also add Add
in .m
-(void) startConnection
{
NSString *requestString = [NSString stringWithFormat:#"http://md5.jsontest.com/?text=Pushkraj"];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
data = [NSMutableData dataWithCapacity:0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:requestData];
connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
[data appendData:aData];
NSDictionary * dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"dataDict : %#",dataDict);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error : %#",error);
}
Call [self startConnection]; wherever you want means on viewDidLoad or on UIButton Click
You forgot to start connection. You are not saving the reference to NSURLConnection for starting the connection. So replace last line
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
with this
NSURLConnection *cn =[NSURLConnection connectionWithRequest:urlRequest delegate:self];
[cn start];
Hope it helps.
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);
}