Tôi đang thực hiện URLSession, nhưng URL yêu cầu thông tin đăng nhập.Swift 3 URLSession với URLCredential không hoạt động
Tôi có toàn bộ phương pháp này ở đây đó là cố gắng để làm một URLSession với URLCredentials:
func loginUser(_ username: String, password: String, completion: @escaping (_ result: Bool) -> Void)
{
//Create request URL as String
let requestString = String(format:"%@", webservice) as String
//Covert URL request string to URL
guard let url = URL(string: requestString) else {
print("Error: cannot create URL")
return
}
//Convert URL to URLRequest
let urlRequest = URLRequest(url: url)
print(urlRequest)
//Add the username and password to URLCredential
credential = URLCredential(user:username, password:password, persistence: .forSession)
//Setup the URLSessionConfiguration
let config = URLSessionConfiguration.default
//Setup the URLSession
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
//Prepare the task to get data.
let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
DispatchQueue.main.async(execute: {
if(error == nil)
{
completion(true)
}
else
{
completion(false)
}
})
})
//Run the task to get data.
task.resume()
}
và đây là phương pháp URLSessionDelegate tôi:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.previousFailureCount > 0
{
completionHandler(Foundation.URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
else
{
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!))
}
}
/**
Requests credentials from the delegate in response to an authentication request from the remote server.
*/
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential,credential)
}
tôi nhận thấy khi tôi gỡ lỗi này trong delegate này phương pháp:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.previousFailureCount > 0
{
completionHandler(Foundation.URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
else
{
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!))
}
}
Phương pháp này được gọi hai lần và khi nó dòng này của mình cho lần thứ hai:
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!))
tôi nhận được lỗi này:
fatal error: unexpectedly found nil while unwrapping an Optional value
và sau đó bị treo ứng dụng của tôi! Làm thế nào để sửa lỗi này?
Ứng dụng không sụp đổ nữa, nhưng khi tôi cố gắng chạy phương pháp đăng nhập không có vấn đề gì là tôi đặt vào (đúng hay sai) nó đi trực tiếp vào dòng này 'print (" unknown state. error: \ (challenge.error) ")' – user979331
Sau khi gỡ lỗi, nó sẽ goto dòng này 'completionHandler (Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential (trust: serverTrust)) 'nhưng sau đó bằng cách nào đó chạy phương thức này một lần nữa và sau đó goto dòng này:' print ("trạng thái không xác định. lỗi: \ (challenge.error) ")' – user979331
bạn có chắc là không có lỗi đánh máy trong câu lệnh in? '\ (challenge.error)' nên được thay thế bởi đối tượng lỗi thực tế – Casey