how to post uitextfield data in web service on unbutton - ios

i have login screen for company registration, i want to post all uitextfield data on web service on button clicked .
this is my code for button clicked
- (IBAction)Register:(id)sender {
if (_CompanyName.text.length <=0)
{
NSLog(#"enter company name");
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Enter Company Name"
message:nil
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Continue", nil];
[message setAlertViewStyle:UIAlertViewStyleDefault];
[message show];
}
I am beginners in that type of activity so,if anyone have knowledge then please help,thanks.

Very simple posting data to server coding is below
- (IBAction)actionRegister:(id)sender
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:strYourURL]];
[request setHTTPMethod:#"POST"];
//Check The Value what we entered in textField
NSLog(#"the company name is:%#",txtFieldCompanyName.text);
NSLog(#"the email is:%#",txtFieldEmail.text);
NSLog(#"the password is:%#",txtFieldPassword.text);
NSLog(#"the password again is:%#",txtFieldPasswordAgain.text);
//Pass The String to server
NSString *strParameters =[NSString stringWithFormat:#"comapny_name=%#&email=%#&password=%#&password_again=%#",txtFieldCompanyName.text,txtFieldEmail.text,txtFieldPassword.text,txtFieldPasswordAgain.text,nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", strParameters);
//Convert the String to Data
NSData *data1 = [strParameters 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");
}
else
{
NSLog(#"faield to connect");
}
}

Use AFNetworking class Here is a link
https://github.com/AFNetworking/AFNetworking
http://www.raywenderlich.com/59255/afnetworking-2-0-tutorial
And some peace of code you will get from this tutorial like
- (IBAction)registerButtonTapped:(id)sender
{
// 1
NSString *string = [NSString stringWithFormat:#"www.yourwebapiurl.php?format=json&username=%#", userNameTextField.text];//and so on
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
NSDictionary *responseDict = (NSDictionary *)responseObject;
NSLog(#"You have got the response ");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
It will Help.Thanks

Related

iOS objective c retrieving data from server NSUrl not able to access to global variable

hi I am new to iOS and I am giving request to server and getting top to the mobile number and through request reply I am able to get the otp but when I print the data out of the seesion which is initialised inside block I am getting null
this is my .h file
#import <UIKit/UIKit.h>.
#interface OtpViewController : UIViewController
#property (nonatomic,strong) NSString *str;
#property (strong,nonatomic) NSString *tmp;
#property(weak,nonatomic) NSString *requestReply ;
#end
this is my url request block in .m file
- (IBAction)submitb:(id)sender
{
if (_mobiletf.text && _mobiletf.text.length >0 )
{
/* not empty - do something */
NSString *post = [NSString stringWithFormat:#"phone=%#",_mobiletf.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Next up, we read the postData's length, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.sitesandflats.com/send_otp.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSLog(#"the data Details is %#", post);
// And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSLog(#"requestReply: %#", jsonDict);
self.tmp=[jsonDict valueForKey:#"otp"] ;
self.str=self.tmp;
NSLog(#"tmp storage inside block:%#",self.tmp);
[self performSelector:#selector(updateStatus) withObject:nil afterDelay:1.0];
// NSLog(#"requestReply: %#", jsonDict);
//self.tmp=[jsonDict valueForKey:#"otp"] ;
//self.str=self.tmp;
//NSLog(#"tmp storage inside block:%#",self.tmp);
}] resume];
//self.str=self.tmp;
NSLog(#" storage:%#",self.str);
NSLog(#"tmp storage:%#",self.tmp);
[ self performSegueWithIdentifier:#"b1" sender:self];
}
else
{
/* what ever */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please check your input!!."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)updateStatus{
NSLog(#" storage:%#",self.str);
NSLog(#"tmp storage:%#",self.tmp);
// [ self performSegueWithIdentifier:#"b1" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender
{
VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
loadCtr.otpStr =self.tmp;
loadCtr.mobileStr = _mobiletf.text;
}
this is my print log
2017-06-01 12:44:08.813 MenuBar[2750:135123] the data Details is phone=9047038606
2017-06-01 12:44:08.829 MenuBar[2750:135123] 9047038606
2017-06-01 12:44:08.835 MenuBar[2750:135123] storage:(null)
2017-06-01 12:44:08.836 MenuBar[2750:135123] tmp storage:(null)
2017-06-01 12:44:10.122 MenuBar[2750:135162] requestReply: {
otp = 552749;
success = 1;
}
2017-06-01 12:44:10.122 MenuBar[2750:135162] tmp storage inside block:552749
block is the additional thread , so you need to wait for completion block, so change your code like below
if you want to acces the data in outside
- (IBAction)submitb:(id)sender
{
if (_mobiletf.text && _mobiletf.text.length >0 )
{
/* not empty - do something */
NSString *post = [NSString stringWithFormat:#"phone=%#",_mobiletf.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Next up, we read the postData's length, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.sitesandflats.com/send_otp.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSLog(#"the data Details is %#", post);
// And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSLog(#"requestReply: %#", jsonDict);
self.tmp=[jsonDict valueForKey:#"otp"] ;
self.str=self.tmp;
NSLog(#"tmp storage inside block:%#",self.tmp);
[self updateStatus];
}] resume];
}
else
{
/* what ever */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please check your input!!."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)updateStatus{
NSLog(#" storage:%#",self.str);
NSLog(#"tmp storage:%#",self.tmp);
dispatch_async(dispatch_get_main_queue(), ^{
[ self performSegueWithIdentifier:#"b1" sender:self];
});
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender
{
VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
loadCtr.otpStr =self.tmp;
loadCtr.mobileStr = _mobiletf.text;
}

ASIFormDataRequest post method is not working in ios

Hi i am beginner in Ios and in my project there is facility for users "ForGotPassword" request
For this i have written some code but that is not working
i.e is objectFromJSONString response shows like -->Message: "No HTTP resource was found that matches the request URI "my url."
what did i do here wrong ,is it my problem or server side problem? please help me
my code:-
- (IBAction)submitBtnClicked:(id)sender {
NSLog(#"password ---->>> %#",self.MedicalIdTxt.text);
NSString *urlStr = [NSString stringWithFormat:#"my url"];
NSLog(#"urlStr --->>> %#",urlStr);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setRequestMethod:#"POST"];
[request setPostValue:self.MedicalIdTxt.text forKey:#"MedicaidId"];
[request setDelegate:self];
[request startAsynchronous];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
- (void)requestFinished:(ASIHTTPRequest *)request {
NSLog(#"requestFinished");
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSLog(#"%#",request);
NSString *receivedString = [request responseString];
NSLog(#"receivedString %#",receivedString);
NSDictionary * jsonObj=[[NSDictionary alloc]init];
jsonObj = [receivedString objectFromJSONString];
NSLog(#"jsonObj result is%#",jsonObj);
NSString *messageStr = [jsonObj objectForKey:#"message"];
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"" message:messageStr delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSString *receivedString = [request responseString];
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:receivedString message:#"" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
here "jsonObj" not showing response which is coming from services what did i do here wrong?
ASIHTTPRequest is not under maintenance since so long, so use AFNetworking instead:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"your url"
parameters:#{#"color": #"green"}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Basic Authentication with AFNetworking

I am trying to call URL and get back to json object. However, I could not able to find out where to put basic authentication in AFNetworking operation. I could able to get my JSON object using the POSTMAN as follows.
Codesnippet of AFNetworking operation:
NSString *string = #"MYURL";
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
int total_count = (int)[[responseObject valueForKey:#"total_count"] integerValue];
if (total_count > 0) {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:total_count];
for (int i = 1; i <= total_count; i++) {
NSString *key = [NSString stringWithFormat:#"%i", i];
id object = [responseObject objectForKey:key];
[array addObject:object];
}
menuArray=array;
tableData = [NSArray arrayWithArray:array];
[categoryTableView reloadData];
}
else
{
NSLog(#"There is no internet connection!");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"There is no internet connection!"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
Here is the POSTMAN, Calling URL with Basic Authorization
You need to put your authentication to headers. You can do it in this way:
//creating crequest
NSURL *url = [NSURL URLWithString:YOUR_URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//Encode username and password
NSData *plainData = [[NSString stringWithFormat:#"%#:%#", username, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *encodedUsernameAndPassword = [plainData base64EncodedStringWithOptions:0];
//set auth header
[request addValue:[NSString stringWithFormat:#"Basic %#", encodedUsernameAndPassword] forHTTPHeaderField:#"Authorization"];
// your AFNetworking code

AFNetworking 2 - get UIImage from NSString

I got the following input XML:
<Company>
<Id>1</Id>
<IndustryId>1</IndustryId>
<IndustriesID>
<int>1</int>
<int>2</int>
<int>3</int>
</IndustriesID>
<Name>ClasOhlson</Name>
<Icon>iVBORw0KGgoAAAANSUhEUgAAAKMAAAByCAYAAAA/DmEKAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AABdDklEQVR4Xu2dB5hURfb2W0GCRPOuuua0hjUnzIoYwQSIKEFEgkgUJCg
How can I get UIImage from <Icon> tag? I am using AFNetworking 2.0. My code:
NSString *str = [NSString stringWithFormat:#"%#/GetAllCompanies", FPHostAddress];
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
// Make sure to set the responseSerializer correctly
operation.responseSerializer = [AFXMLParserResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSXMLParser *XMLParser = (NSXMLParser *)responseObject;
[XMLParser setShouldProcessNamespaces:YES];
id parser = [CompaniesXMLParser new];
XMLParser.delegate = parser;
BOOL isParseSuccessful = [XMLParser parse];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Download failed. Error: \n%#", error.localizedDescription);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
[operation start];
If you are creating an application target to iOS 7 and above you should do this after get the string from parsed xml:
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];
UIImage* icon = [UIImage imageWithData: data];
Otherwise, if the base iOS version of your app is something before iOS 7.0, you should download the files with category implementation from here:
http://www.cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
And do this:
NSData *data = [NSData dataFromBase64String:base64Encoded];
UIImage* icon = [UIImage imageWithData: data];
Where base64Encoded is what you read from Icon tag.

AFNetworking POST cannot return json data

I want to make a request with POST method and after that I want them to return the json data or NSDictionary, but they can only return the string when it succeed
Like NSString *response = [operation responseString];
Anyone know how to make them return NSdictionary instead of NSString?
-(IBAction)SubmitLogin:(id)sender{
NSLog(#"Login");
// NSLog(#"%#",username);
//START FUNGSI UNTUK POST, PUT, DELETE
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:signinUrl];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"someuser", #"username",
#"somepassword",#"password",
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#""
parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation,
id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: %#",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
}];
//call start on your request operation
[operation start];
I was trying to send JSON object and getting back JSON data and parse it
NSURL *url = [NSURL URLWithString:#"https://MySite.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
//[httpClient setParameterEncoding:AFJSONParameterEncoding];
//[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
#"Ans", #"name",
#"29", #"age", nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"/testJSONReturn.php"
parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"DATA: %#", [JSON valueForKeyPath:#"data"]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failure Because %#",[error userInfo]);
}];
[operation start];
Might help
This is what I use, feel free to fit it to your needs:
-(void) loginWithUserID:(NSString*)usrID User:(NSString*)usr Password:(NSString *)psw Sender:(id)sender
{
if ([sender respondsToSelector:#selector(startLoading)]){
[sender performSelector:#selector(startLoading)];
}
baseURL = [NSString stringWithFormat:
#"http://xxx.xxx.xxx.xxx/test/service.svc/weblogin"];
NSString* serviceURL = [NSString stringWithFormat:
#"%#?userID=%#&user=%#&password=%#",baseURL,usrID,usr,psw;
NSURL *url = [NSURL URLWithString:[serviceURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.LoginOK = [JSON valueForKeyPath:#"LoginOK"];
if (LoginOK.intValue == 1) {
NSDictionary *usrData = [JSON valueForKeyPath:#"userData"];
userData = [[UserData alloc]init];
[userData readFromJSONDictionary:usrData];
NSLog(#"Userdata: %#",userData);
if ([sender respondsToSelector:#selector(loginSuccessful:)])
{
[sender performSelector:#selector(loginSuccessful:)];
}
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"No Correct Login Credentials" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
;}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
if ([sender respondsToSelector:#selector(stopLoading)]){
[sender performSelector:#selector(stopLoading)];
}
[[[UIAlertView alloc] initWithTitle:#"Error"
message:#"Loginservice not available! Check your connection!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil] show];
NSLog(#"Error: %#", error);
}];
[operation start];
};
EDIT: Oh and use a
-(void)readFromJSONDictionary:(NSDictionary *)d
{
[self setProperty1:[d objectForKey:#"property1"]];
}
method to get all the properties out of that dictionary into a custom class.

Resources