【问题标题】:Swift 3 How can I convert this function to return content of json variableSwift 3 如何将此函数转换为返回 json 变量的内容
【发布时间】:2017-08-23 12:29:46
【问题描述】:

我的这个功能工作正常(如果你有微调,请随意!):

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

PHP 服务器返回这个 JSon 字符串:

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

这就是 XCode 控制台中的显示:

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

我需要返回这个 JSon 字符串才能继续处理这个数据。

我怎样才能转换我的函数呢?

【问题讨论】:

标签: php ios json swift3


【解决方案1】:

这应该是函数。

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

【讨论】:

  • 你能帮我知道我如何用completionHandler调用函数吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 1970-01-01
  • 2017-09-03
  • 1970-01-01
相关资源
最近更新 更多