2015-09-13 91 views
0

因此,下面的代碼基本上試圖將類型(String,String)的字典作爲JSON對象傳遞給我的服務器。我收到錯誤: 參數類型'[String:String?]'不符合預期類型'AnyObject'。我在調用NSJSONSerialization的那一行收到了這個錯誤,並且字典的名字被強調並且被認爲是造成這個問題的原因。Swift 2.0 JSON字典問題

我不知道如何繼續或更改代碼。我試圖在VAR decleration的末尾添加「作爲解釋」,但似乎並沒有能夠字典轉換成該類型

任何幫助,將不勝感激

var param = ["TeacherID":"1000", "Name":self.firstName.text, "PhoneNo":self.phoneNumber.text, "Email":self.email.text, "Nationality":nationaility, "Gender":self.gender.text, "Type":"True", "HighestQualification":self.heq.text, "CurrentlyWorking":"True", "CurrentlyStudying":"False"] 


    let request = NSMutableURLRequest(URL: NSURL(string: "http://1.1.1.1:8080/signup")!) 

    let session = NSURLSession.sharedSession() 
    request.HTTPMethod = "POST" 
    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
    request.addValue("application/json", forHTTPHeaderField: "Accept") 

    do { 
     request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param, options:[]) 
    } catch { 
     print(error) 
     request.HTTPBody = nil 
    } 

回答

2

錯誤消息表示字典中有可選字符串。

...類型 '[字符串:字符串]'

在字典中的任何鍵和任意值不能nil
確保可選字符串已解包。

0

我有同樣的問題。只需爲每個字符串值添加「感嘆號」即可正確打開它們。像這樣:

var param = ["TeacherID":"1000", "Name":self.firstName.text!, "PhoneNo":self.phoneNumber.text!, "Email":self.email.text!, "Nationality":nationaility, "Gender":self.gender.text!, "Type":"True", "HighestQualification":self.eq.text!, "CurrentlyWorking":"True", "CurrentlyStudying":"False"] 
+0

if self.firstName.text ==零應用程序將簡單地崩潰... – user3441734