如何使用URLSession swift 3解析Json和Normal Parmeters

时间:2017-06-15 08:08:13

标签: ios json swift3 nsurlsession

我在参数中传递参数并使用下面的代码。

这适用于这个参数:module = mymoduleName和userId = userId

 func callWebServices(url: String, methodName: String, parameters: String,istoken: Bool, tokenval: String, completion: @escaping CompletionHandler){

    var url_param = url

    if(methodName == "GET" && parameters != "")
    {
        url_param = url_param + "?" + parameters
    }

    var request = URLRequest(url: URL(string: url_param)!)
    request.httpMethod =  methodName

    if(methodName == "POST" && parameters != "")
    {
        let postString = parameters
        request.httpBody = postString.data(using: .utf8)
    }

    if(istoken)
    {
        request.setValue("Bearer " + tokenval , forHTTPHeaderField: "Authorization")
    }

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
        }

        if let httpsStatus = response as? HTTPURLResponse, httpsStatus.statusCode != 200 {
            print("Status Code should be 200, but it is \(httpsStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        do {
            let dictData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSDictionary
            completion(dictData)

        } catch {
            print("error is : \(error)")
        }
    }
    task.resume()
}

但我必须像

一样解析参数和json
module = mymoduleName
userId = userId and data = [{
"dmode_id": 1,
"user_id": 1,
"schedule_course_id": 1,
"course_id": 1}]

当我调用此方法时出错。帮我解决这个问题。我正在调用这样的方法。

callWebServices(url: URLS.Base_URL, methodName: "POST", parameters: param, istoken: false, tokenval: "", completion: { (jsonResult) in

print(jsonResult)

})

0 个答案:

没有答案