如何将解析器中的数据传递给函数

时间:2019-04-18 08:03:18

标签: swift api parsing

我需要在函数外部的解析器中传递“对象”的数据。

我试图制作一个多维数组并将其存储到其中,但是我只能在函数内部访问它,当我打印它时,它在外面是空的。

ApiParser.parseFuction(strUrl: Constants.URL.Global + "HR/EndOfDay/GetAllEndOfReports", method: "GET", token: "", params: [String : AnyObject]()) { (status, object) in

        let data = object["value"] as! [[String: AnyObject]]

        let jsonData = try? JSONSerialization.data(withJSONObject: data)

        let test = try! JSONDecoder().decode([EODDataContainer].self, from: jsonData!)
        print(test)
    } // this is the code inside the viewdidload


class ApiParser: NSObject {

    class func parseFuction(strUrl: String, method: String, token: String, params: [String : AnyObject]?, postCompleted: @escaping (_ statusCode: Int, _ object: [String: AnyObject]) ->()) {

        let className = "--- ApiParser: ------->>>"
        let url = URL(string: strUrl)

        var request = URLRequest(url: url!)


        request.httpMethod = method
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

        if method == "POST" || method == "PUT" {
            let jsonData = try? JSONSerialization.data(withJSONObject: params!)
            request.httpBody = jsonData

    }

    let sessionConfig = URLSessionConfiguration.default
    sessionConfig.timeoutIntervalForRequest = 300.0
    sessionConfig.timeoutIntervalForResource = 300.0
    let session = URLSession(configuration: sessionConfig)

    session.dataTask(with: request) { (data, response, err) in

    print(request)

        guard let httpResponse = response as? HTTPURLResponse else { return }
        let statusCode = httpResponse.statusCode

        print("statusCode ---->>> \(statusCode)")



        DispatchQueue.main.async {
            guard let data = data else { return }
            do {

                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: AnyObject]
                postCompleted(statusCode, json)

            } catch let jsonErr {

                print("Serializing jsonError \(type(of: jsonErr))", jsonErr._code)
                postCompleted(jsonErr._code, [String: AnyObject]())
            }

        }
        }.resume()


}

} //this is my api parser class

我想将“ test”变量存储在“ twoDimensionalArray”中

1 个答案:

答案 0 :(得分:1)

在ViewController类中:

var test : [EODDataContainer]?

override func ViewDidLoad() {
   super.viewDidLoad()
   ApiParser.parseFuction(strUrl: Constants.URL.Global + "HR/EndOfDay/GetAllEndOfReports", method: "GET", token: "", params: [String : AnyObject]()) { (status, object) in

        let data = object["value"] as! [[String: AnyObject]]

        let jsonData = try? JSONSerialization.data(withJSONObject: data)

        self.test = try! JSONDecoder().decode([EODDataContainer].self, from: jsonData!)
        print(test)
    }