在 swift 中发布数据时出错

Getting error In posting Data in swift

我正在使用这样的 post 方法发送数据

let login = ["user_name":usernameTextField.text,"password":passwordTextField.text]
    //["user":"ords_user@gmail.com", "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)")
        print("Done.")
    })

    // Start the task on a background thread
    task.resume()

} catch {
    // Handle your errors folks...
    print("Error")
}

但我收到类似

的错误消息

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

如果我给出它正在接受的直接字符串。如果我使用 TextFields 动态地提供它就不会出现。我不知道我做错了什么。

任何人都可以帮助解决这个问题吗?

提前致谢。

我认为你的问题是你将可选字符串放入字典中。

尝试这样做:

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

UITextField 的文本 属性 returns 一个可选值,因此编译器无法将其转换为 AnyObject。 你必须先解包选项。

试试这个

let login = ["user_name":usernameTextField.text,"password":passwordTextField.text] as Dictionary<String, AnyObject>