0

I have this function working fine (feel free if you have a fine tuning !) :

    func httpPostRequest(urlString: String, dataToPost: Dictionary<String, String>) {

    let url = URL(string: urlString)!
    let session = URLSession.shared
    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: dataToPost, options: .prettyPrinted)

    } catch let error {
        print(error.localizedDescription)
    }

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

    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil else {
            print("error=\(error) AND error = nil !")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // Check for http(s) errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
            return
        }

        guard let data = data, error == nil else {                                                 // Check for fundamental networking error
            print("error=\(error)")
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print("JSON = ")
                print(json)
           }
        } catch let error {
            print(error.localizedDescription)
            return
        }
    })
    task.resume()
}

The PHP server return this JSon string :

{'exception': false, 'success': false, 'status': -8, 'message': 'Your email address is not valid !', 'confirmMessage': 'null', 'html': 'null', 'data': 'null'}

This is what is diplay in the XCode Console :

JSON = 
["status": -8, "data": null, "html": null, "message": Your email address is not valid !, "exception": 0, "confirmMessage": null, "success": 0]

I need to return this JSon string to continue with this data.

How can I convert my function for do this ?

2
  • You need to pass a completion handler and invoke that when you have the data Commented Mar 29, 2017 at 20:33
  • See stackoverflow.com/questions/39219063/… Commented Mar 29, 2017 at 20:41

1 Answer 1

2

This should be the function.

func httpPostRequest(urlString: String, dataToPost: Dictionary<String, String>, completionHandler:@escaping (Dictionary<String, Any>) -> ()) {

    let url = URL(string: urlString)!
    let session = URLSession.shared
    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: dataToPost, options: .prettyPrinted)

    } catch let error {
        print(error.localizedDescription)
    }

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

    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
        guard error == nil else {
            print("error=\(error) AND error = nil !")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // Check for http(s) errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
            return
        }

        guard let data = data, error == nil else {                                                 // Check for fundamental networking error
            print("error=\(error)")
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print("JSON = ")
                print(json)
                completionHandler(json)
            }
        } catch let error {
            print(error.localizedDescription)
            return
        }
    })
    task.resume()
}
Sign up to request clarification or add additional context in comments.

1 Comment

Can you help me to know how I call the function with completionHandler please ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.