2017-11-28 1 views
0

Sqlite에 문자열 데이터를 삽입하려고했는데 문제가 있습니다. 내가하고 싶은 내 세부 ViewController 사용자가 좋아하는 버튼을 누르면 단어와 문자열의 의미는 Favorite ViewController에 표시되는 Sqlite 파일로 전달됩니다. 아래는 내 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에서 행의 셀 없다. 이 문제를 해결하는 방법? 도와주세요. 최고, Sai Tawng Pha

+0

정말로 원하는 것을 상상하기가 다소 어렵습니다.보기 컨트롤러의 화면을 게시 할 수 있습니까? – YinKiet

+0

예, 내 세부보기 컨트롤러 스크린 샷입니다. [여기] (http://saitp.me/mac/details_vc.png) 즐겨 찾기 View Controller 스크린 샷. [here] (http://saitp.me/mac/favourite_vc.png) 데이터베이스에 문자열과 단어의 의미를 저장하고 싶습니다. 그리고,보다, 즐겨보기 컨트롤러에 표시하고 싶습니다. Favorite View Controller는 테이블 뷰 셀입니다. 그래서 어떻게해야합니까? @YinKiet – SaiPha

답변

0

한 줄의 코드를 추가하여 문제를 해결했습니다. 내 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] 
     } 

    } 
관련 문제