anusha hrithi anusha hrithi - 4 months ago 11
iOS Question

Getting error In posting Data in swift

I am sending the data using post method like this

let login = ["user_name":usernameTextField.text,"password":passwordTextField.text]
//["user":"", "pass":"ords_password"]

let url = NSURL(string: "http://localhost:8300")!

let session = NSURLSession.sharedSession()

let request = NSMutableURLRequest(URL: url)

do {
// JSON all the things
let auth = try NSJSONSerialization.dataWithJSONObject(login, options: .PrettyPrinted)

// Set the request content type to JSON
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

// The magic...set the HTTP request method to POST
request.HTTPMethod = "POST"

// Add the JSON serialized login data to the body
request.HTTPBody = auth

// Create the task that will send our login request (asynchronously)
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
// Do something with the HTTP response
print("Got response \(response) with error \(error)")

// Start the task on a background thread

} catch {
// Handle your errors folks...

But I am getting the error message like

Argument type '[String : String?]' does not conform to expected type ‘AnyObject’

If I give the direct string it is accepting. If I am giving dynamically using the TextFields it is not coming. I don’t know what is the mistake I have done.

Can anyone Please help to solve this issue?

Thanks in advance.


I think your issue is that you are putting optional strings into the dictionary.

Try doing this:

    let username = usernameTextField.text, 
    let password = passwordTextField.text else { 
        return print("Need username & password") 
let login = ["user_name": username,"password": password]