0

I have tried Alamofire, I have tried it with all my heart. It just does not work for me. I finally got http GET working, but I need to get http POST working. Our POST API's take a Request object that has all the necessary data in it. I have requested the backend developers to provide me with a KEY-VALUE pair JSON (no embedded objects/arrays) so that I can use a Dictionary in my swift code convert that to json and send the request. All I need is now to convert the below code to POST.

My earlier questions that did not help much. NSInvalidArgumentException Invalid type in JSON write DemographicsPojo Swift 3.0, Alamofire 4.0 Extra argument 'method' in call

I have given up on Alamofire. I want to use Foundation classes. Simple basic and fundamental way of life :).

 func callWebService(url : String) {
        // Show MBProgressHUD Here
        var config                              :URLSessionConfiguration!
        var urlSession                          :URLSession!

        config = URLSessionConfiguration.default
        urlSession = URLSession(configuration: config)

        // MARK:- HeaderField
        let HTTPHeaderField_ContentType         = "Content-Type"

        // MARK:- ContentType
        let ContentType_ApplicationJson         = "application/json"

        //MARK: HTTPMethod
        let HTTPMethod_Get                      = "GET"

        let callURL = URL.init(string: url)

        var request = URLRequest.init(url: callURL!)

        request.timeoutInterval = 60.0 // TimeoutInterval in Second
        request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
        request.addValue(ContentType_ApplicationJson, forHTTPHeaderField: HTTPHeaderField_ContentType)
        request.httpMethod = HTTPMethod_Get

        let dataTask = urlSession.dataTask(with: request) { (data,response,error) in
            if error != nil{
                print("Error **")

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

        dataTask.resume()
        print("..In Background..")
    }
Community
  • 1
  • 1
Siddharth
  • 9,349
  • 16
  • 86
  • 148
  • I am a bit confused you asking to rewrite code to send POST request? Please try it by your self, and than if it is not working ask for help. – Oleg Gordiichuk Apr 27 '17 at 07:20
  • Trust me when I say this, I have tried it and failed. I finally have a working GET, but cant get POST working. – Siddharth Apr 27 '17 at 07:25

1 Answers1

2

Just pass JSON string and the API URL to this function. Complete code for POST.

func POST(api:String,jsonString:String,completionHandler:@escaping (_ success:Bool,_ response:String?,_ httpResponseStatusCode:Int?) -> Void)  {

    let url = URL(string: api)

    var request: URLRequest = URLRequest(url: url!)

    request.httpMethod = "POST"

    request.setValue("application/json", forHTTPHeaderField:"Content-Type")
    request.timeoutInterval = 60.0

    //additional headers
    if let token = Helper.readAccessToken() {
        request.setValue("\(token)", forHTTPHeaderField: "Authorization")
    }

    let jsonData = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: true)
    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) {
        (data: Data?, response: URLResponse?, error: Error?) -> Void in

        var responseCode = 0
        if let httpResponse = response as? HTTPURLResponse {
            responseCode = httpResponse.statusCode
            print("responseCode \(httpResponse.statusCode)")
        }

        if error != nil {
            completionHandler(false, error?.localizedDescription,nil)

        } else {
            let responseString = String(data: data!, encoding: .utf8)
            completionHandler(true, responseString, responseCode)
        }
    }

    task.resume()
}
Gurdev Singh
  • 1,996
  • 13
  • 11