JSON dealy response - ios

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

Related

How to call webService Using NSURLConnection in ios

Actually I am using now JSON classes for calling web-services but now i want to call that webservice using NSURLConnection any one provide me code for that.
Please provide me details of frameworks what i have to import.
Thank you in advance.
NSURL *url = [NSURL URLWithString:stringurl];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",dictionary);
}];
You Can use this.
You can Do like this using Synchronous :
NSURL *url=[NSURL URLWithString:urlString];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString *response=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dd=[response JSONValue];
OR Using Delegate Method
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSURLResponse *response = nil;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
#pragma mark NSURLConnection Delegate Methods
- (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 {
// Append the new data to the instance variable you declared
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];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
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
}
Use below code forrcalling SOAP web service (POST) :
-(NSString *)posturl:(NSString *)url withpoststring:(NSString *)postString {
NSString *post = postString;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *URL = url;
NSLog(#"%#", URL);
NSLog(#"%#",post);
[request setURL:[NSURL URLWithString: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 *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if ([data isEqualToString:#""]) {
} else {
data = stringByStrippingHTML(data);
}
return data;
}

How can I print the response from my simple, working POST method

I have a post method that looks like this:
NSString *totalPostURL = [NSString stringWithFormat:#"%#registerDevice",self.textUrl];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:totalPostURL]];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:self.finalDict options:0 error:&error];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
The code works fine but I have no idea how to print the response from this post. Any suggestions welcome as I'm new to iOS development.
You can print the response as below:
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString);
But Remember as you are a newbie,don't forget to read the tutorial for calling webservices.Interacting with webservices.
You get your response in the connection delegate. Look for the method
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
You can use like this...
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonString = [[NSString alloc] initWithString: receivedData];
NSData* cData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *WSerror;
NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:cData options:NSJSONReadingAllowFragments error:&WSerror];
}
Print the responseDic.
#Ayan Khan is right! here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.
//POST DATA
NSString *theBody = [NSString stringWithFormat:#"parameter=%#",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = #"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:#"%#/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:#"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(#"Trying to call ws %#",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Download Error:%#",error.description);
}
if (data) {
//
// THIS CODE IS FOR PRINTING THE RESPONSE
//
NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString);
//PARSE JSON RESPONSE
NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
if ( json_response ) {
if ( [json_response isKindOfClass:[NSDictionary class]] ) {
// do dictionary things
for ( NSString *key in [json_response allKeys] ) {
NSLog(#"%#: %#", key, json_response[key]);
}
}
else if ( [json_response isKindOfClass:[NSArray class]] ) {
NSLog(#"%#",json_response);
}
}
else {
NSLog(#"Error serializing JSON: %#", error);
NSLog(#"RAW RESPONSE: %#",data);
NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString2);
}
}
}];
Hope this helps!

Connecting to a JSON API in iOS that requires a user name and password

I have a URL that when typed into a browser (EG Safari) requests a username and password, the response API comes back in the form of JSON.
Now I'm trying to connect to this API in my iOS app so I can work with the JSON data and I'm not sure if I'm going about it the correct way.
NSString *post = [NSString stringWithFormat:#"&Username=%#&Password=%#",#"username",#"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSString *string = [NSString stringWithFormat:#"jsonURL"];
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(connection)
{
NSLog(#"connection success");
}
else
{
NSLog(#"connection could not be made");
}
The NSLog is coming back with a "connection success" response. However, I can't seem to load the JSON response into an NSDictionary or NSArray. I've used NSJSONSerialization here.
NSMutableData *urlData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
NSLog(#"DID RECEIVE RESPONSE %#", urlData);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
[urlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"FINISHED LOADING DATA %#", connection);
NSError *jsonParsingError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
if (jsonParsingError) {
NSLog(#"JSON ERROR: %#", [jsonParsingError localizedDescription]);
} else {
NSLog(#"Parsed Object is %#", parsedObject);
}
}
And here is my JSON error from the NSLog: "JSON ERROR: The operation couldn’t be completed. (Cocoa error 3840.)"
Where am I going wrong? Thanks in advance.
NSString *jsonstring = [NSString stringWithFormat:#"{\"userName\":\"%#\",\"password\":\"%#\",\"loginFrom\":\"2\",\"loginIp\":\"%#\"}",[username_text removequotes],[password_text removequotes],ipaddress];//The removeQuotes method is used to escape sequence the " to \" so that the json structure won't break. If the user give " in the username or password field and if we dint handle that the json structure will break and may give an expection.
NSLog(#"the json string we are sending is %#",jsonstring);
NSData *strdata = [json1 dataUsingEncoding:NSUTF8StringEncoding];
NSString *fixedURL =[NSString stringWithFormat:#"%#",loginURL];//the url is saved in loginURL variable.
NSURL *url = [NSURL URLWithString:fixedURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: strdata];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
NSLog(#"Connected to service waiting for response");
}
Example code for login using json web services
Finally resolved this. Use:
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSLog(#"received authentication challenge");
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:#"username"
password:#"password"
persistence:NSURLCredentialPersistenceForSession];
NSLog(#"credential created");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
NSLog(#"responded to authentication challenge");
}
else {
NSLog(#"previous authentication failure");
}
}
You actually don't need to set request values (e.g.: [request setValue:postLength forHTTPHeaderField:#"Content-Length"];) etc etc
Connect with a:
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
and handle the JSON response data with:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
NSLog(#"DID RECEIVE RESPONSE");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSLog(#"THE RAW DATA IS %#", data);
[urlData appendData:data];
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"LOGGING THE DATA STRING %#", strRes);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"FINISHED LOADING DATA %#", connection);
NSError *jsonParsingError = nil;
//id object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
NSArray *parsedObject = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
NSLog(#"RESPONSE: %#",[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]);
if (jsonParsingError) {
NSLog(#"JSON ERROR: %#", [jsonParsingError localizedDescription]);
} else {
NSLog(#"PARSED OBJECT %#", parsedObject);
}
}
I suggest use AFNetworking whenever deal with networking.
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:username
password:password];

jsonParser objectWithString returns null value

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

JSON POST is not working in iOs

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

Resources