pankaj
pankaj

Reputation: 8338

Get values from uitextfield without optional

I need to get values from a uitextfield but I am getting error unless I declare it optional. When I declare it as optional, optional is prefixed to values and saved to database through web services. I am using it like following:

let request = NSMutableURLRequest(URL: NSURL(string: ConstantStruct.kURLRegisterUser)!)
        request.HTTPMethod = "POST"
        let postString = "first_name=\(txtFName?.text)&last_name=\(txtLName?.text)&email=\(txtEmail?.text)"
        print(postString)
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        

Following query is running on server:

insert into users(firstname, lastname, email)
values('Optional("pan")', 'Optional("sach")', 'Optional("[email protected]")'

Is there a way by which I can remove optional from string?

Upvotes: 0

Views: 186

Answers (1)

keithbhunter
keithbhunter

Reputation: 12324

Use the if statement below to unwrap the optional and place the value into fName, lName and email.

if let fName = txtFName?.text,
   let lName = txtLName?.text,
   let email = txtEmail?.text {
    let request = NSMutableURLRequest(URL: NSURL(string: ConstantStruct.kURLRegisterUser)!)
        request.HTTPMethod = "POST"
        let postString = "first_name=\(fName)&last_name=\(lName)&email=\(email)"
        print(postString)
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
}

Upvotes: 1

Related Questions