简体   繁体   English

Swift 3如何转换此函数以返回json变量的内容

[英]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 : PHP服务器返回此JSon字符串:

{'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 : 这就是XCode控制台中的diplay:

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. 我需要返回此JSon字符串以继续此数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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