2016-08-25 132 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