mohdomar
mohdomar

Reputation: 49

Swift 2.0 JSON Dictionary issue

So this code below is basically trying to pass a dictionary of type (String, String) as a JSON object to my server. I'm getting the error : Argument type '[String : String?]' does not conform to expected type 'AnyObject'. This error I'm getting at the line where NSJSONSerialization is called, and the name of the dictionary is being underlined and said to be causing the issue.

I'm unaware as to how to proceed or change the code. I have tried to add an 'as Dictionary ' at the end of the var decleration but that doesn't seem to be able to convert the dictionary to that type

Any help would be greatly appreciated

 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
    }

Upvotes: 0

Views: 1400

Answers (2)

matthew
matthew

Reputation: 61

I had the same problem. Just put 'Exclamation point' for each String value to unwrap them correctly. Like this:

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"]

Upvotes: 0

vadian
vadian

Reputation: 285240

The error message says there are optional strings in the dictionary.

... type '[String : String?]'

Any key and any value in a dictionary must not be nil.
Make sure that the optional strings are unwrapped.

Upvotes: 2

Related Questions