iT邦幫忙

2022 iThome 鐵人賽

DAY 15
0
自我挑戰組

iOS Junior的菜雞之路系列 第 15

我現在進來了,誒,我又出去了 難道你是方唐SheetDB

  • 分享至 

  • xImage
  •  

資料庫核心邏輯 CRUD
C: Create
R: Read
U: Update
D: Delete

這次會用到的儲存方式是有別於使用本機的UserDefault,希望使用更簡單工作,可以紀錄
這次會使用SheetDB來作為一些資料的紀錄

Post -> Create
Get -> Read
Put -> Update
Delete -> Delete

上傳資料結構

struct ActressData: Codable {
    let data: Actress
}

struct Actress: Codable {
    let name: String
    let id: String
    let img: String
}

Post 新增資料

新增資料非常簡單
HttpMethod選擇為Post
帶入資料

提醒: Decode的結構為[String: Int]
如果使用錯誤就會造成Decode Error

func uploadData(param: Actress = Actress(name: "fake", id: "0", img: "....")) {
        // string填上自己的API URL
        let url = URL(string: "https://sheetdb.io/api//xxxxxxxxxxxx")!
        var urlReqeust = URLRequest(url: url)
        urlReqeust.httpMethod = "Post"
        urlReqeust.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let actressData = ActressData(data: param)
        let encoder = JSONEncoder()
        if let data = try? encoder.encode(actressData) {
            URLSession.shared.uploadTask(with: urlReqeust, from: data) { _, response, error in
                do {
                    if let retData = retData {
                        let decoder = JSONDecoder()
                        let result = try decoder.decode([String: Int].self, from: retData)
                        print("Created",result["created"] == 1 ? "Sucess" : "Failure")
                    }
                } catch {
                    print("Error:", error.localizedDescription)
                }
            }.resume()
        }

}

Get -> 讀取資料

更簡單,甚至不用加上要上傳的參數
我覺得這邊有個重點,之前一直遇到這個問題解決不了

Decode結構要使用[String: Any]

因為以我之前串過的API,他們其實至少都會有名字,導致我剛開始串的時候一直串失敗
因為通常會用一個Struct來代替

func uploadData(param: Actress = Actress(name: "fake", id: "0", img: "....")) {
        // string填上自己的API URL
        let url = URL(string: "https://sheetdb.io/api//xxxxxxxxxxxx")!
        var urlReqeust = URLRequest(url: url)
        urlReqeust.httpMethod = "Get"
        urlReqeust.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        URLSession.shared.dataTask(with: urlReqeust) { _, response, error in
            if error != nil {
                print("Err",error)
            }
            do {
                let statusCode = response as? HTTPURLResponse
                //print("StatusCode",statusCode?.statusCode)
                if let data = data {
                    let decoder = JSONDecoder()
                    let result = try decoder.decode([[String: String]].self, from: data)
                }
            } catch let DecodingError.dataCorrupted(context) {
                print(context)
            } catch let DecodingError.keyNotFound(key, context) {
                print("Key '\(key)' not found:", context.debugDescription)
                print("codingPath:", context.codingPath)
            } catch let DecodingError.valueNotFound(value, context) {
                print("Value '\(value)' not found:", context.debugDescription)
                print("codingPath:", context.codingPath)
            } catch let DecodingError.typeMismatch(type, context)  {
                print("Type '\(type)' mismatch:", context.debugDescription)
                print("codingPath:", context.codingPath)
            } catch {
                print("error: ", error)
            }   
        }.resume()
}

Put -> 更新資料

使用Put要丟要更新參數的Col名稱、要更新的Value(就是格子內的資料)
SheetDB會找到符合該Value的所有row都會更新資料上去

func updataData(param: Actress = Actress(name: "fake", id: "0", img: "....")) {
        // string填上自己的API URL
        let url = URL(string: "https://sheetdb.io/api//xxxxxxxxxxxx/自己的col名稱/在Col內的該Value")!
        var urlReqeust = URLRequest(url: url)
        urlReqeust.httpMethod = "Put"
        urlReqeust.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let actressData = ActressData(data: param)
        let encoder = JSONEncoder()
        if let data = try? encoder.encode(actressData) {
            URLSession.shared.uploadTask(with: urlReqeust, from: data) { retData, response, error in
                do {
                    if let retData = retData {
                        let decoder = JSONDecoder()
                        let result = try decoder.decode([String: Int].self, from: retData)
                        print("Updated: ",result["updated"] == 1 ? "Sucess" : "Failure")
                    }
                } catch {
                    print("Error:", error.localizedDescription)
                }
            }.resume()
        }

}

Delete -> 刪除資料

使用Delete要丟要刪除參數的Col名稱、要刪除的Value值
不過這就只會刪除符合Value填寫的所有row

func updataData(param: Actress = Actress(name: "fake", id: "0", img: "....")) {
        // string填上自己的API URL
        let url = URL(string: "https://sheetdb.io/api//xxxxxxxxxxxx/自己的col名稱/在Col內的該Value")!
        var urlReqeust = URLRequest(url: url)
        urlReqeust.httpMethod = "Delete"
        urlReqeust.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        URLSession.shared.dataTask(with: urlReqeust, from: data) { _, response, error in
            do {
                    if let retData = retData {
                        let decoder = JSONDecoder()
                        let result = try decoder.decode([String: Int].self, from: retData)
                        print("Deleted: ",result["deleted"] == 1 ? "Sucess" : "Failure")
                    }
                } catch {
                    print("Error:", error.localizedDescription)
                }
        }.resume()
}

參考資料:
https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/100%E9%81%93iosapp%E8%AC%8E%E9%A1%8C-20-%E8%A8%82%E9%A3%B2%E6%96%99-app-%E4%B8%8A%E5%82%B3%E8%B3%87%E6%96%99%E5%88%B0%E5%BE%8C%E5%8F%B0-f2e74e3bca91
https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E8%A9%A6%E8%A9%A6%E7%B0%A1%E5%96%AE%E5%A5%BD%E7%94%A8%E7%9A%84sheetdb-8c588b9b4eab


坑:
就如我上面所講的[String: String] 坑殺了一段時間,專研了很多人寫的Decode才有所發現


上一篇
Frame 虐我千百遍,SnapKit待我如初戀
下一篇
TinderCard Slide 研究 - 1
系列文
iOS Junior的菜雞之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言