[英]Multiple JSON parsing from different URLs in Swift
我想在我的iOS Tab Bar應用中解析來自不同URL的JSON字符串:
在Parsing.swift中,我在Playground中控制了各種struct (TopLevel)和枚舉方案:它們完美地工作。 在每個ViewController中,我都有一個要填充不同JSON解析結果的表視圖。 這是我的簡化代碼:
FirstViewController.swift viewDidLoad()
let url = // my first URL to parse
let urlObj = URL(string: url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlObj!) { (data, response, error) in
do {
let results = try JSONDecoder().decode(TopLevel.self, from: data!)
... for ...
self.table.reloadData()
}
catch {
...
}
}
task.resume()
這段代碼完美地工作 :首次打開應用程序時,FirstViewController中的表視圖會使用url的JSON解析結果填充。 但是現在該單擊第二個Bar Item來打開SecondViewController了。 該代碼顯然是:
SecondViewController.swift viewDidLoad()
let url2 = // my second URL to parse
let urlObj2 = URL(string: url2)
let config2 = URLSessionConfiguration.default
let session2 = URLSession(configuration: config2)
let task2 = session.dataTask(with: urlObj2!) { (data2, response2, error2) in
do {
let results2 = try JSONDecoder().decode(TopLevel.self, from: data2!)
... for ...
self.table2.reloadData()
}
catch {
...
}
}
task2.resume()
好吧,當我點擊第二個選項卡欄項以打開SecondViewController時,表視圖不會顯示,並且XCode給出了錯誤 : dataCorrupted(Swift.DecodingError.Context(codingPath:[],debugDescription:“給定的數據不是有效的JSON。 。,底層錯誤:可選(錯誤域= NSCocoaErrorDomain代碼= 3840“ JSON文本不是以數組或對象開頭,並且選項未設置片段。” UserInfo = {NSDebugDescription = JSON文本不是以數組或對象開頭,並且選項為允許未設置片段。})))但是JSON文本有效 。
我已經嘗試了許多解決方案:我將任務更改為URLSession.shared,使用了私有結構和枚舉,控制了變量和成本,但是,沒有辦法正確地解析第二個URL。 即使我創建一個新的單一視圖應用程序,我的SecondViewController.swift代碼復制到viewDidLoad中()FUNC,它完美的作品,所以,再一次,它不是第二個URL的問題,JSON字符串是有效的 。 我認為這兩個解析任務之間存在干擾,看起來第一個破壞了第二個。 我能做什么? 謝謝。
編輯 :這是我的JSON(所有字段均為有效字符串,為簡化起見,我已將其刪除)
{
"attributes": {
"version": "2.0",
"nodeValue": "\n"
},
"channel": {
"title": " ",
"link": " ",
"description": " ",
"lastBuildDate": " ",
"language": " ",
"copyright": " ",
"item": [
{
"title": " ",
"link": " ",
"guid": {
"attributes": {
"isPermaLink": "false",
"nodeValue": " "
}
},
"pubDate": " ",
"category": " "
},
{
"title": " ",
"link": " ",
"guid": {
"attributes": {
"isPermaLink": "false",
"nodeValue": " "
}
},
"pubDate": " ",
"category": " "
}
]
} }
由於我無權使用JSON響應和Model。 我可以假設幾種可能導致此問題的可能性。
1)您有模型和JSON響應。 當您嘗試解碼時,JSON響應中可能有任何字段為null,並且模型中的相同屬性不是可選的。
2)模型的結構(屬性)可能與JSON響應不同。
好吧,我解決了將我的第二個URL從“ WWW.myserver.net/string2.json”更改為“ myserver.net/string2.json”的問題,而沒有使用WWW。 這樣,兩個任務都可以工作並解析來自不同URL的相應字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.