微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Swift中创建NSMutableDictionary?

我正在尝试创建一个NSMutableDictionary来使用iOS中的密钥链,但是我收到以下错误.

Could not find an overload for ‘init’ that accepts the supplied arguments

这是我正在使用的代码

var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecclassGenericPassword,service,userAccount,kcfBooleanTrue,kSecMatchLimitOne],forKeys: [kSecclass,kSecAttrService,kSecAttrAccount,kSecReturnData,kSecMatchLimit])

知道是什么原因引起的吗?

完整的代码

import UIKit
import Security

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

class KeychainService: NSObject {

    class func savetoken(token: Nsstring) {
        self.save(serviceIdentifier,data: token)
    }

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

        return token
    }

    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: [kSecclassGenericPassword,dataFromString],kSecValueData])

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

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

    class func load(service: Nsstring) -> Nsstring? {
        // Instantiate a new default keychain query
        // Tell the query to return a result
        // Limit our results to one item
        var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecclassGenericPassword,kSecMatchLimit])

        var dataTypeRef :Unmanaged<AnyObject>?

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

        let opaque = dataTypeRef?.toOpaque()

        var contentsOfKeychain: Nsstring?

        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
    }
}

解决方法

对于您的代码,您可以使用NSDictionary:

var keychainObjects = NSArray(objects:"\(kSecclassGenericPassword)",dataFromString)
    var keychainValues = NSArray(objects:"\(kSecclass)","\(kSecAttrService)","\(kSecAttrAccount)","\(kSecValueData)")
    let keychainQuery = NSDictionary(objects: keychainObjects,forKeys: keychainValues)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