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

问题描述 投票:0回答:1

我需要在函数外传递我的Parser中的“对象”的数据。

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

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”中

swift api parsing
1个回答
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)
    }
© www.soinside.com 2019 - 2024. All rights reserved.