LoginSignup
12
8

More than 5 years have passed since last update.

Swift ライブラリKeychainAccessの利用例

Posted at

ライブラリKeychainAccess利用

https://github.com/kishikawakatsumi/KeychainAccess/
アプリを削除した後にもデータを残して、再インストールした後に使いたい、iCloud Keychain で値を保存しておきたい場合など

導入

インスタンス生成の際にキーが必要なのでBundleIdentifierをキーとしています。
もちろん任意の文字列が使えます。

import KeychainAccess

var keychain: Keychain {
    guard let identifier = Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as? String else { return Keychain(service: "") }
    return Keychain(service: identifier)
}

保存

キーを指定して値を保存

do {
    try? keychain.set(value, key: "key")
} catch {
    // エラー処理
}

参照

キーを指定して値を参照
Stringの例
エラーが発生することもあるのでオプショナル型にしておくのが無難っぽい

var stringValue: String? {
    do {
        return try keychain.get("key")
    } catch {
        return nil
    }
}
12
8
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
12
8