如何在 GitHub for iOS (SWIFT) 项目中隐藏 API 密钥?

问题描述:

您好,我正在尝试在 GitHub 上发布一个 iOS (SWIFT) 个人项目,但我害怕与所有人共享我的 API 私有密钥和秘密.

Hello I'm trying to publish a iOS (SWIFT) personal project in GitHub but I'm afraid of sharing my private API keys and secrets with everybody.

我正在使用解析,所以我在我的 AppDelegate 中有这样的内容:

I'm using parse so I have in my AppDelegate something like this:

let applicationId = "mySecretApplicationId"
let clientKey = "mySecretClientKey"
Parse.setApplicationId(applicationId!, clientKey: clientKey!)

我想隐藏mySecretApplicationId"和mySecretClientKey",我的项目中是否有可以放置这些变量的私人位置或目录?

I would like to hide "mySecretApplicationId" and "mySecretClientKey", is there private place or directory in my project where I can put this variables?

谢谢!

您可以使用 .plist 文件来存储所有重要的密钥.将此文件放入您的 .gitignore 文件中非常重要.

You can use a .plist file where you store all your important keys. It is very important to put this file into your .gitignore file.

就您而言,您需要像这样设置 keys.plist 文件:

In your case, you need to set your keys.plist file like this:

并在您的 AppDelegate 中使用它,如下所示:

And use it inside your AppDelegate as follows:

    var keys: NSDictionary?

    if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
        keys = NSDictionary(contentsOfFile: path)
    }
    if let dict = keys {
        let applicationId = dict["parseApplicationId"] as? String
        let clientKey = dict["parseClientKey"] as? String

        // Initialize Parse.
        Parse.setApplicationId(applicationId!, clientKey: clientKey!)
    }

SWIFT 3 更新:

SWIFT 3 Update:

 if let path = Bundle.main.path(forResource: "Keys", ofType: "plist") {
        keys = NSDictionary(contentsOfFile: path)
    }