我是iOS新手。我需要在本地保存数据。在android中我们可以在sharedPreferences中保存数据。并且开发人员可以清除整个共享首选项,也可以删除/删除特定键。
我正在使用钥匙串。但现在我想删除/删除一个键。但我对如何做到这一点有疑问。这是我从SO获得的钥匙串代码。
public class KeychainService: NSObject {
static let USER_PIN : String = "USER_PIN"
static let LOGGEDIN_ID : String = "LOGGEDIN_ID"
static let USER_NAME : String = "USER_NAME"
static let IS_USER_LOGGEDIN : String = "IS_USER_LOGGEDIN"
static let IS_APP_SETTINGS_DOWNLOADED : String = "IS_APP_SETTINGS_DOWNLOADED"
static let APP_SETTINGS_DOWNLOADED : String = "APP_SETTINGS_DOWNLOADED"
static let APP_NAME : String = "APP_NAME"
class func iterateKeychainItems(log: Bool, delete: Bool) {
let secItemClasses = [
kSecClassGenericPassword,
kSecClassInternetPassword,
kSecClassCertificate,
kSecClassKey,
kSecClassIdentity
]
if (log) {
for secItemClass in secItemClasses {
let query: [String: Any] = [
kSecReturnAttributes as String: kCFBooleanTrue,
kSecMatchLimit as String: kSecMatchLimitAll,
kSecClass as String: secItemClass
]
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status == noErr {
print(result as Any)
}
}
print("AppUsageMetadata.iterateKeychainItems ended.")
}
if (delete) {
for secItemClass in secItemClasses {
let dictionary = [kSecClass as String:secItemClass]
SecItemDelete(dictionary as CFDictionary)
}
}
}
class func save(key: String, data: Data) -> OSStatus {
let query = [
kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : key,
kSecValueData as String : data ] as [String : Any]
SecItemDelete(query as CFDictionary)
return SecItemAdd(query as CFDictionary, nil)
}
class func load(key: String) -> Data? {
let query = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccount as String : key,
kSecReturnData as String : kCFBooleanTrue,
kSecMatchLimit as String : kSecMatchLimitOne ] as [String : Any]
var dataTypeRef: AnyObject? = nil
let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)
if status == noErr {
return dataTypeRef as! Data?
} else {
return nil
}
}
class func createUniqueID() -> String {
let uuid: CFUUID = CFUUIDCreate(nil)
let cfStr: CFString = CFUUIDCreateString(nil, uuid)
let swiftString: String = cfStr as String
return swiftString
}
}
extension Data {
init<T>(from value: T) {
var value = value
self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
}
func to<T>(type: T.Type) -> T {
return self.withUnsafeBytes { $0.pointee }
}
}
所以现在告诉我如何删除一个键/项目。例如,我想 删除IS_USER_LOGGEDIN键。怎么做?请帮帮我
答案 0 :(得分:0)
Theres是一个很好的包装器,用于访问GitHub上的系统密钥链:
只需使用&#34; setPassword&#34;和&#34; deletePassword&#34;满足您的需求。
答案 1 :(得分:-1)
您可以像共享偏好设置一样使用 UserDefaults 对于 Swift 3: 对于使用键设置字符串值 UserDefaults.standard.set(“2”,forKey:“LOGINID”)
使用key获取字符串值 让LoginID = UserDefaults.standard.string(forKey:“LOGINID”)!
按键删除 UserDefaults.standard.removeObject(forKey:“LOGINID”)
适用于Swift2.2 let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(“2”,forKey:“LOGINID”)