LoginSignup
7
7

More than 5 years have passed since last update.

Info.plistを使って情報を保存・取得する方法

Last updated at Posted at 2018-02-03

背景

iOSアプリを開発していると、APIのURLや特定の文字列等の固定値をアプリ内に持っておきたい場合があります。定数管理用のクラスを作って保存しておくこともできますが、複数の文字列を配列や辞書形式で保存したい場合、Xcodeプロジェクトにデフォルトで用意されているInfo.plistを使うと便利です。

Info.plistに項目を追加する

例えば、名称とURLを持つ画像の情報を複数保存したい場合、下記のようにInfo.plistにImageListという項目をArray形式で追加し、その中にnameとurlという要素を持つDictionaryを登録していきます。このようにすることで、同じ要素を持つ複数の項目をInfo.plistに保存することができます。

Screen Shot 2018-02-03 at 11.14.28.png

Info.plistから情報を取り出す

下記のようにBundleを使用することで、Info.plistに保存した情報を取り出すことができます。

if let imageList = Bundle(for: type(of: self)).object(forInfoDictionaryKey: "ImageList") as? [[String: String]] {
    for image in imageList {
        print("name: " + image["name"]!)
        print("url: " + image["url"]!)
    }
}

実行結果

name: dog
url: https://example.com/dog
name: cat
url: https://example.com/cat
name: fish
url: https://example.com/fish
name: bird
url: https://example.com/bird
7
7
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
7
7