在Swift中,didReceiveAuthenticationChallenge代理未被调用

3

我正在尝试使用NSURLConnection进行一个示例项目。

 import Foundation
 import UIKit
    class loginVC: ViewController, UITextFieldDelegate, NSURLConnectionDelegate, NSURLConnectionDataDelegate{
        var webData: NSMutableData!

        override func viewDidLoad() {
            super.viewDidLoad()
            webData = NSMutableData()
            callWebService("testdentist@gmail.com", Password:"1")

        }

        func callWebService(userName:NSString, Password:NSString){

            var strURl: NSURL = NSURL .URLWithString("")
            var request: NSMutableURLRequest = NSMutableURLRequest(URL: strURl, cachePolicy:NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval:60.0)
            var postString: NSString = ""
            postString = postString.stringByAppendingFormat("username=%@&password=%@", userName,Password)
            request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
            request.HTTPMethod = ""
            var connection: NSURLConnection = NSURLConnection(request: request, delegate:self)
            connection.start()
        }

        //NSURLConnection webservice
        func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!){
           // webData.length = 0
            println("response")
        }

        func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
           println(data.length)
            webData .appendData(data)
        }

        func connection(connection: NSURLConnection, didFailWithError error: NSError!){
            println("error in connection")
        }

        func connectionDidFinishLoading(connection: NSURLConnection!){

            var response: NSString = NSString(data: webData, encoding: NSUTF8StringEncoding)

            println("response:\(response)")
            if response != ""{

            }

        }
        func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge!){
            var authentication: NSURLCredential = NSURLCredential.credentialWithUser("", password:"", persistence: NSURLCredentialPersistence.ForSession)
        }  
    }

似乎所有的委托都被调用了,除了didReceiveAuthenticationChallenge委托方法。我错过了什么。任何帮助都将不胜感激。提前致谢。

你不需要在连接上调用start() -- 只有在使用initWithRequest:delegate:startImmediately:并将startImmediately设置为false时才需要调用start()。 - KerrM
2个回答

2

对于iOS 8及以上版本,您必须实现connection(_:willSendRequestForAuthenticationChallenge:)。在iOS 8中不会调用connection:didReceiveAuthenticationChallenge:方法,该方法仅适用于旧操作系统。

因此,为了在iOS 8及以上版本中提供身份验证,您必须实现上述方法,并在其中调用一个挑战响应器方法(NSURLAuthenticationChallengeSender protocol):

useCredential:forAuthenticationChallenge:

continueWithoutCredentialForAuthenticationChallenge: 

cancelAuthenticationChallenge:

performDefaultHandlingForAuthenticationChallenge: 

rejectProtectionSpaceAndContinueWithChallenge:

didReceiveAuthenticationChallengeNSURLConnectionDelegate协议中的一个方法,而除了didFailWithError之外的所有方法都是NSURLConnectionDataDelegate协议中的方法。您是否在控制器中实现了这两个协议?如果您发布了整个类的代码,可能会更有帮助。


我已经实现了两个协议,但它仍然没有被调用? - user3823935
你的部署目标是什么?仅限于iOS8吗?didReceiveAuthenticationChallenge在iOS8中已被弃用。 - KerrM
有没有其他的身份验证方式? - user3823935
请看我的编辑 - 您必须实现 connection(_:willSendRequestForAuthenticationChallenge:) 方法,并在其中调用一个 challenge-responder 方法 (NSURLAuthenticationChallengeSender 协议):useCredential:forAuthenticationChallenge:continueWithoutCredentialForAuthenticationChallenge:cancelAuthenticationChallenge:performDefaultHandlingForAuthenticationChallenge:rejectProtectionSpaceAndContinueWithChallenge: - KerrM
当我添加该协议时,出现“loginVC不符合NSURLAuthenticationChallengeSender协议”的错误。 - user3823935

0

我认为这个问题对于新的Swift 3.0来说不是用那些术语描述的。

我有一个类似的问题,在xcode7/ios7-8-9/Swift 2.2下正常工作的代码。

迁移后产生了以下问题:

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

...

但是并不起作用。

手动重写:

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


}

现在它确实可以工作了。 这是我的意见。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接