DEV'S

Shopping List App - Swift Part 1

ListViewController.swift

//
//  ListViewController.swift
//  TbleExample
//
//  Created by Vasudev Kumaran on 18/12/17.
//  Copyright © 2017 NSE. All rights reserved.
//

import UIKit

class ListViewController: UITableViewController,WebServiceDelegate {
    
    
    
    var webService:WebService = WebService();
    var itemArray:[Dictionary<String,Any>] = [];

    override func viewDidLoad() {
        super.viewDidLoad()
        webService.delegate = self;
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }
    
    override func viewDidAppear(_ animated: Bool) {
        let userDefaults:UserDefaults = UserDefaults.standard;        print(userDefaults.string(forKey: "LoginStatus") ?? "No Value");
            print(userDefaults.string(forKey: "user_name") ?? "No Username");
        if (userDefaults.string(forKey: "LoginStatus") != "loggedIn"){
            performSegue(withIdentifier: "loginSegue", sender: nil);
        }else{
            let username = userDefaults.string(forKey: "user_name") ?? "";
            let password = userDefaults.string(forKey: "user_password") ?? "";
            let payload = "username="+username+"&password="+password;
            //print(payload);
            webService.serverConnect(webUrl: "http://vasudevkumaran.com/app/getallitems", payload: payload);
        }
 
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return itemArray.count;
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)

        // Configure the cell…
        let itemObj = itemArray[indexPath.row];
        let itemName:UILabel = cell.viewWithTag(10) as! UILabel;
        let itemQty:UILabel = cell.viewWithTag(20) as! UILabel;
        let itemPrice:UILabel = cell.viewWithTag(30) as! UILabel;
        
        itemName.text = itemObj["item_name"] as? String;
        itemQty.text = "Qty: \(itemObj["item_qty"] as! Int)";
        itemPrice.text = "Price: \(itemObj["item_price"] as! Int)";
        return cell
    }
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // 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.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    func getWebServiceResults(result: Dictionary<String, Any>) {
        print(result);
        itemArray = result["items"] as! [Dictionary<String, Any>];
        self.tableView.reloadData();
    }
    
   @IBAction func getCallBack(segue:UIStoryboardSegue) -> Void{
        
    }

}

LoginViewController.swift

