2017-11-28 7 views
0

私はSqliteに文字列データを挿入しようとしたという問題があります。私はしたいと思う私の詳細ViewControllerユーザーが好きなViewControllerに表示されるSqliteファイルに文字列の単語と意味を渡すLikeボタンを押した場合。以下は私のDetailsVCコードです。Swift3の文字列からSqliteにデータを挿入する方法は?

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; 

    } 

} 

マイ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インスタンス

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 
    } 

} 

しかし、行のセルがFavouriteVCではありません。これを修正するには?私を助けてください。 ベスト、 サイタウンPha

+0

あなたが本当に望むものを想像するのは少し難しいですが、あなたのView Controllerの画面を投稿できますか? – YinKiet

+0

はい、ここに私の詳細View Controllerのスクリーンショットがあります。 [ここ](http://saitp.me/mac/details_vc.png) お気に入りのView Controllerスクリーンショット。 [ここをクリック](http://saitp.me/mac/favourite_vc.png) 単語と意味をデータベースに保存します。そして、それをお気に入りのView Controllerに表示したい。お気に入りビューコントローラは、テーブルビューセルです。では、どうすればいいですか? @YinKiet – SaiPha

答えて

0

私は1行のコードを追加して問題を解決しました。私のFavouriteVCクラスでは、ViewdidLoad関数 "fdata = FavouriteData.instance.getData()"の下に追加するだけです。 ここに私の完全なコードです。

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] 
     } 

    } 
関連する問題