leoho0722
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    ###### tags: `第13屆IT邦鐵人賽文章` # 【在 iOS 開發路上的大小事-Day28】透過 Firebase 來管理資料 (Cloud Firestore 篇) Part2 # 前情提要 昨天已經將環境設定好了,今天要來將新增、讀取、更新、刪除、排序功能實作出來 # 開始實作 ## 設計留言的 Model 我們會需要一個 id 來記錄這是哪一筆留言,方便我們後面來處理 然後還需要記錄留言人的名字以及留言內容跟最後留言時間 所以就可以將這些東西設計成一個 struct 此外,後面我們還有**透過時間來排序留言**的需求 所以我們還需要讓這個 struct 符合 Comparable 的規範,所以 ```swift= struct MessageModel: Comparable { static func < (lhs: MessageModel, rhs: MessageModel) -> Bool { return lhs.time < rhs.time } var id: String var name: String var content: String var time: String } ``` ## 建立變數 宣告兩個變數跟一個常數 ```swift= let dataBase = Firestore.firestore() // 初始化 Firestore var docRef: DocumentReference? = nil // 建立資料庫參考 var messageList = [MessageModel]() // 取得 Struct 內容 ``` ## 要加到 viewDidLoad 裡面的東西 ```swift= override func viewDidLoad() { super.viewDidLoad() messageTableView.register(UINib(nibName: "FirestoreDatabaseCell", bundle: nil), forCellReuseIdentifier: "FirestoreDatabaseCell") // 因為我是用 Xib 設計畫面,所以要註冊一下 messageTableView.delegate = self messageTableView.dataSource = self self.fetchMessageFromFirebase() // 這個後面會用到,先寫著 } ``` ## 要加到送出 Button 的 IBAction 裡面的東西 ```swift= @IBAction func sendMessageToFirestoreDatabase(_ sender: UIButton) { self.sendMessageToFirestore() } // MARK: - 送出留言到 Cloud Firestore func sendMessageToFirestore() { let key = docRef?.documentID let message = [ "id": key, "name": self.messagePeopleTF.text!, "content": self.messageContentTV.text!, "time": self.getSystemTime() ] docRef = dataBase.collection("messages").addDocument(data: message as [String : Any], completion: { error in guard error == nil else { CustomFunc.customAlert(title: "錯誤訊息", message: "Error adding document: \(String(describing: error))", vc: self, actionHandler: nil) return } CustomFunc.customAlert(title: "留言已送出!", message: "", vc: self, actionHandler: self.fetchMessageFromFirestore) }) self.messagePeopleTF.text = "" self.messageContentTV.text = "" } ``` ## 從 Cloud Firestore Database 裡面讀取 / 抓取資料 ```swift= // MARK: - 從 Cloud Firestore 抓取留言 func fetchMessageFromFirestore() { dataBase.collection("messages").getDocuments { snapshot, error in if let error = error { CustomFunc.customAlert(title: "錯誤訊息", message: "Error getting document: \(String(describing: error))", vc: self, actionHandler: nil) } else { self.messageList.removeAll() for messages in snapshot!.documents { let messageObject = messages.data(with: ServerTimestampBehavior.none) // let messageID = messageObject["id"] let messageName = messageObject["name"] let messageContent = messageObject["content"] let messageTime = messageObject["time"] let message = MessageModel( id: messages.documentID, name: messageName as! String, content: messageContent as! String, time: messageTime as! String ) self.messageList.append(message) } self.messageTableView.reloadData() } } } ``` ## 取得送出留言 / 更新留言的時間 ```swift= // MARK: - 取得送出/更新留言的當下時間 func getSystemTime() -> String { let currectDate = Date() let dateFormatter: DateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss" dateFormatter.locale = Locale.ReferenceType.system dateFormatter.timeZone = TimeZone.ReferenceType.system return dateFormatter.string(from: currectDate) } ``` ## 將留言呈現在 TableView 上面 ```swift= extension CloudFirestoreDatabaseVC: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FirestoreDatabaseCell", for: indexPath) as! FirestoreDatabaseCell cell.messagePeople.text = messageList[indexPath.row].name cell.messageContent.text = messageList[indexPath.row].content return cell } ``` ## 更新留言 ```swift=+ // MARK: - 更新留言到 Cloud Firestore func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let editAction = UIContextualAction(style: .normal, title: "編輯") { action, view, completeHandler in let alertController = UIAlertController(title: "更新留言", message: "", preferredStyle: .alert) alertController.addTextField { textField in textField.text = self.messageList[indexPath.row].name } alertController.addTextField { textField in textField.text = self.messageList[indexPath.row].content } let updateAction = UIAlertAction(title: "更新", style: .default) { action in let updateMessage = [ "id": self.messageList[indexPath.row].id, "name": alertController.textFields?[0].text!, "content": alertController.textFields?[1].text!, "time": self.getSystemTime() ] DispatchQueue.main.async { self.dataBase.collection("messages").document("\(String(describing: self.messageList[indexPath.row].id))").updateData(updateMessage as [AnyHashable : Any]) CustomFunc.customAlert(title: "留言更新成功!", message: "", vc: self, actionHandler: self.fetchMessageFromFirestore) } } let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) alertController.addAction(updateAction) alertController.addAction(cancelAction) self.present(alertController, animated: true) completeHandler(true) } let leadingSwipeAction = UISwipeActionsConfiguration(actions: [editAction]) editAction.backgroundColor = UIColor(red: 0.0/255.0, green: 127.0/255.0, blue: 255.0/255.0, alpha: 1.0) return leadingSwipeAction } ``` ## 刪除留言 ```swift=+ // MARK: - 從 Cloud Firestore 刪除留言 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let deleteAction = UIContextualAction(style: .destructive, title: "刪除") { action, view, completeHandler in DispatchQueue.main.async { self.dataBase.collection("messages").document("\(String(describing: self.messageList[indexPath.row].id))").delete { error in if let error = error { CustomFunc.customAlert(title: "錯誤訊息", message: "Error removing document: \(String(describing: error))", vc: self, actionHandler: nil) } else { CustomFunc.customAlert(title: "已成功刪除留言!", message: "", vc: self, actionHandler: self.fetchMessageFromFirestore) } } } completeHandler(true) } let trailingSwipeAction = UISwipeActionsConfiguration(actions: [deleteAction]) return trailingSwipeAction } } ``` ## 要加到排序留言 Button 的 IBAction 裡面的東西 ```swift= // MARK: - 留言排序 @IBAction func sortMessage(_ sender: UIButton) { self.sortMessageFromFirestore() } enum sortMode { case defaultSort // 預設排序 (從新到舊) case fromNewToOldSort // 從新到舊 case fromOldToNewSort // 從舊到新 } func sortMessageFromFirestore() { let alertController = UIAlertController(title: "請選擇留言排序方式", message: "排序方式為送出/更新留言的時間早晚", preferredStyle: .actionSheet) let defaultAction = UIAlertAction(title: "預設排序", style: .default) { action in self.sortMessageList(sortMode: .defaultSort) } let fromNewToOldAction = UIAlertAction(title: "從新到舊", style: .default) { action in self.sortMessageList(sortMode: .fromNewToOldSort) } let fromOldToNewAction = UIAlertAction(title: "從舊到新", style: .default) { action in self.sortMessageList(sortMode: .fromOldToNewSort) } let closeAction = UIAlertAction(title: "關閉", style: .cancel, handler: nil) alertController.addAction(defaultAction) alertController.addAction(fromNewToOldAction) alertController.addAction(fromOldToNewAction) alertController.addAction(closeAction) self.present(alertController, animated: true) } func sortMessageList(sortMode: sortMode) { if (sortMode == .defaultSort || sortMode == .fromNewToOldSort) { self.messageList.sort(by: >) } else if (sortMode == .fromOldToNewSort) { self.messageList.sort(by: <) } self.messageTableView.reloadData() } ``` # 成果 {%youtube bXdRYdGWI7Q %} 本篇的範例程式碼: 1. MessageModel.swift:[Github](https://github.com/leoho0722/IT2021/blob/main/Day15~Day22%E3%80%81Day24~Day28/CocoaPodsDemo/CocoaPodsDemo/Model/MessageModel.swift) 2. CloudFirestoreDatabaseVC.swift:[Github](https://github.com/leoho0722/IT2021/blob/main/Day15~Day22%E3%80%81Day24~Day28/CocoaPodsDemo/CocoaPodsDemo/FirebaseVC/CloudFirestoreDatabaseVC/CloudFirestoreDatabaseVC.swift)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully