0

I use this code,

let username = usernameText.text
let pass = passTxt.text
let pass2 = pass2Txt.text

let myUrl = NSURL(string: "http://192.168.1.6/ff/jsonsignup.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let postString = "username=\(username)&password=\(pass)&c_password=\(pass2)";

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if error != nil
    {
        print("error=\(error)")
        return
    }

   print("response = \(response)")

    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    print("responseString = \(responseString)")


           let myJSON = try!NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary

        if let parseJSON = myJSON as NSDictionary! {

        var firstNameValue = parseJSON["username"] as? String
        print("Username: \(firstNameValue)")
    }

}

task.resume()

responseString

Username: {"username":"Optional(\"ttttt\")"}

Optional extra added phrase

BUT

I went, as I want to get sent

{"username":"ttttt"}

I wonder where the error making ?

1
  • Try this: print("Username: \(firstNameValue!)") Commented Nov 17, 2015 at 11:21

1 Answer 1

1

You are getting the Optional keyword because when you get any data out of a dictionary it will always give you an Optional.

Optional means it may contain the object or it may contain nil. Just a safer way of programming

Just Unwrap the optional using if let statement

   if let firstNameValue = parseJSON["username"] as? String
   {
      print("Username: \(firstNameValue)")
   }
Sign up to request clarification or add additional context in comments.

1 Comment

It's like the following while recording to the database. I think about what is not told

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.