//
//  LoginViewController.swift
//  TbleExample
//
//  Created by Vasudev Kumaran on 18/12/17.
//  Copyright © 2017 NSE. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController,WebServiceDelegate {
    
    @IBOutlet weak var userNameField: UITextField!
    
    @IBOutlet weak var passwordField: UITextField!
    
    var webService:WebService?;
    
    func getWebServiceResults(result: Dictionary<String, Any>) {
        //print(result);
        let resultObj:String = result["result"] as! String;
        let userDefaults:UserDefaults = UserDefaults.standard;
        if (resultObj == "OK"){
            let userArray:[Dictionary<String,Any>] = result["data"] as! [Dictionary<String,Any>];
            let userObj:Dictionary<String,Any> = userArray[0];
            userDefaults.set(userObj["user_name"], forKey: "user_name");
            userDefaults.set(userObj["user_password"], forKey: "user_password");
            userDefaults.set(userObj["is_business"], forKey: "is_business");
            userDefaults.set(userObj["is_holidays"], forKey: "is_holidays");
            userDefaults.set(userObj["is_travel"], forKey: "is_travel");
            userDefaults.set(userObj["user_full_name"], forKey: "user_full_name");
            userDefaults.set(userObj["user_gender"], forKey: "user_gender");
            userDefaults.set(userObj["user_last_name"], forKey: "user_last_name");
            userDefaults.set(userObj["user_id"], forKey: "user_id");
            userDefaults.set("loggedIn", forKey: "LoginStatus");
            
            userDefaults.synchronize();
            dismiss(animated: true, completion: nil);
            
        }else{
        userDefaults.removeObject(forKey:"LoginStatus");
            self.showAlert(title: "Wrong", message: "Login Failed");
            
            userDefaults.synchronize();
        }
        
    }
    
    private func showAlert(title:String,message:String) -> Void{
        let alertController:UIAlertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert);
        let alertActionOk:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil);
        alertController.addAction(alertActionOk);
        present(alertController, animated: true, completion: nil);
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        let userDefaults:UserDefaults = UserDefaults.standard;
        userDefaults.removeObject(forKey:"LoginStatus");
        userDefaults.removeObject(forKey:"username");
        userDefaults.removeObject(forKey:"password");
        userDefaults.synchronize();
        webService = WebService();
        webService!.delegate = self;
        
        // Do any additional setup after loading the view.
    }
    

    @IBAction func loginPressed(_ sender: Any) {
        let payload:String = "username="+userNameField.text!+"&password="+passwordField.text!;
        /*
        let anotherWay:String = "username=\(userNameField.text!)&password=\(passwordField.text!)";
 */
        
        webService!.serverConnect(webUrl: "http://vasudevkumaran.com/app/login", payload: payload);
        //
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        userNameField.endEditing(true);
        passwordField.endEditing(true);
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

AddEditTableViewController.swift

//
//  AddEditTableViewController.swift
//  TbleExample
//
//  Created by Vasudev Kumaran on 18/12/17.
//  Copyright © 2017 NSE. All rights reserved.
//

import UIKit

class AddEditTableViewController: UITableViewController,WebServiceDelegate {
    
    
    
    
    @IBOutlet weak var itemQtyField: UITextField!
    @IBOutlet weak var itemNameField: UITextField!
    
    @IBOutlet weak var itemPriceField: UITextField!
    var webService:WebService = WebService();
    
    var itemId:Int = -1;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webService.delegate = self;

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func onSavePressed(_ sender: Any) {
        let userDefaults:UserDefaults = UserDefaults.standard;
        let userName = userDefaults.string(forKey: "user_name");
        let passWord = userDefaults.string(forKey: "user_password")
        if (itemId == -1){
        let payload = "username=\(userName!)&password=\(passWord!)&itemname=\(itemNameField.text!)&itemqty=\(itemQtyField.text!)&itemprice=\(itemPriceField.text!)";
        webService.serverConnect(webUrl: "http://vasudevkumaran.com/app/additem", payload: payload);
        }else{
            //Edit
        }
    }
    
    func getWebServiceResults(result: Dictionary<String, Any>) {
        print(result);
        performSegue(withIdentifier: "goBackSegue", sender: nil);
    }
    
    
}

WebService.swift


import UIKit

class WebService: NSObject {
    
    var delegate:WebServiceDelegate?;
    let contentType = "application/x-www-form-urlencoded";
    
    func serverConnect(webUrl:String,payload:String) -> Void {
        let url:URL = URL(string:webUrl)!;
        var request:URLRequest = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 250);
        request.httpMethod = "POST";
        request.addValue(contentType, forHTTPHeaderField: "Content-Type");
        request.httpBody = payload.data(using: String.Encoding.utf8);

        let session:URLSession = URLSession.shared;
        let sessionTask:URLSessionTask = session.dataTask(with: request, completionHandler:{ (data,response,_) in
            
            let httpResponse:HTTPURLResponse = response as! HTTPURLResponse;
            
            if (httpResponse.statusCode == 200){
                let resultDic:Dictionary<String,Any> = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String,Any>;
                DispatchQueue.main.async {
                    self.delegate?.getWebServiceResults(result: resultDic);
                }
            }
        }
        );
        
        sessionTask.resume();
        
        
    }
    
    

}

WebServiceDelegate.swift

//
//  WebServiceDelegate.swift
//  TbleExample
//
//  Created by Vasudev Kumaran on 18/12/17.
//  Copyright © 2017 NSE. All rights reserved.
//

import Foundation

protocol WebServiceDelegate {
    func getWebServiceResults(result:Dictionary<String,Any>) -> Void;
    
}

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