我做了一个简单的应用程序来做笔记。我将笔记存储在称为“数据”的数组中。
现在,我使用UserDefaults
进行保存,可以正常工作。但是现在我想将其扩展为使用Firebase。
我该怎么做?
这是我保存和检索数据的tableViewController
:
import UIKit
import Firebase
class TableViewControllers: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var table: UITableView!
var data:[String] = []
var selectedRow:Int = -1
var newRowText:String = ""
private let cellReuseIdentifier: String = "cell"
let collection = Firestore.firestore().collection("notes")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
table.dataSource = self
table.delegate = self
self.title = "Notes"
self.navigationController?.navigationBar.prefersLargeTitles = true
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNote))
self.navigationItem.rightBarButtonItem = addButton
self.navigationItem.leftBarButtonItem = editButtonItem
load()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if selectedRow == -1 {
return
}
data[selectedRow] = newRowText
if newRowText == "" {
data.remove(at: selectedRow)
}
table.reloadData()
save()
}
@objc func addNote() {
if table.isEditing {
return
}
let name:String = ""
data.insert(name, at: 0)
let indexPath:IndexPath = IndexPath(row: 0, section: 0)
table.insertRows(at: [indexPath], with: .automatic)
table.selectRow(at: indexPath, animated: true, scrollPosition: .none)
self.performSegue(withIdentifier: "detail", sender: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) as UITableViewCell
cell.textLabel?.text = data[indexPath.row]
return cell
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
table.setEditing(editing, animated: animated)
}
internal func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
data.remove(at: indexPath.row)
table.deleteRows(at: [indexPath], with: .fade)
save()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "detail", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let detailView:ViewController = segue.destination as! ViewController
selectedRow = table.indexPathForSelectedRow!.row
detailView.masterView = self
detailView.setText(t: data[selectedRow])
}
func save() {
UserDefaults.standard.set(data, forKey: "notes")
for dat in data {
// collection.addDocument(data: dat)
print(dat)
}
}
func load() {
if let loadedData:[String] = UserDefaults.standard.value(forKey: "notes") as? [String] {
data = loadedData
table.reloadData()
}
}
}