简体   繁体   中英

how to insert data from string to Sqlite in Swift3?

I have a problem that I have tried to insert string data to Sqlite. I want to do is in my Details ViewController if user press Like button, the word and meaning of string pass into Sqlite file that show in Favourite ViewController. Below is my DetailsVC code.

    import UIKit
import AVFoundation

class DetailsVC: UIViewController, UITextViewDelegate {

    @IBOutlet weak var wordLbl: UILabel!
    @IBOutlet weak var meaningLbl: UITextView!
    @IBOutlet weak var sysWordLbl: UILabel!
    @IBOutlet weak var sysWordsLbl: UILabel!
    @IBOutlet weak var anyWordsLbl: UILabel!
    @IBOutlet weak var anyWordLbl: UILabel!
    @IBOutlet weak var wordImg: UIImageView!
    @IBOutlet weak var buSound: UIButton!
    @IBOutlet weak var buLike: UIButton!
    @IBOutlet weak var menuBtn: UIButton!

    //Data from HomeVC
    var data:Data?
    var fdatas = [FData]()
    var favouriteVC = FavouriteVC()

    override func viewDidLoad() {
        super.viewDidLoad()

        meaningLbl.delegate = self

        wordLbl.text = "\((data?._word.capitalized)!) \((data?._phonetic)!)"
        self.meaningLbl.text = data?._meaning
        self.sysWordsLbl.text = data?._meaning
        self.anyWordsLbl.text = data?._meaning
        self.sysWordLbl.text = "Synonym"
        self.anyWordLbl.text = "Antonym"
        meaningLbl.font = UIFont(name: FONT_REGULAR, size: 24.0)

    }

    @IBAction func buMenu(_ sender: Any) {
        //menu
       dismiss(animated: true, completion: nil)

    }

    @IBAction func buSound(_ sender: Any) {
        //Todo: speak the word
        if buSound.isEnabled == true{
            buSound.setImage(UIImage(named: "volume-2.png"), for: .normal)
        }else{
            buSound.setImage(UIImage(named: "volume-un-2.png"), for: .normal)
        }
        let utTerance = AVSpeechUtterance(string: "\((data?._word)!)")
        let synthesize = AVSpeechSynthesizer()
        utTerance.voice = AVSpeechSynthesisVoice(language: "en-gb")
        synthesize.speak(utTerance)
    }

    @IBAction func buLike(_ sender: Any) {
        //Todo: Click Like
        if buLike.isEnabled == true{
            buLike.setImage(UIImage(named: "heart.png"), for: .normal)
            //Save data to Database
            let word = data?._word ?? ""
            let meaning = data?._meaning ?? ""
            do{
                let favData = FData(word: word, meaning: meaning)
                self.fdatas.append(favData)
                print("\(word), \(meaning)")
            }catch{
                print(error)
            }
        }else{
            buSound.setImage(UIImage(named: "heart-un.png"), for: .normal)
        }
        //FavouriteVC.insertRowsAtIndexPaths([NSIndexPath(forRow: fdatas.count-1, inSection: 0)], withRowAnimation: .Fade)
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

            self.view.endEditing(true);
            return false;

    }

}

My FavouriteVC

    import UIKit
import SwipeCellKit
import SQLite

class FavouriteVC: UIViewController,UITableViewDelegate,UITableViewDataSource, SwipeTableViewCellDelegate{

    //TabelView
     @IBOutlet weak var fTableView: UITableView!

    //Variables
    var fdata = [FData]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // FtableView
        fTableView.delegate = self
        fTableView.dataSource = self

        //reload Data
        fTableView.reloadData()

    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: FAVOURITE_CELL, for: indexPath) as? FavouriteCell{
            cell.configureCell(fdata: fdata[indexPath.row])
            //cell.delegate = self
            return cell
        }
        return FavouriteCell()
    }

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        guard orientation == .right else { return nil }

        let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
            // handle action by updating model with deletion

        }

        // customize the action appearance
        deleteAction.image = UIImage(named: "delete")

        return [deleteAction]
    }

}

FData.swif

    import Foundation

class FData {

    //let id: Int64?
    var word: String
    var meaning: String
    //var address: String

    init(id: Int64) {
       // self.id = id
        word = ""
        meaning = ""
        //address = ""
    }

    init(word: String, meaning: String) {
       // self.id = id
        self.word = word
        self.meaning = meaning
        //self.address = address
    }

}

FavouriteData Instance

    import UIKit
import SQLite

class FavouriteData{

    static let instance = FavouriteData()
    private let db: Connection?

    private let words = Table("words")
    private let id = Expression<Int64>("id")
    private let wordL = Expression<String?>("word")
    private let meaningL = Expression<String?>("shanword_uni")
    //private let address = Expression<String>("address")

    private init() {
        let path = NSSearchPathForDirectoriesInDomains(
            .documentDirectory, .userDomainMask, true
            ).first!

        do {
            db = try Connection("\(path)/favourite.sqlite")
        } catch {
            db = nil
            print ("Unable to open database")
        }

        createTable()
    }

    func createTable() {
        do {
            try db!.run(words.create(ifNotExists: true) { table in
                table.column(id, primaryKey: true)
                table.column(wordL)
                //table.column(phone, unique: true)
                table.column(meaningL)
            })
        } catch {
            print("Unable to create table")
        }
    }

    func addData(word: String, meaning: String) -> Int64? {
        do {
            let insert = words.insert(wordL <- word, meaningL <- meaning)
            let id = try db!.run(insert)
            print("Save: \(id)")
            return id
        } catch {
            print("Insert failed")
            return -1
        }
    }

    func getData() -> [FData] {
        var contacts = [FData]()

        do {
            for contact in try db!.prepare(self.words) {
                contacts.append(FData(
                   // id: contact[id],
                    word: contact[wordL]!,
                    meaning: contact[meaningL]!))
            }
        } catch {
            print("Select failed")
        }

        return contacts
    }

    func deleteData(index: Int64) -> Bool {
        do {
            let contact = words.filter(id == index)
            try db!.run(contact.delete())
            return true
        } catch {
            print("Delete failed")
        }
        return false
    }

}

But, there is not cell of row in the FavouriteVC. How to fix this? Please help me. Best, Sai Tawng Pha

I have solved my problem by add one line of code. In my FavouriteVC class, just add it under ViewdidLoad function " fdata = FavouriteData.instance.getData() ". Here is my complete code.

    import UIKit
    import SwipeCellKit
    import SQLite

    class FavouriteVC: UIViewController,UITableViewDelegate,UITableViewDataSource, SwipeTableViewCellDelegate{

        //TabelView
         @IBOutlet weak var fTableView: UITableView!

        //Variables
        var fdata = [FData]()

        override func viewDidLoad() {
            super.viewDidLoad()

            // FtableView
            fTableView.delegate = self
            fTableView.dataSource = self

            //reload Data
            fTableView.reloadData()
            //Get Data 
            fdata = FavouriteData.instance.getData()

        }

        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }

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

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            if let cell = tableView.dequeueReusableCell(withIdentifier: FAVOURITE_CELL, for: indexPath) as? FavouriteCell{
                cell.configureCell(fdata: fdata[indexPath.row])
                //cell.delegate = self
                return cell
            }
            return FavouriteCell()
        }

        func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
            guard orientation == .right else { return nil }

            let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
                // handle action by updating model with deletion

            }

            // customize the action appearance
            deleteAction.image = UIImage(named: "delete")

            return [deleteAction]
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM