DEV'S

Shopping List App - Cloud - Part 2

LoginViewController.h
//
//  LoginViewController.h
//  ShoppingListCloudApp
//

#import <UIKit/UIKit.h>
#import "WebService.h"

@interface LoginViewController : UIViewController<WebServiceDelegate>
@property (strong, nonatomic) IBOutlet UITextField *usernameField;
@property (strong, nonatomic) IBOutlet UITextField *passwordField;

@property(nonatomic,retain)WebService *webService;

@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *loader;

-(IBAction)loginButtonPressed:(id)sender;

@end

LoginViewController.m

//
//  LoginViewController.m
//  ShoppingListCloudApp
//

#import "LoginViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

@synthesize webService,usernameField,passwordField,loader;

- (void)viewDidLoad {
    [super viewDidLoad];
    webService = [[WebService alloc]init];
    [webService setWebDelegate:self];
    
    [loader stopAnimating];
  
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)loginButtonPressed:(id)sender{
    
    [loader startAnimating];
    
    NSString *payload = [NSString stringWithFormat:@"username=%@&password=%@",usernameField.text,passwordField.text];
    NSLog(@"%@",payload);
    [webService callWebServiceURL:@"http://devsonline.in/app/login" withPayLoad:payload withType:@"Login"];
    
    /*
    [webService callWebServiceURL:@"http://devsonline.in/app/getallitem" withPayLoad:payload withType:@"GetAllItem"];
     */
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - WebServiceDelegate Functions here
-(void)getResponseFromWeb:(NSDictionary *)result by:(NSString *)type{
    
    [loader stopAnimating];
    NSLog(@"%@",result);
    
    if ([type isEqualToString:@"Login"]){
        
        if ([[result objectForKey:@"result"] isEqualToString:@"OK"]){
        //Login success
            NSArray *userData = [result objectForKey:@"data"];
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            
            NSDictionary *user = [userData objectAtIndex:0];
            
            [userDefault setValue:[user objectForKey:@"user_name"] forKey:@"username"];
            [userDefault setValue:[user objectForKey:@"user_password"] forKey:@"password"];
            [userDefault setValue:[user objectForKey:@"user_id"] forKey:@"userid"];
            
            [userDefault synchronize];
            
            [self performSegueWithIdentifier:@"loginsuccesssegue" sender:self];
        
        }else{
        //Login Failed
            UIAlertController *uiAlertCtrl = [UIAlertController alertControllerWithTitle:@"Login Failed!!" message:@"Username /Password Wrong" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
            
            [uiAlertCtrl addAction:okAction];
            
            [self presentViewController:uiAlertCtrl animated:YES completion:nil];
            
        }
        
    }else if ([type isEqualToString:@"GetAllItem"]){
    
    }
}

@end

RegistrationViewController.h

//
//  RegistrationViewController.h
//  ShoppingListCloudApp
//

#import <UIKit/UIKit.h>
#import "WebService.h"

@interface RegistrationViewController : UIViewController<WebServiceDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
@property (strong, nonatomic) IBOutlet UITextField *firstNameField;
@property (strong, nonatomic) IBOutlet UITextField *lastNameField;
@property (strong, nonatomic) IBOutlet UITextField *passwordField;
@property (strong, nonatomic) IBOutlet UITextField *genderField;
@property (strong, nonatomic) IBOutlet UITextField *usernameField;
@property (nonatomic, retain) UIPickerView *genderPicker;
@property (nonatomic, retain) NSArray *genderArray;

@property (nonatomic,retain) NSArray *gender;

@property (nonatomic,retain)WebService *webService;

@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *activityLoader;

-(IBAction)saveButtonPressed:(id)sender;
-(IBAction)cancelButtonPressed:(id)sender;

@end

RegistrationViewController.m

//
//  RegistrationViewController.m
//  ShoppingListCloudApp
//

#import "RegistrationViewController.h"

@interface RegistrationViewController ()

@end

@implementation RegistrationViewController

@synthesize webService,firstNameField,lastNameField,usernameField,passwordField,genderField,gender,genderPicker,genderArray,activityLoader;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //genderArray = @[@"Male",@"Female"];
    genderPicker = [[UIPickerView alloc]init];
    [genderPicker setDataSource:self];
    [genderPicker setDelegate:self];
    
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:(CGRectMake(0, 0, self.view.frame.size.width, 35))];
    
    UIBarButtonItem *okButton = [[UIBarButtonItem alloc]initWithTitle:@"OK" style:UIBarButtonItemStyleDone target:self action:@selector(donePressed)];
    
    UIBarButtonItem *flex = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    NSArray *barButtons = [NSArray arrayWithObjects:flex,okButton,flex, nil];
    
    [toolBar setItems:barButtons];
    
    genderArray = [[NSArray alloc]initWithObjects:@"Male",@"Female", nil];
    webService = [[WebService alloc]init];
    [webService setWebDelegate:self];
    
    
    [genderField setInputAccessoryView:toolBar];
    
    [genderField setInputView:genderPicker];
    
    [genderField setText:[genderArray objectAtIndex:1]];
    [genderPicker selectRow:1 inComponent:0 animated:YES];
    
    [activityLoader stopAnimating];
}

