Ios 有没有办法保存swift keychain对象和nil?

Ios 有没有办法保存swift keychain对象和nil?,ios,swift,keychain,Ios,Swift,Keychain,当我试图保存字符串时,我看到我的代码失败了!或nil或使用swift钥匙链的任何对象 func setSharedPrefrences() { if (mainViewController != nil) { if (mainViewController.location_text != nil) { keychainSetSafe(mainViewController.location_text.text, key: StringCon

当我试图保存字符串时,我看到我的代码失败了!或nil或使用swift钥匙链的任何对象

func setSharedPrefrences()
{

    if (mainViewController != nil)
    {
        if (mainViewController.location_text != nil) {
            keychainSetSafe(mainViewController.location_text.text, key: StringConstans.keychain_lineName)
        }
    }
}

func keychainSetSafe(value: String!, key : String)
{
    if let nonNullValue = value
    {
        keychain.set(nonNullValue, forKey: key)
    }

}

func getSharedPrefrences()
{
    if (mainViewController != nil)
    {
        let gcmToken = keychain.get(StringConstans.keychain_gcmToken)
        if (gcmToken != nil) {
            mainViewController.userState.gcmToken = gcmToken
        }
    }
}
有没有办法存储这些类型,以便在应用程序从bg移动到fg并再次移动时进行恢复

//
// Keychain helper for iOS/Swift.
//
// https://github.com/marketplacer/keychain-swift
//
// This file was automatically generated by combining multiple Swift source files.
//


// ----------------------------
//
// KeychainSwift.swift
//
// ----------------------------

import Security
import Foundation

/**

A collection of helper functions for saving text and data in the keychain.

*/
public class KeychainSwift

为什么您希望存储在KeyChain中,而不仅仅是使用NSUserDefaults?正如@Michael所说,您为什么要使用KeyChain来实现这一点?无论如何,你不能存储零。如果某个特定值为nil,那么您应该从密钥链中删除相应的项,然后当您恢复该值时(如果该值不存在),您可以假定它是nil@Michael
NSUserDefaults
也适用于swift吗?当然可以。保存到NSUserDefaults要容易得多。为什么您希望存储在KeyChain中而不仅仅是使用NSUserDefaults?正如@Michael所说,为什么您要使用KeyChain?无论如何,你不能存储零。如果某个特定值为nil,那么您应该从密钥链中删除相应的项,然后当您恢复该值时(如果该值不存在),您可以假定它是nil@Michael
NSUserDefaults
也适用于swift吗?当然可以。保存到默认值要容易得多。