In my app am using UITextField in the login screen. To get the login details I connect the app to server through API. While calling the api I display an activity UIActivityIndicatorView. Before calling the api I do end editing. once the response is received from server again the keyboard is pop up when the activity indicator stops
Here is my Code
[self.view endEditing:YES];
VW_overlay.hidden = NO;
[activityIndicatorView startAnimating];
[self performSelector:#selector(API_Login) withObject:activityIndicatorView afterDelay:0.01];
and the API_Login Method have the following code
-(void) API_Login
{
NSString *userEmail = _TXT_email.text;
NSString *userPWD = _TXT_password.text;
NSError *error;
NSHTTPURLResponse *response = nil;
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",userEmail,userPWD];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSString *urlGetuser =[NSString stringWithFormat:#"%#loginApi",SERVER_URL];
NSURL *urlProducts=[NSURL URLWithString:urlGetuser];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:urlProducts];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setHTTPShouldHandleCookies:NO];
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (aData)
{
NSMutableDictionary *json_DATA = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:aData options:NSASCIIStringEncoding error:&error];
NSLog(#"The response %#",json_DATA);
if ([[json_DATA valueForKey:#"status"]isEqualToString:#"success"]) {
[[NSUserDefaults standardUserDefaults] setValue:[json_DATA valueForKey:#"driver_id"] forKey:#"driver_id"];
[[NSUserDefaults standardUserDefaults] synchronize];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[json_DATA valueForKey:#"status"] message:[json_DATA valueForKey:#"msg"] delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
[activityIndicatorView stopAnimating];
VW_overlay.hidden = YES;
[self performSelector:#selector(stop_activity) withObject:nil afterDelay:1.0];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[json_DATA valueForKey:#"status"] message:[json_DATA valueForKey:#"msg"] delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
}
}
else
{
[activityIndicatorView stopAnimating];
VW_overlay.hidden = YES;
NSLog(#"Error %#\nResponse %#",error,response);
}
}
-(void) stop_activity
{
[self order_details_page];
}
-(void)order_details_page
{
[self performSegueWithIdentifier:#"login_order" sender:self];
}
Related
I'm trying to build and login and logout application, but not able to login please help me to set default user id and password through which i would be able go to the next page
You can try this code it will help you :
-(void)login
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://www.example.com/pm/api/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=admin&password=123456&api_key=bf45c093e542f057c123ae7d6"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
if(checkBoxSelected == YES)
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* textField1Text = usernameField.text;
[defaults setObject:textField1Text forKey:#"textField1Text"];
NSString *textField2Text = passwordField.text;
[defaults setObject:textField2Text forKey:#"textField2Text"];
[defaults synchronize];
}
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:#"user_id"] forKey:#"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:#"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
ItemManagement *i = [[ItemManagement alloc]init];
[self.navigationController pushViewController:i animated:YES];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected;
[checkbox setSelected:checkBoxSelected];
}
to set a default user in app you may use the code below
In your AppDelegate.m
if ([[NSUserDefaults standardUserDefaults]boolForKey:#"IsFirstTime"])
{
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
ViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:#"ViewController"];
self.window.rootViewController = vc;
}
else
{
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:#"IsFirstTime"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
then #import your AppDelegate.m class to the class where you put code for login
AppDelegate *delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
}
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://43.252.88.251/jsonandroid/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=admin&password=123456&api_key=bf45c093e542f057c123ae7d6"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString* textField1Text = usernamefield.text;
[defaults setObject:textField1Text forKey:#"textField1Text"];
NSString *textField2Text = passwordfield.text;
[defaults setObject:textField2Text forKey:#"textField2Text"];
[defaults synchronize];
}
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:#"user_id"] forKey:#"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:#"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
/* ItemManagement *ItemManagement = [[ItemManagement alloc]init];
[self.navigationController pushViewController:ItemManagement animated:YES];
*/
}
else
{
NSLog(#"Unsuccessful, Try again.");
/* UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];*/
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Title" message:#"Hello" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelbutton = [UIAlertAction actionWithTitle:#"" style:UIAlertActionStyleCancel handler:nil];
//UIAlertAction *oktext= [UIAlertAction actionWithTitle:oktext style:UIAlertActionStyleDefault handler:nil];
[alert addAction:cancelbutton];
//[alert addAction:oktext];
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}
I try to upload an image to Azure storage through MVC 4 web API. But the server side always return:
"Invalid length for a Base-64 char array or string."
Below is Objective-C code:
- (IBAction)btnUploadReceipt:(id)sender {
UIImage *img = self.imgReceipt.image;
NSData *dataObj = UIImagePNGRepresentation(img);
NSString *fff = [dataObj base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
//NSString *ddd = [self base64EncodeString:imgData];
//NSString *ddd = [dataObj base64EncodedString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/api/upload/UploadAzure",baseUrl]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"Post"];
NSString *jsonData = [NSString stringWithFormat:#"FileName=%#&FileData=%#&FolderName=%#&UserName=%#&Point=%#&DateTime=%#&MerchantName=%#&OutletID=%#",fileName,fff,imgFolder,userName,#"3",dateTime,_mName,_mOutletID];
[request setHTTPBody:[jsonData dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSString * json =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",json);
if ([json isEqualToString:#"\"True\""]) {
NSLog(#"%#",#"Success Add Photo");
//[self dismissViewControllerAnimated:YES completion:nil];
//[[self navigationController]popViewControllerAnimated:YES];
}
else
{
UIAlertView *messageAlert = [[UIAlertView alloc]initWithTitle:#"Connection Error" message:#"Please Check Internet Setting" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[messageAlert show];
}
}
else
{
UIAlertView *messageAlert = [[UIAlertView alloc]initWithTitle:#"Connection Error" message:#"Please Check Internet Setting" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[messageAlert show];
}
}];
}
- (NSString *)base64String2 {
UIImage *img = self.imgReceipt.image;
NSData * data = [UIImagePNGRepresentation(img) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
return [NSString stringWithUTF8String:[data bytes]];
}
Anyone face this kind of problem?
Have you tried using the Azure Storage iOS Library? The Getting Started documentation should be able to help with your scenario.
I have a button
When it is done click on the request and opens the following window
when return back to the previous screen and then press the button query is executed with any parameters
This button code
- (IBAction)loginClick:(id)sender {
if ([self.emailTextField.text isEqualToString:#""] || [self.passwordTextField.text isEqualToString:#""]) {
UIAlertView *falseAlert = [[UIAlertView alloc]initWithTitle:#"" message:#"Please enter your username and password" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[falseAlert show];
} else {
[spinner startAnimating];
// dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
// dispatch_async(queue, ^{
NSString *initialURL = [NSString stringWithFormat:#"https://www.-------"];
NSURL *url=[NSURL URLWithString:initialURL];
NSString *key = [NSString stringWithFormat:#"username=%#&password=%#&service=%#", self.emailTextField.text, self.passwordTextField.text, #"login"];
NSData *mastData = [key dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *mastLength = [NSString stringWithFormat:#"%ld",[mastData length]];
NSError *error;
request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
[request setHTTPMethod:#"POST"];
[request setValue:mastLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:mastData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
info = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
request = NULL;
// dispatch_async(dispatch_get_main_queue(), ^{
if ([info[#"success"] isEqualToString:#"false"]) {
[self.errorLabel setHidden:FALSE];
[spinner stopAnimating];
[spinner setHidden:YES];
} else {
DounloadYatseykoViewController *newController = [self.storyboard instantiateViewControllerWithIdentifier:#"load"];
newController.dataInfo = responseData;
[self presentModalViewController:newController animated:YES];
}
//
// });
// });
}
//NSLog(#"%#", responseString);
}
So I go back to the previous screen
UIViewController *newController = [self.storyboard instantiateViewControllerWithIdentifier:#"login"];
[self presentViewController:newController animated:NO completion:nil];
I have a Login screen and I POST username and password to a login page.
The webservice gives me 2 responses if the Login user details are correct I get a response of back from the request.
{"value":1}
and if the user details are wrong I get back from request.
{"value":0}
I have been able to parse that JSON Result to give me a log output of
value: 1 or value:0
I am battling to handle the parsed json e.g
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:urlData //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"value"]; //2
NSLog(#"value: %#", defineJsonData); //3
if ([[json objectForKey:#"value"] isEqualToNumber:[NSNumber numberWithInt:1]])
{
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
[self performSegueWithIdentifier: #"introScreenView" sender:self];
}
else {
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Wrong Credentials" message:#"Please try to login again" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
Here is the rest of my code.
- (void)myTask {
if ([userNameTextField.text isEqualToString:#""] || [passwordTextField.text isEqualToString:#""]) {
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Feilds Missing" message:#"Please Fill all the field" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
NSString *data = [NSString stringWithFormat:#"UserName=%#&Password=%#",userNameTextField.text, passwordTextField.text];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// preaparing URL request to send data.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString *url = [NSString stringWithFormat:#"http://www.ddproam.co.za/Central/Account/LogOnIOS?"];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[request setTimeoutInterval:7.0];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Login response:%#",str);
NSHTTPCookie *cookie;
NSLog(#"name: '%#'\n", [cookie name]);
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
NSLog(#"name: '%#'\n", [cookie name]);
NSLog(#"value: '%#'\n", [cookie value]);
NSLog(#"domain: '%#'\n", [cookie domain]);
NSLog(#"path: '%#'\n", [cookie path]);
}
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:urlData //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"value"]; //2
NSLog(#"value: %#", defineJsonData); //3
if ([defineJsonData isEqual:0])
{
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Wrong Credentials" message:#"Please try to login again" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
else {
HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"37x-Checkmark.png"]];
HUD.mode = MBProgressHUDModeCustomView;
[HUD hide:YES afterDelay:0];
[self performSegueWithIdentifier: #"introScreenView" sender:self];
}
if (theConnection) {
}
}
If response from the server is really just {"value":1}, then you correctly parse JSON to dictionary using NSJSONSerialization.
However under value key, there is an instance of NSNumber, not NSArray.
Your code to retrieve value and check it should look like this:
NSNumber *defineJsonData = [json objectForKey:#"value"];
NSLog(#"value: %#", defineJsonData);
if ([defineJsonData integerValue] == 0) {
NSLog(#"Wrong credentials");
}
else {
NSLog(#"Welcome :-)");
}
I've been working on a way to send a value to a web-server in objective c.
I think I have everything working on both ends, except for the fact that my value doesn't show up in the email that is sent out.
Here is my code, if someone could point out what I'm doing wrong, that would be great.
(dval is what's not showing up)
NSMutableString *mmessage = [[NSMutableString alloc]initWithString:#""];
[mmessage appendString:[NSString stringWithFormat:#"<p><b>Drink Name:</b> %#</p>", dval]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://test.com/api/stuff/send"]];
NSMutableDictionary *postInfo = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:mmessage, #"message", nil] forKey:#"form"];
NSError *e = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:postInfo options:0 error:&e ];
__block int resp_code = 0;
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
resp_code = httpResponse.statusCode;
if(resp_code == 200){
NSDictionary *jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if ([[jsonObjects objectForKey:#"status"] isEqualToString:#"success"]) {
UIAlertView *emailsuccess = [[UIAlertView alloc] initWithTitle:#"Email Successfully sent." message:nil delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[emailsuccess show];
}
else if ([[jsonObjects objectForKey:#"status"] isEqualToString:#"failed"]) {
UIAlertView *emailfailed = [[UIAlertView alloc] initWithTitle:#"Email Failed." message:[jsonObjects objectForKey:#"messages"] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[emailfailed show];
}
else {
UIAlertView *emailfailed = [[UIAlertView alloc] initWithTitle:#"Email Response." message:[jsonObjects objectForKey:#"messages"] delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[emailfailed show];
}
}
}];