-(void)donePressed{
    [[self view]endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)saveButtonPressed:(id)sender{
    
    
    [activityLoader startAnimating];
    NSString *payload = [NSString stringWithFormat:@"firstname=%@&lastname=%@&username=%@&password=%@&gender=%d",firstNameField.text,lastNameField.text,usernameField.text,passwordField.text,(int)[genderPicker selectedRowInComponent:0]+1];
    
    [webService callWebServiceURL:@"http://devsonline.in/app/registration" withPayLoad:payload withType:@"Registration"];
    
    

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];

}

-(IBAction)cancelButtonPressed:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - WebServiceDelegate Function here
-(void)getResponseFromWeb:(NSDictionary *)result by:(NSString *)type{
    
    [activityLoader stopAnimating];

    if ([type isEqualToString:@"Registration"]){
    
        NSLog(@"%@",result);
        
        NSString *resultObj = [result objectForKey:@"result"];
        
        if ([resultObj isEqualToString:@"OK"]){
        //Successfully Registered
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
        //Registration Failed // Display a UIAlertController
            UIAlertController *uiAlertCtrl = [UIAlertController alertControllerWithTitle:@"Registration Failed!!" message:[result objectForKey:@"message"] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
            
            [uiAlertCtrl addAction:okAction];
            
            [self presentViewController:uiAlertCtrl animated:YES completion:nil];
        }
        
    }

}

#pragma mark UIPickerViewDataSource methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [genderArray count];
}

#pragma mark - UIPickerViewDelegate methods

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [genderArray objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    [genderField setText:[genderArray objectAtIndex:row]];
}

@end

WebService.h

//
//  WebService.h
//  ShoppingListCloudApp

#import <Foundation/Foundation.h>

@class WebService;

@protocol WebServiceDelegate <NSObject>

-(void)getResponseFromWeb:(NSDictionary *)result by:(NSString *)type;

@end

@interface WebService : NSObject

@property(nonatomic,retain) id <WebServiceDelegate> webDelegate;

-(void)callWebServiceURL:(NSString *)webUrl withPayLoad:(NSString *)payLoad withType:(NSString *)type;

-(void)displayMessage:(NSString *)message withTitle:(NSString *)title;

@end

WebService.m

//
//  WebService.m
//  ShoppingListCloudApp

#import "WebService.h"

@implementation WebService

@synthesize webDelegate;

-(void)callWebServiceURL:(NSString *)webUrl withPayLoad:(NSString *)payLoad withType:(NSString *)type{

    NSURL *url = [NSURL URLWithString:webUrl];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:240];
    
    [request setHTTPMethod:@"POST"];
    
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSString *strLen = [NSString stringWithFormat:@"%ld", (long)payLoad.length];
    
    [request setValue:strLen forHTTPHeaderField:@"Content-Length"];
    
    NSData *payLoadData = [payLoad dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPBody:payLoadData];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
    
        NSHTTPURLResponse *httpUrlResponse = (NSHTTPURLResponse *)response;
        
        if ([httpUrlResponse statusCode] == 200){
        //Valid response
            NSError *rError;
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&rError];
            dispatch_async(dispatch_get_main_queue(), ^(void){
            
                [webDelegate getResponseFromWeb:result by:type];
            
            });
            
            
        }else{
        //Something went wrong
            
        }
        
    }];
    
    [task resume];
    
    
    

}

-(void)displayMessage:(NSString *)message withTitle:(NSString *)title{
    
    

}

@end

ShoppingTableViewController.h

//
//  ShoppingTableViewController.h
//  ShoppingListCloudApp
//

#import <UIKit/UIKit.h>

@interface ShoppingTableViewController : UITableViewController

-(IBAction)getCallBackFromAddEdit:(UIStoryboardSegue *)segue;

@end

ShoppingTableViewController.m

//
//  ShoppingTableViewController.m
//  ShoppingListCloudApp
//

#import "ShoppingTableViewController.h"

@interface ShoppingTableViewController ()

@end

@implementation ShoppingTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)getCallBackFromAddEdit:(UIStoryboardSegue *)segue{
    //sh
}
 

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return 0;
}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell…
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

@end

AddEditViewController.h

//
//  AddEditViewController.h
//  ShoppingListCloudApp
//

#import <UIKit/UIKit.h>
#import "WebService.h"

@interface AddEditViewController : UIViewController<WebServiceDelegate>
@property (strong, nonatomic) IBOutlet UITextField *itemNameField;
@property (strong, nonatomic) IBOutlet UITextField *itemPriceField;

@property (strong, nonatomic) IBOutlet UITextField *itemQtyField;

