how to send user name and password using post to server in iphone app - iphone

I am making a lo-gin app i want to send the username and password to server for validation how to do this i have done in many ways but i am unable to post.
I am posting the username and password but it did not work if i direct give username and password to php it works so how to do this in iphone to send through post
NSString *post = [[NSString alloc] initWithFormat:#"UserName=%#&Password=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://www.celeritas-solutions.com/emrapp/connect.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"Inside the else condition");
}
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;

//Edited your code try this may help you.
NSString *post = [[NSString alloc] initWithFormat:#"UserName=%#&Password=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://www.celeritas-solutions.com/emrapp/connect.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];

//when the user clicks login<action>
- (IBAction)signinClicked:(id)sender {
NSInteger success = 0;
#try {
//to check if username and password feild are filled
if([[self.txtUsername text] isEqualToString:#""] || [[self.txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter Username and Password" :#"Sign in Failed!" :0];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[self.txtUsername text],[self.txtPassword text]];
NSLog(#"PostData: %#",post);
//post it to your url where your php file is saved for login
NSURL *url=[NSURL URLWithString:#"http://xyz.rohandevelopment.com/new.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
success = [jsonData[#"success"] integerValue];
NSLog(#"Success: %ld",(long)success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
} else {
//if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Please Check Your Connection" :#"Sign in Failed!" :0];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Sign in Failed." :#"Error!" :0];
}
if (success) {
[self performSegueWithIdentifier:#"login_success" sender:self];
}
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}

Add Following Code After
[theRequest setHTTPBody:postData];
NSURLResponse *response;// = [[NSURLResponse alloc] init];
NSError *error;// = [[NSError alloc] init;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Login response: is %#",str);

Related

Multiple form data get

I have registration page for multiple users. When user register it will stores to database in multiple form data with username and password. Then i'm getting in viewcontroller with login page. When i use username=abcd&password=123 it working. But when i use username=%#&password=%# for multiple users it's not working.
code:
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[usrname text],[password text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://myserver.net/projects/mobile/test_login.php?name=abcd&password=123"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response code: %d", [response statusCode]);
if ([responseData length]){
NSLog(#"Response ==> %#", responseData);
NSMutableDictionary *dict=[responseData JSONValue];
NSInteger success = [(NSNumber *) [dict objectForKey:#"success"] integerValue];
NSLog(#"%d",success);
if(success == 1){
//save the ID
NSInteger id1 = [(NSNumber *) [dict objectForKey:#"id"] integerValue];
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setInteger:id1 forKey:#"id"];
[userData synchronize];
NSLog(#"id1 data is %#",userData);
NSLog(#"Login SUCCESS");
[self alertStatus:#"Logged in Successfully." :#"Login Success!"];
[self.navigationController pushViewController:overlay animated:YES];
} else {
NSString *error_msg = (NSString *) [dict objectForKey:#"error_message"];
[self alertStatus:error_msg :#"Login Failed!"];
}
}
you should try it this way
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://myserver.net/projects/mobile/test_login.php?name=%#&password=%#",[usrname text],[password text]]];
hope it helps you thanks. :)

using HTTP Post method how to make login page in iphone

I'm have created a Login view. Everytime I login it gives me login Success message will be displayed. even if I enter wrong username and password.I am created login page static.The menctioned link is sample web services link. This is the method I'm using right now:Please give me any idea.Thanks in advance.
loginPage.m
-
(IBAction)login:(id)sender
{
NSString *post = [NSString stringWithFormat:#"&Username=%#&Password=%#",#"username",#"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"HTTP://URL"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (conn)
{
NSLog(#"connection successful");
}
else
{
NSLog(#"Failed");
}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
// NSURL *theURL=[response URL];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
if(receivedData)
{
NSLog(#"success",[receivedData length]);
}
else
{
NSLog(#"Success",[receivedData length]);
}
}
NSString *string= [NSString stringWithFormat:#"your Url.php?&Username=%#&Password=%#",username,password];
NSLog(#"%#",string);
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"responseData: %#", str);
NSString *str1 = #"1";
if ([str isEqualToString:str1 ])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Successfully" message:#"" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Try Again" message:#"" delegate:self cancelButtonTitle:#"Try Later" otherButtonTitles:#"Call", nil];
alert.tag = 1;
[alert show];
}
Don't need to use JSON you can do this without JSON in a esay way!!!
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
- (IBAction)loginClicked:(id)sender {
#try {
if([[txtUserName text] isEqualToString:#""] || [[txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Пожалуйста заполните все поля!!!" :#"Авторизация не удолась!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"login=%#&pass=%#",[txtUserName text],[txtPassword text]];
NSURL *url=[NSURL URLWithString:#"http:xxxxxxxx.xxx/?"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSData *responseData = [[NSData alloc]initWithData:urlData];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
if([jsonObject objectForKey:#"error"])
{
[self alertStatus:#"" :#""];
} else {
[self alertStatus:#"" :#""];
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!"];
}
[txtUserName resignFirstResponder];
[txtPassword resignFirstResponder];
}
Try below code.
-(void)webservice_Call
{
NSString *urlString=#"http://api.openweathermap.org/data/2.1/find/city?lat=10.369&lon=122.5896";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSDictionary *resDictionary = [NSJSONSerialization JSONObjectWithData:response1 options:NSJSONReadingMutableContainers error:Nil];
}
Post Method for iOS 9 Version
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
   
[post setValue:#“25” forKey:#"user_id"];
NSArray* notifications = [NSArray arrayWithObjects:post, nil];
       
NSError *writeError = nil;
       
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
       
NSString *postLength = [NSString stringWithFormat:#"%d",[jsonData length]];
       
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
      
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://your/url]]];
      
[request setHTTPMethod:#"POST"];
      
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
      
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
      
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
      
[request setHTTPBody:jsonData];
      
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
 
// Create a data task object to perform the data downloading.
    
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
 
    data = [[NSData alloc]initWithData:urlData];
    NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}];
      
[task resume];
-(void)apiCode
{
NSString *string= [NSString stringWithFormat:#"http:url...project_id=1&user_id=58&question=%#&send_enquiry=%#",self.txtTitle.text,self.txtQuestion.text];
NSLog(#"%#",string);
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"responseData: %#", str);
NSString *str1 = #"success";
if ([str isEqualToString:str1 ])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Successfully" message:#"" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Try Again" message:#"" delegate:self cancelButtonTitle:#"Try Later" otherButtonTitles:#"Call", nil];
alert.tag = 1;
[alert show];
}
}

NSURL passing with one argument

NSString *myString = #"1994";
NSString *post =[[NSString alloc] initWithFormat:#"data=%#",myString];
NSURL *url=[NSURL URLWithString:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastid2.php/?data=%#",myString];
NSLog(#"URL%#",url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSLog(#"postDATA%#",postData);
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"postLENGTH%#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error1 = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error1];
NSString *string;
if ([response statusCode] >=200 && [response statusCode] <300)
{
string = [[NSString alloc] initWithData:urlData encoding:NSMacOSRomanStringEncoding];
UIAlertView *alert1=[[UIAlertView alloc]initWithTitle:#"alert1" message:string delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert1 show];
}
I am new to objective c. When I am sending NSURL with an argument it is give error as "Too many arguments expects 1 have 2 "How do I change my url with one argument?
Replace
NSURL *url=[NSURL URLWithString:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastid2.php/?data=%#",myString];
with
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastid2.php/?data=%#",myString]];
I have corrected few things and tested your code, it should be fine now:
NSString *myString = #"1994";
NSString *post =[[NSString alloc] initWithFormat:#"data=%#",myString];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://nyxmyx.com/Kinkey/KinkeyPHP/lastid2.php/?data=%#",myString]];
NSLog(#"URL%#",url);
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSLog(#"postDATA%#",postData);
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"postLENGTH%#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error1 = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error1];
NSString *string;
if ([response statusCode] >=200 && [response statusCode] <300)
{
string = [[NSString alloc] initWithData:urlData encoding:NSMacOSRomanStringEncoding];
UIAlertView *alert1=[[UIAlertView alloc]initWithTitle:#"alert1" message:string delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert1 show];
}
Response from above call:
1995,prabu,1231231233,antab,8080808080,1360738531881.jpg,No1996,prabu,1231231233,antab,8080808080,1361013972284.jpg,No1997,prabu,1231231233,antab,8080808080,1360844505212.jpg,No1998,josh,0417697070,null,+61420224346,1361160944442.jpg,No1999,josh,0417697070,null,+61420224346,1356047464383.jpg,No2000,josh,0417697070,null,+61420224346,1361160816141.jpg,No2001,wooza,0420224346,J Wratt ,+61417697070,2013-55-1803-55-54.jpg,No2002,wooza,0420224346,J Wratt ,+61417697070,2013-56-1803-56-17.jpg,No2003,testing,9894698946,ggh hjj,9894598945,2013-11-1811-11-40.jpg,Yes

URL Decoding of json in ios

I am having 1 webservice in php which is having browser url mentioned bel :
http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01 01:00:00
Now when I try to fetch url in my iphone app, it is taking this url:
http://Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00
This is creating problem.
i have used this code for fetching data from my url.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"";
NSString *str;
str = #"LastUpdated";
NSString *requestString = [NSString stringWithFormat:#"{\"LastUpdated\":\"%#\"}",str];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
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];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ACTEC"
message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
......
}
here,i am getting null response as url is getting decoded...How can I make this solved...
Help me out.
Thanks in advance.
NSString *urlLoc = [[fileContents objectForKey:#"URL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postData = [NSMutableData data];
NSMutableURLRequest *urlRequest;
[postData appendData: [[NSString stringWithFormat: #"add your data which you want to send"] dataUsingEncoding: NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:urlLoc]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSString *temp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"\n\nurl =%# \n posted data =>%#",urlLoc, temp);
check nslog. that which data u send to service.
NSData *response = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"json_string >> %#",json_string);
Maybe this will help you.
hey dear just for an another example i just post my this code..
first Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
    [NSURL URLWithString:#"http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00"]];
Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request
    returningResponse:nil error:nil];
Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc]
    initWithData:response encoding:NSUTF8StringEncoding];
Parse the JSON response into an object Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil]
And in statuses array you have all the data you need.
i hope this help you...
:)

How to send a Get request in iOS?

I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as
[requestObject setHTTPMethod:#"GET"];
Tell me what could be the problem. Also provide me the code if you have.
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response1 =
[NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSString *getString = [NSString stringWithFormat:#"parameter=%#",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:#"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https:yoururl"]];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
Make sure your requestObject is of type NSMutableURLRequest.
Simply call and use:
(void)jsonFetch{
NSURL *url = [NSURL URLWithString:#"http://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *data = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSError *erro = nil;
if (data!=nil) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro ];
if (json.count > 0) {
for(int i = 0; i<10 ; i++){
[arr addObject:[[[json[#"feed"][#"entry"] objectAtIndex:i]valueForKeyPath:#"im:image"] objectAtIndex:0][#"label"]];
}
}
}
dispatch_sync(dispatch_get_main_queue(),^{
[table reloadData];
});
}];
[data resume];
}