简体   繁体   中英

Multiple JSON parsing from different URLs in Swift

I want to parse JSON strings from different URLs in my iOS Tab Bar app:

  • Parsing.swift
  • FirstViewController.swift (INITIAL Tab Bar View Controller)
  • SecondViewController.swift
  • ...

In Parsing.swift I have various struct (TopLevel) and enum schemes I have controlled in Playground: they works perfectly. In every ViewController I have a Table View that I want to popolate with results of different JSON parsing. This is my simplified code:

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()

This code works perfectly : When app first open, Table View in FirstViewController popolates with results of JSON Parsing from url. But now its time to click on second Bar Item to open SecondViewController. The code is obviously:

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()

Well, when I tap on second Tab Bar Item to open the SecondViewController, Table View don't popolate and XCode gives an error : dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}))) But JSON text is valid .

I have tried a lot of solutions: I've changed tasks to URLSession.shared, I have used private struct and enum, I have controlled variables and costants, well, no way to parse second URL correctly. Even if I create a NEW Single View App and I copy the SecondViewController.swift code into the viewDidLoad() func, it works perfectly , so, again, its not a problem of the second URL, the JSON strings are valid . I think there is an interference between the two parsing tasks, it looks like the first corrupted the second one. What can I do? Thanks.

EDIT : this is my JSON (all fields are valid strings, I have deleted it for simplify)

{
"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": " "
          }
      ]
} }

As I don't have access to JSON response and Model used. I can assume few possibilities that may cause this issue.

1) You have your model and JSON response. When you are trying to decode, there could any field in JSON response that is null and same property in your model is not made optional.

2) The model may not have same structure (properties) as JSON response.

Well, I resolved the issue changing my second URL from "WWW.myserver.net/string2.json" to "myserver.net/string2.json", simply without WWW. In this way both tasks works and parses respective strings from different URLs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM