2016-08-25 129 views
0

发布的数据我使用POST方法类似这样的得到错误在迅速

let login = ["user_name":usernameTextField.text,"password":passwordTextField.text] 
    //["user":"[email protected]", "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") 
} 

发送的数据,但我越来越喜欢

参数类型“错误信息[字符串:字符串] '不符合预期类型'AnyObject'

如果我给直接字符串它接受。如果我动态使用TextField,它不会来。我不知道我做了什么错误。

任何人请帮助解决这个问题?

在此先感谢。

+0

哪条线你得到实际的错误? – sbarow

+0

let“auth = try”NSJSONSerialization.dataWithJSONObject(login,options:.PrettyPrinted)at“login” –

+1

Unwarp textField的文本。即使它出现了相同的错误,也可以使用 – Apurva

回答

1

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

尝试这样做:

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

。 –

+0

@anushahrithi刚刚更新了我的答案,它应该已经'让登录= [“user_name”:用户名,“密码”:密码]' – sbarow

+0

超级。谢谢你这么多。它正在工作。 –

0

UITextField的文本属性返回一个可选的值,因此编译器无法将其转换为AnyObject。 您必须先解开optionals。

0

试试这个

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

这不会编译textfields文本返回一个可选项。 – sbarow

+0

但这里的问题不是可选值。 –

+0

你想把它扔进游乐场,并告诉我它是否没有问题? – sbarow