Swift 正在重置URLSession.shared凭据
我正在尝试使用URLSession.shared执行一些api请求(使用凭据),但它的行为与预期不符 当用户第一次输入他们的凭据时,我使用以下命令将其设置为会话的默认值Swift 正在重置URLSession.shared凭据,swift,Swift,我正在尝试使用URLSession.shared执行一些api请求(使用凭据),但它的行为与预期不符 当用户第一次输入他们的凭据时,我使用以下命令将其设置为会话的默认值 let credential = URLCredential(user: username, password: password, persistence: .forSession) URLCredentialStorage.shared.setDefaultCredential(credential, for: myProt
let credential = URLCredential(user: username, password: password, persistence: .forSession)
URLCredentialStorage.shared.setDefaultCredential(credential, for: myProtectionSpace)
然后,我将使用此命令发出第一个url请求。对于本例,假设请求正在尝试访问
这很好用,凭证会被传递,直到我需要用户注销为止。当我存储不同的凭据时,即使密码不正确,对的请求仍然会返回OK,并且似乎不会发出401质询
我尝试了以下所有方法,但似乎没有任何方法可以清除该特定URL的会话凭据
// Attempt #1: doesn't work
URLSession.shared.reset {
// I confirmed this eliminates all credentials in the URLCredentialStorage.shared
// store updated credentials and fire off new request here
}
// Attempt #2: doesn't work
URLCredentialStorage.shared.remove(credential, for: myProtectionSpace)
URLSession.shared.invalidateAndCancel()
// store updated credentials and fire off new request here
// Attempt #3: doesn't work
URLCredentialStorage.shared.remove(credential, for: myProtectionSpace)
URLSession.shared.finishTasksAndInvalidate()
// store updated credentials and fire off new request here
在第一次成功请求后,服务器似乎没有发出401质询,因此没有使用修改后的凭据。我是否因为这个原因而被迫使用自定义URLSession 您是否尝试过使用
URLCredentialStorage.shared.set(credential,for:myProtectionSpace)
而不是setDefault?我也尝试过,同样的结果我发现我必须调用它来“重置”会话,从而重置凭据。
// Attempt #1: doesn't work
URLSession.shared.reset {
// I confirmed this eliminates all credentials in the URLCredentialStorage.shared
// store updated credentials and fire off new request here
}
// Attempt #2: doesn't work
URLCredentialStorage.shared.remove(credential, for: myProtectionSpace)
URLSession.shared.invalidateAndCancel()
// store updated credentials and fire off new request here
// Attempt #3: doesn't work
URLCredentialStorage.shared.remove(credential, for: myProtectionSpace)
URLSession.shared.finishTasksAndInvalidate()
// store updated credentials and fire off new request here