如何将解析器中的数据传递给函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将解析器中的数据传递给函数相关的知识,希望对你有一定的参考价值。
我需要在函数外传递我的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”中
答案
在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)
}
以上是关于如何将解析器中的数据传递给函数的主要内容,如果未能解决你的问题,请参考以下文章
如何将计时器中的数据传递给新的 ViewController (Swift 3)
R:是不是可以使用 paste0 函数(或一些类似的函数)将存储在对象中的数据传递给新对象?
如何将表单 FormSeetController 中的数据传递给 ViewController?