Search code examples
jsonswiftios9

Swift 2 & json post issue


I am still fairly new to working with swift and json and I'm struggling with the following and getting an error message on the line: let param = jsonObj.dataUsingEncoding(NSUTF8StringEncoding). The error is:- value of type 'String : NSString' has no dataUsingEncoding

        let url = "{URLADDRESS/PHP FILE}"
        let request = NSMutableURLRequest(URL: NSURL(string: url)!)
        let session = NSURLSession.sharedSession()
        let jsonObj = ["usEmail":email, "usFullName":name, "usAddress":address, "usArea/District":area, "usPostTown":town, "usPostZip":zip, "usContactNum":number]

        request.HTTPMethod = "POST"

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

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

If anyone can assist me and tell what the problem is I would appreciate it very much.

Thanks


Solution

  • method .dataUsingEncoding is exist for String type, you have to make not a [String:NSString] dictionary, but a String. So you have do it like this:

    result: XCode playground example

     let email = "@gmail"
     let  name = "Kostia"
     let address = "Home"
     let area = "UA"
     let town = "Kiev"
     let zip = "11111"
     let number = "123456"
    
     let stringJson = "{\"usEmail\":\"\(email)\",\"usFullName\":\"\(name)\",\"usAddress\":\"\(address)\",\"usArea/District\":\"\(area)\",\"usPostTown\":\"\(town)\",\"usPostZip\":\"\(zip)\",\"usContactNum\":\"\(number)\",}"
     let data = stringJson.dataUsingEncoding(NSUTF8StringEncoding)!
     do {
         let jsonObj = try NSJSONSerialization.JSONObjectWithData(data,      options: []) as? [String:String]
     } catch (let error as NSError) {
         print("ERROR be like: ", error)
     }