在视图控制器之间解析 JSON 数据
Posted
技术标签:
【中文标题】在视图控制器之间解析 JSON 数据【英文标题】:parsing JSON data between view controllers 【发布时间】:2017-05-23 23:43:48 【问题描述】:此代码获取 JSON 数据并显示在此代码所在的视图控制器上。我试图弄清楚如何在另一个视图控制器上使用此页面的结果,这将大多数来自下面的第二个视图控制器的代码,我试图让代码的结果显示在上面。
func paraseData()
fetchedFiName = []
let url = ""
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) (data, response, error) in
if error != nil
print("Error")
else
do
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
//print(fecthdata)
for eachFetchedfiName in fetchedData
let eachfiName = eachFetchedfiName as! [String :Any]
let fiName = eachfiName["financial_institution"] as! String
let oneYear = eachfiName["one_year"] as! String
let twoYear = eachfiName["two_year"] as! String
let threeYear = eachfiName["three_year"] as! String
let fourYear = eachfiName["four_year"] as! String
let fiveYear = eachfiName["five_year"] as! String
self.fetchedFiName.append(rates(fiName: fiName, oneYear: oneYear, twoYear: twoYear, threeYear: threeYear, fourYear: fourYear, fiveYear: fiveYear))
//print(self.fetchedFiName)
self.mtgRates.reloadData()
catch
print("Error 2")
task.resume()
class rates
var fiName: String
var oneYear: String
var twoYear: String
var threeYear: String
var fourYear: String
var fiveYear: String
init(fiName: String, oneYear: String, twoYear: String, threeYear: String, fourYear: String, fiveYear: String)
self.fiName = fiName
self.oneYear = oneYear
self.twoYear = twoYear
self.threeYear = threeYear
self.fourYear = fourYear
self.fiveYear = fiveYear
这是我试图将结果传递给第二个视图控制器的代码。我正在尝试使用 JSON 数据中的贷方名称填充pickerview...我已经为这个问题苦苦挣扎了好几天...请思考。
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
return fetchedFiName[row].fiName
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
return fetchedFiName.count
func numberOfComponents(in pickerView: UIPickerView) -> Int
return 1
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
lenderName.text = fetchedFiName[row].fiName
self.view.endEditing(false)
【问题讨论】:
【参考方案1】:Investigate 后续。离开当前视图控制器时,您可以在目标视图控制器上设置一个值。代码如下所示:
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
let destinationViewController = segue.destination as! YourViewController
destinationViewController.json = yourJSONObj
【讨论】:
以上是关于在视图控制器之间解析 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章
如何在两个视图控制器之间的快速应用程序中传递 json 数据
我的表格视图已创建,但数组未显示在表格视图中,控制台中的所有数据都来了。请帮我解决 json 解析
tableview 在 connectionDidFinishLoading 中重新加载数据时出错(由 json 解析)