发布请求始终由可选文本包装 [英] Post request always wrapped by optional text
问题描述
我有一个非常类似的问题,例如为什么http post请求体总是被Swift应用程序中的Optional文本包裹
但我无法将此线程的解决方案应用到我的代码中,因为我不知道有一个request.setValue。
有谁知道我需要做什么才能摆脱Optional?
我的代码:
I have a very similar problem like in Why the http post request body always wrapped by Optional text in the Swift app but I can´t apply the solution from this thread to my code, because I don´t have a request.setValue. Does anyone know what I need to do to get rid of the Optional? My Code:
@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()
推荐答案
首先从UITextField获取文本时必须解包该值,因为 text
U的属性ITextField
允许 nil
You must unwrapping the value when get text from UITextField first, because the text
property of UITextField
allow nil
let username = UsernameTextField.text!
let password = PasswordTextField.text!
解释更多
当您打开UITextField的文本
时,用户名
和密码
将是而不是
变量。
代码比较空应为:
When you unwrap the text
of the UITextField, the username
and password
will be not nil
variable.
The code compare empty should be:
if(username.isEmpty || password.isEmpty) {return }
如果你没有打开,当你使用这个\(用户名)
,您尝试将 nil
able对象转换为字符串,因此字符串结果将附加可选文本。
If you does not unwrap, when you use this "\(username)"
, your are try to convert a nil
able object to string, so the string result will be appended with a "Optional" text.
解决Content-Type请求的问题
将此行粘贴到您的代码中。我不相信你没有 setValue
方法。
Paste this line to your code. I don't believe that you do not have setValue
method.
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
这篇关于发布请求始终由可选文本包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!