简体   繁体   中英

Swift 3 How can I convert this function to return content of json variable

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 ?

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM