0
我需要你的幫助,因爲我不能使用這段代碼。 我在obj-c中使用它,現在我想用它與iOS Swift,但是當我模擬它,使用webData時有一個錯誤,因爲它是零,但我不知道如何解決它導致它的與我一直使用obj-c很長一段時間一樣。用iOS登錄錯誤Swift:致命錯誤:意外地發現零,同時展開一個可選值
好了,這是我的代碼:
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!){
NSLog("webData:\(webData)")
webData.length = 0
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
webData.appendData(data)
}
func connection(connection: NSURLConnection, didFailWithError error: NSError!){
NSLog("ERROR with theConenction")
}
func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace!) -> Bool{
return true
}
func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge!){
if challenge.previousFailureCount >= 3{
textResult = "this connection requires user & password"
connection.cancel()
} else {
NSLog("didRecieveAuthentication")
var credential:NSURLCredential = NSURLCredential.credentialWithUser(txt_user.text, password: txt_pass.text, persistence: NSURLCredentialPersistence.ForSession)
challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)
NSLog("Credential: \(credential)")
}
}
func connectionDidFinishLoading(connection: NSURLConnection!){
NSLog("DONE. Recieved Bytes: \(webData.length)")
NSLog("webData\n\(webData)")
var convertToStringData: NSString = NSString(data: webData, encoding: NSUTF8StringEncoding)
textResult = convertToStringData
NSLog("textResult:\n\(textResult)")
}
func validateUserCredentials(){
var txtURL: NSString = "http://ws.itteria.cat/leina.nsf"
var nodeContent:NSMutableString
var locationOfWebService: NSURL = NSURL.URLWithString(txtURL)
NSLog("web url = \(locationOfWebService)")
var theRequest: NSMutableURLRequest = NSMutableURLRequest(URL: locationOfWebService)
theRequest.addValue("text/html", forHTTPHeaderField: "Content-Type")
theRequest.HTTPMethod = "GET"
var connect: NSURLConnection = NSURLConnection.connectionWithRequest(theRequest, delegate: self)!
}
我打電話給FUNC ValidateCredentials,然後我用WEBDATA時出現此錯誤:
webData nil
fatal error: unexpectedly found nil while unwrapping an Optional value
WEBDATA在這裏宣佈:
class LoginViewController: UIViewController, UITextFieldDelegate, UIScrollViewDelegate, NSURLSessionDelegate{
let webData: NSMutableData = NSMutableData(bytes: nil, length: 0)
希望你能幫助我,因爲我不知道我還能做什麼:S
由於
如果我使用'VAR WEBDATA:NSMutableData'然後我不能使用'webData.length = 0'或'webData.appendData(數據)' - '?NSMutableData'沒有名爲'length'的成員。 – Norolim 2014-09-01 09:29:05
使用可選綁定(請參閱鏈接文檔):'if let webData = webData {...}'。在 – Antonio 2014-09-01 09:32:11
裏面加入你的代碼,這個不能解決這個問題,但是我已經修復了這個問題:) 'let webData:NSMutableData = NSMutableData(bytes:nil,length:0)' 無論如何;) – Norolim 2014-09-01 09:57:17