LoginSignup
15
13

More than 5 years have passed since last update.

API keyを.plistにStringで保存して隠す(例: Google Maps Api)

Posted at

API keyを毎回消してgithubに乗せるのは面倒なので、調べて書きました。
簡単に言うと、
1. apikey.plistを新しく作成,
2. apikeyをStringとして保存,
3. 使う場所で読み込む
4. apikey.plistを呼ぶヘルパークラスを作成
5. apikeyを返すメソッドを呼ぶ

1. apikey.plistファイルを作成

Screen Shot 2017-07-04 at 9.02.22 PM.png

2. apiKeyをStringとして保存

新しく作成した.plistにapikeyを追加

Screen Shot 2017-07-04 at 9.06.46 PM.png

3. .gitignoreファイルを作成して無視するファイルを書く

なんでもいいので、テキストエディタを開いて、.gitignoreファイルを新規作成して、
以下を入力してセーブ

CollectionView3/APIKey.plist
.gitignore

こうすると、APIKey.plistと.gitignoreのファイルが、githubに無視され、中身が変更されても認識されません。ただし一回プッシュした場合は消えないので、gitにすでに上がっていた場合は消してください。

何を無視するかはチームや自分次第だとは思いますが、
あまり変更がないファイル、なくてもプロジェクトが理解できるファイルとエラーログなどは無視してもいいのでは?

Pods/
Podfile.lock
***.xcworkspace

Screen Shot 2017-07-04 at 9.27.22 PM.png

4. apikey.plistを呼ぶヘルパークラスを作成

友達がすごく便利なヘルパークラスを作ったのでご紹介
https://github.com/Nismit

KeyManager.swift

struct KeyManager {

    private let keyFilePath = Bundle.main.path(forResource: "apiKey", ofType: "plist")

    func getKeys() -> NSDictionary? {
        guard let keyFilePath = keyFilePath else {
            return nil
        }
        return NSDictionary(contentsOfFile: keyFilePath)
    }

    func getValue(key: String) -> AnyObject? {
        guard let keys = getKeys() else {
            return nil
        }
        return keys[key]! as AnyObject
    }
}

apikeyが複数あるとすれば、その中からkeyを指定してValueを返してくれる。

5. apikeyを返すメソッドを呼ぶ

やり方はいくつかあると思うのですが、google.maps.apiを使った時は
appdelegateファイルの, 最初のapplicationメソッドの中に指定しました

AppDelegate.swift
//~

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // Google Maps API Key
        if let APIKEY = KeyManager().getValue(key: "apiKey") as? String {
            GMSServices.provideAPIKey(APIKEY)
            GMSPlacesClient.provideAPIKey(APIKEY)
        }

        return true
    }
//~

15
13
4

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
15
13