如何在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)
    }