如何从 URL 注册表存储中删除凭据



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

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

若要删除可同步的凭据,必须在删除函数中提供一个选项。

URLCredentialStorage.shared.remove(cred, for: protectionSpace, options: [NSURLCredentialStorageRemoveSynchronizableCredentials: true])

这为我删除了未删除的凭据。

最新更新