Overblog
Edit post Follow this blog Administration + Create my blog

#27 利用 Codable 儲存過年紅包

May 7 2019


#27 利用 Codable 儲存過年紅包

目的: 學習將自訂型別的資料存檔,存在 Documents 下,運用 Codable, PropertyListEncoder,PropertyListDecoder。

製作過年紅包 App,記錄別人給的紅包,和發給別人的紅包,方便未來研究分析,決定明年要包給對方多大的紅包。

參考資料

App Development with Swift 的 4.1 Protocols,4.7 Saving Data

App Development with Swift by Apple Education on iBooks
Read a free sample or buy App Development with Swift by Apple Education. You can read this book with iBooks on your…itunes.apple.com

4.7 的 Lab 範例,Emoji App

import Foundation
struct Emoji: Codable {
   var symbol: String
   var name: String
   var detailDescription: String
   var usage: String
   static let DocumentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
   static let ArchiveURL = DocumentsDirectory.appendingPathComponent("emojis").appendingPathExtension("plist")
   static func loadFromFile() -> [Emoji]?  {
      guard let codedEmojis = try? Data(contentsOf: ArchiveURL) else {return nil}
      let decoder = PropertyListDecoder()
      return try? decoder.decode(Array<Emoji>.self, from: codedEmojis)
   }
   static func saveToFile(emojis: [Emoji]) {
      let encoder = PropertyListEncoder()
      let codedEmojis = try? encoder.encode(emojis)
      try? codedEmojis?.write(to: ArchiveURL, options: .noFileProtection)
   }
}
Share this post
Repost0
To be informed of the latest articles, subscribe:
Comment on this post