3

I just started coding in swift and I am at the point that I can get a single value out of the JSON but I can't seem to get all the values out of it by looping trough the array. so my question is how do I get all the values out and view it as float or string.

here is my code:

 let url = URL(string: "http://api.fixer.io/latest")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                    //Array
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    //print(myJson)

                    for items in myJson [AnyObject] {
                        print(items)
                    }

                    //here is the single value part, it looks for the rates then it puts it in label.

                    if let  rates = myJson["rates"] as? NSDictionary{


                        if let currency = rates["AUD"]{


                        print(currency);

                       self.label.text=String(describing: currency)


                        }





                    }

                }

                catch
                {


                }
            }
        }
    }
    task.resume()
2
  • This line doesn't make sense to me: for items in myJson [AnyObject] I would not expect that to compile. @aircraft's answer casts the JSON result to the correct type in the line that defines the myJSON constant. Aside from using an as! force cast, that is the better way to go. (I'd rewrite that as a guard statement that exits if the cast fails, since the format of data from a remote serve may change on you.) Commented Jan 16, 2017 at 0:31
  • As always, mutableContainers is completely meaningless in Swift. Commented Jan 16, 2017 at 8:00

3 Answers 3

2

Try this code:

import UIKit

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()

    self.getJson()
}

func getJson(){

    let url = URL(string: "http://api.fixer.io/latest")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                        //Dic
                        guard let myJson:[String:Any] = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any] else {return}
                        //print(myJson)

                        for items in myJson {
                            print(items)
                        }

                        //here is the single value part, it looks for the rates then it puts it in label.

                        if let  rates = myJson["rates"] as? NSDictionary{


                            if let currency = rates["AUD"]{


                                print(currency);

                               // self.label.text=String(describing: currency)


                            }


                        }

                    }

                    catch
                    {


                    }
                }
            }
        }
        task.resume()
    }
}

And the result in the console is like below:
enter image description here

The myJson is the dictionary what you want.

Sign up to request clarification or add additional context in comments.

3 Comments

Good answer, except this line should be a guard statement: guard let myJson:[String:Any] = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any] else {return}
Your code uses a force cast, which is not safe for data from a remote server since you can't guarantee the format of data from a remote site.
@Duncan C, thanks your suggestion, your suggestion is considerate, great.
1

I strongly recommend that you use SwiftyJSON to deal with JSON. It's extremely easy to learn and use.

first, you should install SwiftyJSON via CocoaPods (or any other way you like). then you can code it simply like below:

let url = URL(string: "http://api.fixer.io/latest")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {

                // Initialization
                let myJson = JSON(data: content)

                // Getting a string using a path to the element
                self.label.text = myJson["rates"]["AUD"].stringValue

                // Loop test
                for (key,value):(String, JSON) in myJson["rates"] {
                    print("key is :\(key), Value:\(value.floatValue)")
                }
            }
        }
    }
    task.resume()

1 Comment

so now I made it work! but now it wont show the whole list in an label it will only show last record. when I print it shows everything, any way to fix that?
0

try this out:

    if let currency = rates["AUD"] as? NSDictionary{
         for(key,value) in currency {
            // the key will be your currency format and value would be your currency value
         }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.