LoginSignup
5
3

More than 3 years have passed since last update.

独自プロパティリスト(plist)を利用する

Posted at

iOSアプリで独自plist(プロパティリスト)を作って使いたい時のメモ。
※よくある、APIのURLとかその他アプリに特化した設定などに使用
※他の方がわかりやすく書いてくれているのもあるのでメモ程度

plistの作成

まずはお目当てのplistを作成します。

  • File→New→File(cmd+N)で新規作成画面を表示
  • Property Listを選択、名前(今回はApp.plist)を決めて作成

作成できたら、適当に値を設定しましょう。
今回はよくあるURLを記載します

作ったplistの読み込み

先程作ったApp.plistを読み込むコードが以下になります。

var property: Dictionary<String, Any> = [:]
// App.plistのパス取得
let path = Bundle.main.path(forResource: "App", ofType: "plist")
// App.plistをDictionary形式で読み込み
let configurations = NSDictionary(contentsOfFile: path!)
if let datasourceDictionary: [String : Any]  = configurations as? [String : Any] {
    property = configurations
}
// キーを指定して、値の取得
let url = property["url"] as! String
print(url)

データ取得部分も含めてクラス化

読み込み、データ取得を毎度書くのは無駄よってことで
クラス化します。

App.swift
class App {
    var property: Dictionary<String, Any> = [:]
    init() {
        // App.plistのパス取得
        let path = Bundle.main.path(forResource: "App", ofType: "plist")
        // App.plistをDictionary形式で読み込み
        let configurations = NSDictionary(contentsOfFile: path!)
        if let datasourceDictionary: [String : Any]  = configurations as? [String : Any] {
            property = datasourceDictionary
        }
    }

    /// 指定されたキーの値を取得する
    /// - Parameter key: plistのキー
    func getString(_ key: String) -> String? {
        guard let value: String = property[key] as? String else {
            return nil
        }
        return value
    }
}

さて、これで利用できるようになりました。
では実際に呼び出してみましょう。

var app = App()
print(app.getStirng("url"))

Appクラスをシングルトンにしてみる

シングルトンにすることで、読み込みを一回だけにしてあとはインスタンス再利用する形にします。
以下コードを追加

static let shared: App = {
    let instance = App()
    return instance
}()

全体

App.swift
class App {
    var property: Dictionary<String, Any> = [:]
    static let shared: App = {
        let instance = App()
        return instance
    }()
    private init() {
        // App.plist取得
        let path = Bundle.main.path(forResource: "App", ofType: "plist")
        let configurations = NSDictionary(contentsOfFile: path!)
        if let datasourceDictionary: [String : Any]  = configurations as? [String : Any] {
            property = datasourceDictionary
        }
    }

    /// 指定されたキーの値を取得する
    /// - Parameter key: plistのキー
    func getString(_ key: String) -> String? {
        guard let value: String = property[key] as? String else {
            return nil
        }
        return value
    }
}

さて、これで利用方法を変更します。

var app = App.shared
print(app.getStirng("url"))

これでアプリ独自プロパティも怖くない!!
次回は、これを環境別に設定できるようにしたいと思います。

参考

Swift で簡単なシングルトンの実装方法
Swiftでplistを読み込む

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3