swift - 尝试从 KeyChain 获取值时获取可选 ("")

标签 swift nsstring keychain option-type

当我尝试获取我的 keyChain 值时,它返回一个包含以下内容的字符串:

Optional("[thing in the KeyChain]")

因此,我尝试使用循环删除“可选”:

var str = KeychainService.loadToken()

for(var i = 0; i < 9 ; i++)
{
    str[i] = ""
}

但我得到一个错误:NSString 没有名为“下标”的成员

KeychainService 类:

import Foundation
import Security

let serviceIdentifier = "MySerivice"
let userAccount = "authenticatedUser"
let accessGroup = "MySerivice"

// Arguments for the keychain queries
let kSecClassValue = kSecClass.takeRetainedValue() as NSString
let kSecAttrAccountValue = kSecAttrAccount.takeRetainedValue() as NSString
let kSecValueDataValue = kSecValueData.takeRetainedValue() as NSString
let kSecClassGenericPasswordValue = kSecClassGenericPassword.takeRetainedValue() as NSString
let kSecAttrServiceValue = kSecAttrService.takeRetainedValue() as NSString
let kSecMatchLimitValue = kSecMatchLimit.takeRetainedValue() as NSString
let kSecReturnDataValue = kSecReturnData.takeRetainedValue() as NSString
let kSecMatchLimitOneValue = kSecMatchLimitOne.takeRetainedValue() as NSString

class KeychainService: NSObject {

/**
* Exposed methods to perform queries.
* Note: feel free to play around with the arguments
* for these if you want to be able to customise the
* service identifier, user accounts, access groups, etc.
*/
internal class func saveToken(token: NSString) {
    self.save(serviceIdentifier, data: token)
}

internal class func loadToken() -> NSString? {
    var token = self.load(serviceIdentifier)

    return token
}

/**
* Internal methods for querying the keychain.
*/
private class func save(service: NSString, data: NSString) {
    var dataFromString: NSData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

    // Instantiate a new default keychain query
    var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])

    // Delete any existing items
    SecItemDelete(keychainQuery as CFDictionaryRef)

    // Add the new keychain item
    var status: OSStatus = SecItemAdd(keychainQuery as CFDictionaryRef, nil)
}

private class func load(service: NSString) -> String? {
    // Instantiate a new default keychain query
    // Tell the query to return a result
    // Limit our results to one item
    var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

    var dataTypeRef :Unmanaged<AnyObject>?

    // Search for the keychain items
    let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)

    let opaque = dataTypeRef?.toOpaque()

    var contentsOfKeychain: String?

    if let op = opaque? {
        let retrievedData = Unmanaged<NSData>.fromOpaque(op).takeUnretainedValue()

        // Convert the data retrieved from the keychain into a string
        contentsOfKeychain = NSString(data: retrievedData, encoding: NSUTF8StringEncoding)
    } else {
        println("Nothing was retrieved from the keychain. Status code \(status)")
    }

    return contentsOfKeychain
    }
}

我只是不想删除 str 周围的 Optional 东西 或者有更好的方法吗?

我从以下位置获取此代码:

http://matthewpalmer.net/blog/2014/06/21/example-ios-keychain-swift-save-query/

最佳答案

你得到 Optional("") 因为可选值没有被解包。您需要在对象之后放置一个 ! 并且您将不会再获得 Optional("") 位。我会向您展示代码,但您没有向我们展示 print() 语句。我在下面制作了一些示例,我认为它们会重现该问题,但我还没有尝试过。

var value:String?
value = "Hello, World"

print("The Value Is \(value)") // Prints "The Value Is Optional(Hello, World)"
print("The Value Is \(value!)")// Prints "The Value Is Hello, World"

我希望这能回答您的问题或至少为您指明正确的方向,只需询问您是否需要更多信息或更好的示例。

关于swift - 尝试从 KeyChain 获取值时获取可选 (""),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25488162/

相关文章:

swift - 如何快速连接字符串中的 "+"运算符

ios - Keychain 中的 SecItemCopyMatching 和 kSecAttrAccessible

ios - 使用用户 _www 或守护程序设置 macOS 钥匙串(keychain)搜索列表

ios - iOS keychain 技术用什么比较合适

iphone - 大小和字体 :forwidth:linebreakmode

swift - 有人能告诉我为什么我一直收到错误 "unexpected non-void return value in void function"

使用 GCDAsyncUdpSocket 的 iOS swift 应用程序

ios - 如何通过 UnsafePointer<Int32> 创建 Int32?

iphone - 如何获取两个单词之间的 NSString?

ios - NSRegularExpression 无法正常工作