我正在尝试使用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委托方法。我错过了什么。任何帮助将不胜感激。谢谢提前
答案 0 :(得分:1)
对于iOS 8及更高版本,您必须实施connection(_:willSendRequestForAuthenticationChallenge:)
。在iOS8中不调用connection:didReceiveAuthenticationChallenge:
,仅在较旧的操作系统中调用NSURLAuthenticationChallengeSender protocol
。
因此,要在iOS8及更高版本中提供身份验证,请实现上述方法,并且必须调用其中一个质询 - 响应方法(useCredential:forAuthenticationChallenge:
continueWithoutCredentialForAuthenticationChallenge:
cancelAuthenticationChallenge:
performDefaultHandlingForAuthenticationChallenge:
rejectProtectionSpaceAndContinueWithChallenge:
):
didReceiveAuthenticationChallenge
didFailWithError
是NSURLConnectionDelegate
上的方法,而其他方法({{1}}除外)都是NSURLConnectionDataDelegate
方法。您是否在控制器中实现了这两种协议?如果您发布了所有课程代码,这可能会有所帮助。
答案 1 :(得分: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) {
}
现在它开始工作了。 我的两分钱。