0

I am building an app where people need to fill out a form and then it creates an HTTP post where the API will return a Json file to the app with data I need. Everything is working fine with accessing the API however I want to parse the data in another view controller. How can I access the JSON file from another view controller?

let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {


                print(json)

 ^^^^^^^
 How do I take this JSON file to the next view controller so I dont have to do the parsing below?



                let jsonData = json

                let ratesJson = jsonData["rates"]!

                let rates = ratesJson as! NSArray



                print("Rates: \(rates)")

                print("*************")
                print(rates.count)
                print("*************")


                for item in 0..<rates.count {
                    let specificRate = rates[item]
                    let price = (specificRate as AnyObject)["amount_local"]!
                    let provider = (specificRate as AnyObject)["provider"]!

                    print("--\(item)--")
                    print("Price: \(price!)")
                    print("Provider: \(provider!)")



                }

            }

        } catch let error {
            print(error.localizedDescription)
        }
    })
BrandonMayU
  • 726
  • 2
  • 6
  • 13
  • How do you show your other view? o what is the relationship between the one who does the request and the one you want to process the data? – Christian Serrano Jul 26 '17 at 22:17
  • If you save a variable outside of either class, both classes will be able to access it. If you have an item struct or object, try storing an array of items when you parse through the json. You'll then be able to access it from any other VC – Justin Doan Jul 26 '17 at 22:28
  • Are you using Storyboard Segues ? Already answered (in objc though): https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers – nathan Jul 26 '17 at 22:28

2 Answers2

1

I assume by your comment, your intention is to actually pass a JSON object, not a JSON file to the next view controller.

Therefore, you just need to pass the JSON object to your segue and assign it as a property to the next view controller.

Since the question was very open ended, here is one possible solution and interpretation.

Example:

//Sample snippet from code from question    
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
    performSegue(withIdentifier: "MySegue", sender: json);
}

override func prepare(for segue: UIStoryboardSegue!, sender: Any?) {
    if (segue.identifier == "MySegue") {
       let vc = segue.destinationViewController as! RandomViewController
       vc.json = sender as! [String:Any];
    }
}
Josh Hamet
  • 957
  • 8
  • 10
0

One of the things that usually cause bugs in programs is state. What you are asking here in my opinion is state.

What I would do is i would write a generic function ( Swift encourages functional programming in a lot of cases, have a look at: swift map, filter etc. that deals with the HTTP request and returning the data in a closure.

This closure will then live within the view controller you want your json object in, thus solving your problem of accessing said data.

Now I don't believe that is the right approach either. I would create an object for your specific data returned, like say a "struct Person" or whatever your needs are.

This has 2 advantages:

  • In swift 3.1 you can have a custom init() method that parses the JSON safely ( remember, optionals! ) and populates the structs data accordingly
  • In swift 4.0 and Xcode9.0 You will be able to morph the struct you just created to conform to the Codable and Decodable protocols with wich json parsing will be greatly simplified, as explained here: ultimate swift json guide

Hope this was of any help.

Antwan van Houdt
  • 6,989
  • 1
  • 29
  • 52