@property (nonatomic, retain) WebService *webService;
@property (strong, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

-(IBAction)saveButtonPressed:(id)sender;

@end

AddEditViewController.m

//
//  AddEditViewController.m
//  ShoppingListCloudApp
//

#import "AddEditViewController.h"

@interface AddEditViewController ()

@end

@implementation AddEditViewController

@synthesize itemNameField;
@synthesize itemPriceField;
@synthesize itemQtyField;
@synthesize webService;
@synthesize activityIndicator;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    webService = [[WebService alloc]init];
    [webService setWebDelegate:self];
    [activityIndicator stopAnimating];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)saveButtonPressed:(id)sender{
    [activityIndicator startAnimating];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *payload = [NSString stringWithFormat:@"username=%@&password=%@&itemname=%@&itemqty=%@&itemprice=%@",[userDefault objectForKey:@"username"],[userDefault objectForKey:@"password"],itemNameField.text,itemQtyField.text,itemPriceField.text];
    
    
    [webService callWebServiceURL:@"http://devsonline.in/app/additem" withPayLoad:payload withType:@"AddItem"];
    
    

}

#pragma mark - WebServiceDelegate function
-(void)getResponseFromWeb:(NSDictionary *)result by:(NSString *)type{
    [activityIndicator stopAnimating];
    NSLog(@"%@",result);
    if ([[result objectForKey:@"result"] isEqualToString:@"OK"]){
        //Successfully Added
        [self performSegueWithIdentifier:@"donesegue" sender:self];
    }

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

Info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSAllowsArbitraryLoads</key>
		<true/>
	</dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>en</string>
	<key>CFBundleExecutable</key>
	<string>$(EXECUTABLE_NAME)</string>
	<key>CFBundleIdentifier</key>
	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>$(PRODUCT_NAME)</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>CFBundleShortVersionString</key>
	<string>1.0</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>CFBundleVersion</key>
	<string>1</string>
	<key>LSRequiresIPhoneOS</key>
	<true/>
	<key>UILaunchStoryboardName</key>
	<string>LaunchScreen</string>
	<key>UIMainStoryboardFile</key>
	<string>Main</string>
	<key>UIRequiredDeviceCapabilities</key>
	<array>
		<string>armv7</string>
	</array>
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UISupportedInterfaceOrientations~ipad</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationPortraitUpsideDown</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
</dict>
</plist>

iOS

2017-12-19 00:07:26
1) CoreData - UIDatePicker - Part2 - Final
2017-12-18 23:29:30
2) CoreData - UIDatePicker - Part1
2017-12-18 05:09:33
3) Shopping List App - Swift Part 2 - ActionSheet
2017-12-18 03:22:51
4) Shopping List App - Swift Part 1
2017-12-17 23:34:49
5) Swift - Introduction - WebService
2017-12-15 03:30:23
6) Shopping List IOS App - Part 2
2017-12-15 01:21:10
7) Shopping List IOS App - Part 1
2017-12-14 21:58:22
8) Shopping List IOS App - API Calls
2017-12-14 03:48:37
9) Delegate - Protocols - WebService
2017-12-13 04:28:23
10) NSMutableArray - NSMutableDictionary - TableViewController
2017-12-13 02:47:13
11) UITableViewController
2017-12-12 22:59:32
12) Segue Forward And Unwind
2016-02-27 03:20:22
13) GoogleMap Addon
2016-02-26 04:06:38
14) UILocalNotification With NSNotificationCenter
2016-02-25 03:51:07
15) CLLocationManager Example
2016-02-24 03:27:59
16) UIImagePickerController Using Camera And PhotoLibrary
2016-02-23 02:08:19
17) Multi Section UITableView - UIPickerView
2016-02-18 03:16:09
18) Hello World IOS App Using Swift
2016-02-17 03:10:24
19) Swift Programming Language - Playground
2016-02-15 02:06:55
20) TabBar Controller
2016-02-15 02:06:55
21) Understanding Auto Layout and Layout Constraints
2016-02-10 22:56:12
22) Shopping List App - Cloud - Part 3 - Final
2016-02-09 04:12:06
23) Shopping List App - Cloud - Part 2
2016-02-08 03:21:52
24) Shopping List App - Cloud - Part 1
2016-02-05 03:24:01
25) Protocol And Delegates With NSURLSession
2016-02-04 00:59:51
26) Webservice Using NSURLSession
2016-02-02 02:09:13
27) UIPickerView Addon - InputView And AccessoryView For UITextField
2016-02-02 02:07:12
28) Protocol And Delegates
2016-02-01 00:37:02
29) UIPickerView - Add Programmatically
2016-01-30 00:52:48
30) NSUserDefaults - UIAlertControler - Back Navigation Title Change
2016-01-29 02:01:06
31) CoreData - StudentsRecord App
2016-01-27 21:54:28
32) Manual Segue
2016-01-27 00:04:21
33) TableViewController Example
2016-01-25 02:08:16
34) NSArray And NSDictionary
2016-01-23 03:23:10
35) Reverse (Unwind) Segue
2016-01-22 00:56:28
36) ViewController - Segue - Messages
2014-12-22 05:29:28
37) WebService Example
2014-12-22 05:16:57
38) CoreData Example

© Vasudev.H / Email: tech3in@live.com