Monday, 1 May 2017

Databse Using SQLiteDB (Swift)

Databse Using SQLiteDB (Swift)




Download Two File & Add:

SQLiteDB.swift :-  Download
SQLTable.swift : -  Download



Add framework : - 


- libsqlite3.tbd



Add PCH file & Import This Class in File :-



#import "sqlite3.h"
#import <time.h>


Add This PCH file in Build Settings of Application target : -






create database data.db : -









Write Coding In Appdelegate : -


        var window: UIWindow?
let db = SQLiteDB.shared

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
_ = db.openDB(copyFile:false)
return true
}



Create Class SQLTable :- 




import UIKit


class Task:SQLTable {
var id = -1
var task = ""
var categoryID = -1
}



Write Coding In TasksViewController.swift : -



import UIKit

class TasksViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var table:UITableView!
var data = [Task]()
override func viewDidLoad() {
super.viewDidLoad()
}

override func viewWillAppear(_ animated:Bool) {
super.viewWillAppear(animated)
// data = Task.rows(order:"task ASC") as! [Task]
data = Task.rows(order:"id ASC") as! [Task]
table.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

// UITableView Delegates
func tableView(_ tv:UITableView, numberOfRowsInSection section:Int) -> Int {
let cnt = data.count
return cnt
}
func tableView(_ tv:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tv.dequeueReusableCell(withIdentifier: "TaskCell")!
let task = data[indexPath.row]
cell.textLabel?.text = task.task
return cell
}
}



Write Coding In AddTaskViewController.swift : -



import UIKit

class AddTaskViewController: UITableViewController {
@IBOutlet var txtTask: UITextField!

@IBAction func save() {
// Hide keyboard
if txtTask.isFirstResponder {
txtTask.resignFirstResponder()
}
// Validations
if txtTask.text!.isEmpty {
let alert = UIAlertView(title:"SQLiteDB", message:"Please add a task description first!", delegate:nil, cancelButtonTitle: "OK")
alert.show()
}
// Save task
let task = Task()
task.task = txtTask.text!
if task.save() != 0 {
let alert = UIAlertView(title:"SQLiteDB", message:"Task successfully saved!", delegate:nil, cancelButtonTitle: "OK")
alert.show()
}
}
}



Final Inserted Data : - 



















No comments:

Post a Comment