Post request always wrapped by optional text

2019-08-09 09:08发布

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()

1条回答
劫难
2楼-- · 2019-08-09 09:28

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!

Explain more

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 }

If you does not unwrap, when you use this "\(username)", your are try to convert a nilable object to string, so the string result will be appended with a "Optional" text.

To Solve problem with Content-Type for request

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")
查看更多
登录 后发表回答