2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【iOS】APIキーをGitHubに公開せず安全に管理する方法

Posted at

【iOS】APIキーをGitHubに公開せず安全に管理する方法(Secrets.plist + .gitignore)

💡 はじめに

iOSアプリでAPIを使うとき、APIキーをコードに直接書くと GitHubに公開されてしまうリスクがあります。

この記事では、Secrets.plist + .gitignore を使って、APIキーをGitHubにアップせず、安全にアプリで使う方法を解説します。


🧩 今回やること

  • Secrets.plist にAPIキーを保存
  • .gitignore でGit管理外にする
  • Swiftで安全に読み込む

🔧 ① Secrets.plist を作成する

  1. Xcodeでプロジェクトを開く
  2. 右クリック → New File...
  3. Property List を選んで作成
  4. ファイル名を Secrets.plist にする
  5. 中身を以下のように記述:
<dict>
    <key>WeatherAPIKey</key>
    <string>YOUR_API_KEY_HERE</string>
</dict>

🚫 ② .gitignore に追加してGitHubに公開しないようにする

.gitignore ファイルに以下を追記:

NyankoWeather/Secrets.plist

もしすでにGit管理されていた場合は、次のコマンドで除外:

git rm --cached NyankoWeather/Secrets.plist
git commit -m "Remove Secrets.plist from Git tracking"

🧪 ③ SwiftからAPIキーを読み込む

以下の関数を作って、.plistからキーを読み込みます:

func loadAPIKey() -> String? {
    guard let path = Bundle.main.path(forResource: "Secrets", ofType: "plist"),
          let dict = NSDictionary(contentsOfFile: path),
          let apiKey = dict["WeatherAPIKey"] as? String else {
        return nil
    }
    return apiKey
}

使い方:

if let apiKey = loadAPIKey() {
    print("APIキー: \(apiKey)")
} else {
    print("APIキーの読み込みに失敗しました")
}

✅ まとめ

やったこと 効果
Secrets.plist作成 APIキーを安全に保存
.gitignore設定 GitHubに公開されない
Swiftで読み込み アプリで利用可能

🐱 おわりに

にゃんこ天気予報🐾の開発をしながら学んだベストプラクティスでした!

「GitHubに秘密のキーを載せたくない…」という人の参考になれば嬉しいです。

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?