[英]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")
}
但是我收到了這樣的錯誤消息
參數類型'[String:String?]'與預期類型'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
的text屬性返回一個可選值,因此編譯器無法將其轉換為AnyObject。 您必須先拆開可選組件。
嘗試這個
let login = ["user_name":usernameTextField.text,"password":passwordTextField.text] as Dictionary<String, AnyObject>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.