我有一个非常类似的问题,例如Why the http post request body always wrapped by Optional text in the Swift app 但我无法将此线程的解决方案应用于我的代码,因为我没有request.setValue。 有谁知道我需要做什么来摆脱可选? 我的代码:
@IBAction func LoginButtonTapped(sender: UIButton) {
let username = UsernameTextField.text
let password = PasswordTextField.text
if(username!.isEmpty || password!.isEmpty) {return; }
let request = NSMutableURLRequest (URL: NSURL(string: "http://myip/loginregister.php")!)
request.HTTPMethod = "POST"
let postString = "username=\(username)&password=\(password)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else {
// check for fundamental networking error
print("error=\(error)")
return
}
let data = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
let success = json["success"] as? Int // Okay, the `json` is here, let's get the value for 'success' out of it
print("Success: \(success)")
} else {
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) // No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError) // Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
答案 0 :(得分:1)
首先从UITextField获取文本时必须展开值,因为text
的{{1}}属性允许UITextField
nil
解释更多
当您打开UITextField的let username = UsernameTextField.text!
let password = PasswordTextField.text!
时,text
和username
将是password
变量。
代码比较空应该是:
not nil
如果你没有打开,当你使用这个if(username.isEmpty || password.isEmpty) {return }
时,你会尝试将"\(username)"
能力对象转换为字符串,因此字符串结果将附加一个“可选”文本。 / p>
解决Content-Type for request
的问题将此行粘贴到您的代码中。我不相信你没有nil
方法。
setValue