ios - 如何从 URLCredentialStorage 中删除凭据

标签 ios swift authentication keychain

我可以存储和检索凭据,但无法删除它们。我在这里创建了一个简单的包装器,但清除方法不起作用。在我打电话清除后,凭证似乎仍然存在。我需要做什么来清除凭据?

class PasswordManager {
    static let shared = PasswordManager() // singleton instance

    private lazy var protectionSpace: URLProtectionSpace = {
        return URLProtectionSpace(host: "somehost.com",
                                  port: 0,
                                  protocol: "http",
                                  realm: nil,
                                  authenticationMethod: nil)
    }()

    private init() { }

    func password(for userID: String) -> String? {
        guard let credentials = URLCredentialStorage.shared.credentials(for: protectionSpace) else { return nil }
        return credentials[userID]?.password
    }

    func set(password: String, for userID: String) {
        let credential = URLCredential(user: userID, password: password, persistence: .permanent)
        URLCredentialStorage.shared.set(credential, for: protectionSpace)
    }

    func clear(for userID: String) {
        if let password = password(for: userID) {
            let credential = URLCredential(user: userID, password: password, persistence: .permanent)
            URLCredentialStorage.shared.remove(credential, for: protectionSpace)
        }
    }
}

最佳答案

为了胜利:

func clear(for userID: String) {
    guard let creds = URLCredentialStorage.shared.credentials(for: protectionSpace) else { return }
    guard let cred = creds[userID] else { return }
    URLCredentialStorage.shared.remove(cred, for: protectionSpace)
}

关于ios - 如何从 URLCredentialStorage 中删除凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49827490/

相关文章:

ios - 如何获取包含 UIImage 的 NSAttributedString 的自定义文本等效项?

arrays - 将字符串拆分为数组 string.components(separtedBy : ",") consumes more time

powershell - 如何使用具有集成安全性的 Powershell 连接 Azure Paas 数据库

iphone - UIViewController 互通,有什么方法可以强制 UIViewController 更新吗?

iOS CABasicAnimation 彩色动画不生效

iphone - 以编程方式在底部的 UIToolbar

ios - 我可以创建一个我所有的 View Controller 都可以访问的类吗

ios - Swift:在 UITabView 之间传递数据并允许全局访问数据

java - 使用 Htmlunit,按钮 click() 不起作用;

asp.net-mvc - 使用 ASP.NET MVC 的 Restful 基本身份验证