Monday, 17 June 2019

Service Call With NsUrlSession

func loginWS(parameters:[String:String], completionHandler: @escaping (Any?) -> Swift.Void) {

    guard let gitUrl = URL(string: BASE_URL+ACTION_URL) else { return }
    print(gitUrl)

    let request = NSMutableURLRequest(url: gitUrl)
    //  uncomment this and add auth token, if your project needs.
    //  let config = URLSessionConfiguration.default
    //  let authString = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMywiUGFzc3dvcmQiOiIkMmEkMTAkYVhpVm9wU3JSLjBPYmdMMUk2RU5zdU9LQzlFR0ZqNzEzay5ta1pDcENpMTI3MG1VLzR3SUsiLCJpYXQiOjE1MTczOTc5MjV9.JaSh3FvpAxFxbq8z_aZ_4OhrWO-ytBQNu6A-Fw4pZBY"
    //  config.httpAdditionalHeaders = ["Authorization" : authString]

    let session = URLSession.shared
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [])

    let task = session.dataTask(with: request as URLRequest) { data, response, error in

        guard let data = data else { return }
        do {
        //  let decoder = JSONDecoder()
        //  here replace LoginData with your codable structure.
            let gitData = try JSONDecoder().decode(LoginData.self, from: data)
            print("response data:", gitData) 
            completionHandler(gitData)
        } catch let err {
            print("Err", err)
        }
        }.resume()
}