使用URLSession发布数据

时间:2018-03-21 16:32:05

标签: swift nsurlsession

当我从Alamofire尝试然后它工作正常但是当我尝试从URLSESSION Swift 4解决时,我得到了错误的回答。 我检查了邮递员,这是对的。

参数描述: 我有一个关键的“数据”,其值是另一个字典["answer1":"1","answer2":"2","answer3":"3"]。需要发布此内容。

Wrong Reposnse = {"message = "Invalid data."; response = failure;}"

Right Reposnse = {"response":"success","message":"Data Inserted”}

func postData()
{
    let BASEURLS = "http://sebamedretail.techizer.in/babystore_api/question_data"
    let parameter = ["data":["answer1":"1","answer2":"2","answer3":"3"]]
    let session = URLSession.shared
    var request = URLRequest.init(url: URL.init(string: BASEURLS)!)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    do
    {
        request.httpBody = try JSONSerialization.data(withJSONObject:parameter, options: [])
        let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
            do{
                let responseArr = try! JSONSerialization.jsonObject(with: data!, options: [])
            }
        })
        task.resume()
    }
    catch
    {}
}

1 个答案:

答案 0 :(得分:0)

一切似乎都很好,也许你应该检查你在代码中提取JSON的方式,如果它是PHP,这里可以是一个解决方案:https://stackoverflow.com/a/18867369/7452015