Wednesday, 17 January 2018

Swipe Delete cell from tableView (Using SQLite...)

step 1: Add following libraries.
1. libsqlite3.tbd
2. libsqlite3.0.tbd

step 2: Create Bridgeheader.h (Header) file.

step 3: Import sqlite3. Like,


#import <sqlite3.h>

step 4: Create database and table using "DB Browser For SQLite".
step 5: After create database and table, drag database_name.sqlite file and drop on your project.

step 6: Put the following code on Viewcontroller. Like,

var db : OpaquePointer? = nil
    var arr_of_Users : NSMutableArray = NSMutableArray()
    var arrData = NSMutableArray()
    var query = String()

    var temp = String()
    internal let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)
    internal let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)

step 7: Create the copy_file function. Like,

func copy_file()
    {
        let file_manager = FileManager.default
        let document_path = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        let destination_sqlite_url = document_path.appendingPathComponent("example_db.sqlite")
        let source_sqlite_url = Bundle.main.url(forResource: "example_db", withExtension: "sqlite")
        
        print("\(destination_sqlite_url.path)")
        
        if !file_manager.fileExists(atPath: destination_sqlite_url.path)
        {
            do
            {
                try file_manager.copyItem(at: source_sqlite_url!, to: destination_sqlite_url)
                print("copied..")
                print(destination_sqlite_url.path)
            }
            catch let error as NSError
            {
                print("Enable to create database:\(error.debugDescription)")
            }
        }
        if sqlite3_open(destination_sqlite_url.path, &db) != SQLITE_OK
        {
            print("Error open database..")
        }
        else
        {
            print("Success open database..")
        }
    }


step 8: Call this function on ViewDidLoad. Like,

override func viewDidLoad() {
        super.viewDidLoad()
        
        copy_file()
       
        
    }

step 9: Create select query function(Get data from table). Like,

func get_data_from_table(_ querySQL : String) -> NSMutableArray {
        var statement : OpaquePointer? = nil
        
        if sqlite3_prepare_v2(db, querySQL, -1, &statement, nil) != SQLITE_OK
        {
            let error_msg = String(cString: sqlite3_errmsg(db))
            print("Error prepaer select:\(error_msg)")
        }
        
                while sqlite3_step(statement) == SQLITE_ROW {
            
            
            let name = sqlite3_column_text(statement, 0)
            var name_str = String()
            if name != nil
            {
                name_str = String(cString: name!)
                print("Name is=\(name_str)")
            }
            else
            {
                print("Name is not found")
            }
            
            
            
            let dict_of_user : NSMutableDictionary = NSMutableDictionary()
            dict_of_user.setObject(name_str, forKey: "name" as NSCopying)
            
            
            arr_of_Users.add(dict_of_user)
        }
        print(arr_of_Users)
        
        if sqlite3_finalize(statement) != SQLITE_OK
        {
            let err_msg = String(cString: sqlite3_errmsg(db))
            print("Error finalized prepared statement\(err_msg)")
        }
        statement = nil
        return arr_of_Users
    }

step 10: Call this function on viewDidLoad. Like, 

override func viewDidLoad() {
        super.viewDidLoad()
        
        copy_file()
       
        arrData = get_data_from_table("select * from example_table")
        
        
        print(arrData)

    }

Note: I already put data on database, so I will get data from database.

step 11: Create delete function. Like, 

func deleteData(_ queryStr : String) {

        var deleteStatement: OpaquePointer? = nil
        if sqlite3_prepare_v2(db, queryStr, -1, &deleteStatement, nil) == SQLITE_OK {
            if sqlite3_step(deleteStatement) == SQLITE_DONE {
                print("Successfully deleted row.")
            } else {
                print("Could not delete row.")
            }
        } else {
            print("DELETE statement could not be prepared")
        }
        
        sqlite3_finalize(deleteStatement)
    }

step 12: Create UITableView on viewcontroller. Give proper constraints on it.

step 13: Give UITableviewDatasource and UITableviewDelegate.

step 14: Put following code in NumberOfRowsInSection method. Like,

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        
        return arrData.count
    }

step 15: Put following code in cellForRowAtindexPath method. Like,

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : custom_cell = tableView.dequeueReusableCell(withIdentifier: "custom_cell") as! custom_cell


        cell.textLabel?.text = (arrData[indexPath.row] as! NSMutableDictionary).value(forKey: "name") as? String
        return cell
    }

step 16: Put following code in commiteditingStyle method. Like,

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        temp = (arrData[indexPath.row] as! NSMutableDictionary).value(forKey: "name")! as! String
        print(temp)
        
        if editingStyle == .delete
        {
            
            arrData.removeObject(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)

            deleteData("delete from example_table where name = '\(temp)' ")
            
        }
        
        
    }

Note: This method is use to swipe delete cell from UITableview.

Thank you...

No comments:

Post a Comment