swift-如何从服务器获取JSON响应

时间:2018-08-29 08:38:58

标签: ios json swift swift4 urlsession

我正在将此数据发送到服务器,我希望它做出响应。尝试过此代码,但不起作用。

    let parameters = [ "imie" : (imie), "nazwisko" : (nazwisko), "telefon" : (telefon), "adres" : (adres), "miasto" : (miasto), "kod" : (kod), /*"powiat" : (powiat), "wojewodztwo" : (wojewodztwo),*/ "opis" : (selectedvalue)   ]


    let url = URL(string: "http://www.hetman.pl/post1.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setBodyContent(parameters)

    let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
        if error != nil{
            return
        }

        do{
            let t = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
            print(t as? String)
        } catch{
            print("Error 43 -> \(error)")
        }


    }

请求正确,服务器正在正确处理数据,但是响应给了我这个错误:

Error 43 -> Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}

问题是,如何从服务器取回数据?

2 个答案:

答案 0 :(得分:0)

为什么有内容类型?

// code 3840, data.length = 1 byte, so empty and no error
  1. request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")

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

删除第一个内容类型标题字段并仅尝试:

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

答案 1 :(得分:0)

请检查此网址的响应是否仅为JSON。您可能会收到XML或字符串响应。

如果收到 String 响应,请尝试以下行:

let stringResponse = String(data: data!, encoding: String.Encoding.utf8) as String!

如果收到 XML 响应,请尝试以下行:

let xmlDictionary = try XMLSerialization.xmlObject(with: data!) as? [String: Any]