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