設定ファイルなどのシンプルなデータをアプリ内に保存し、必要に応じて読み込みたいようなケースでは、JSON形式で取り扱うと簡単に行えます。
今回はUnboxとWrapという2つのライブラリを使ったSwiftの簡単な実装例を紹介します。
Unbox、WrapともにJohn Sundell氏が公開しているJSON decoder/encoderです(GitHubはこちら)
UnboxとWrapをXcodeプロジェクトに追加します。
UnboxとWrapはCocoaPodsやCarthageなどのメジャーなツールに対応しています。
Carthageを利用する場合はこちらを参考にライブラリを追加してください。
JSON化するデータを定義します。
import Unbox struct Setting { let sound: Sound let notification: Notification struct Sound { let bgmVolume: Float let seVolume: Float let mute: Bool } struct Notification { let general: Bool let event: Bool let recommend: Bool } }
設定データをJSON化してテキストファイルに保存します。
import UIKit import Wrap class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 設定データの準備 let sound = Setting.Sound(bgmVolume: 1.0, seVolume: 1.0, mute: false) let notification = Setting.Notification(general: true, event: true, recommend: true) let setting = Setting(sound: sound, notification: notification) // セーブ save(setting) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func save(_ setting: Setting) { // 保存するパスの指定 let path = NSHomeDirectory() + "/Documents/setting.txt" let url = URL(fileURLWithPath: path) do { // 設定データをData型に変換してsetting.txtに出力する let data: Data = try wrap(setting) try data.write(to: url, options: Data.WritingOptions.atomic) } catch { } } }
JSONをdecodeするための処理を追加します。
import Unbox struct Setting { // 省略 } // 追加 extension Setting: Unboxable { init(unboxer: Unboxer) throws { self.sound = unboxer.unbox(key: "sound") self.notification = unboxer.unbox(key: "notification") } } extension Setting.Sound: Unboxable { init(unboxer: Unboxer) throws { self.bgmVolume = unboxer.unbox(key: "bgmVolume") self.seVolume = unboxer.unbox(key: "seVolume") self.mute = unboxer.unbox(key: "mute") } } extension Setting.Notification: Unboxable { init(unboxer: Unboxer) throws { self.general = unboxer.unbox(key: "general") self.event = unboxer.unbox(key: "event") self.recommend = unboxer.unbox(key: "recommend") } }
setting.txtから設定データを読み込みます。
import UIKit import Wrap class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 設定データの読み込み if let setting = load() { } else { // 設定データの準備 let sound = Setting.Sound(bgmVolume: 1.0, seVolume: 1.0, mute: false) let notification = Setting.Notification(general: true, event: true, recommend: true) let setting = Setting(sound: sound, notification: notification) // セーブ save(setting) } } // 省略 func load() -> Setting? { // setting.txtのパスの指定 let path = NSHomeDirectory() + "/Documents/setting.txt" let url = URL(fileURLWithPath: path) do { // Data型からSetting型に変換する let data = try Data(contentsOf: url) let setting: Setting = try unbox(data: data) return setting } catch { return nil } } }
UnboxとWrapを利用して設定ファイルを永続化するSwiftのコードを紹介しました。
保存するデータ量の多いアプリを作る機会があればRealmを使ってみたいと思います。