2016-11-07 18 views
10

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?

Trả lời

0

sự cố là do challenge.protectionSpace.serverTrust là không khi bạn cố gắng gỡ bỏ nó.

bạn nên unwrap serverTrust và xử lý nó là không. tôi đoán là khi serverTrust là nil challenge.error có một giá trị.

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { 

    if challenge.previousFailureCount > 0 { 
     completionHandler(Foundation.URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) 
    } else if let serverTrust = challenge.protectionSpace.serverTrust { 
     completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust)) 
    } else { 
     print("unknown state. error: \(challenge.error)") 
     // do something w/ completionHandler here 
    } 
} 
+0

Ứ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

+0

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

+0

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

0

Đây là cú pháp theo nhanh chóng 3.

Chỉ cần xác minh trước hết là trong đó một phần của phương pháp đại biểu nó vào

open func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void){ 

    var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling 

    var credential:URLCredential? 

    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { 
     credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) 

     if (credential != nil) { 
      disposition = URLSession.AuthChallengeDisposition.useCredential 
     } 
     else{ 
      disposition = URLSession.AuthChallengeDisposition.performDefaultHandling 
     } 
    } 
    else{ 
     disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge 
    } 

    if (completionHandler != nil) { 
     completionHandler(disposition, credential); 
    } 
} 
+0

Có hai vấn đề ở đây .. .first off khi tôi chạy phương thức loginUser của mình, nó chạy phương thức urlSession hai lần, lần đầu tiên nó đi tới 'disposition = URLSession.AuthChallengeDisposition.useCredential' rồi lần thứ hai nó đi tới' disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge' – user979331

+0

cũng như thế này dòng 'if (completionHandler! = nil) {' cho tôi một cảnh báo 'So sánh giá trị không tùy chọn kiểu '(URLSession.AuthChallengeDisposition, URLCredential?) -> Void' thành nil luôn trả về true ' – user979331

+0

bạn đã cố gắng in' giá trị authenticationMethod' lần thứ hai –

Các vấn đề liên quan