0

I have added to my project the SwiftyJSON.swift file and I am trying to get some data from the web. Now my project runs but only until the line where I am trying to get the array from json in a dictionary. I cannot understand where the problem is, but I am guessing it has to be something very stupid as I am just in the beginning with learning swift.

I am just trying to print in the console the name of all the movies from that url and after I manage to achieve this performance, I will try to get the summary of the movie as well and then put them in a TableView.

import UIKit

class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //grab the status code and check if the transfer was successful == 200
        let requestURL: NSURL = NSURL(string: "https://itunes.apple.com/us/rss/topmovies/limit=50/json")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {

                //sort through the stations key and cast the data into an array of dictionaries
                do{
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
                    print("bbbbb")

// From here on, it doesn't print anything anymore
                    if let movies = json["entry"] as? [[String: AnyObject]] {
                        print(movies)
                        print("test")

                        for movie in movies {

                            if let name = movie["name"] as? String {
                                print("mmmm")
                                print("%@ (Built %@)",name)

                            }
                        }

                    }

                }catch {
                    print("Error with Json: \(error)")
                }
            }
        }
    task.resume()
5
  • Try printing out the contents of the json dictionary via "print("json contents is \(json)")" right before you try to get movies". I'd be interested in finding out if there's really an entry? I'm guessing there is, but it's probably nested inside something else. Commented Apr 21, 2016 at 23:18
  • By looking at this I'd take a stab in the dark and say that json doesn't have a key called entry. If you want to force the error change your as? to as! It might let you know what's happening. Commented Apr 21, 2016 at 23:23
  • @MichaelDautermann I have just added your print line before the one where I try to get the movies and it still doesn't print anything, the only thing that I have in the console is the bbbbb from the previous print. Commented Apr 21, 2016 at 23:34
  • @Jthomps I have also tried changing from ? to ! and I am getting this: Initializer for conditional binding must have Optional type, not [[String: AnyObject]] Commented Apr 21, 2016 at 23:37
  • Here's the json data: itunes.apple.com/us/rss/topmovies/limit=50/json Commented Apr 21, 2016 at 23:38

1 Answer 1

1

entry is an json array, Use .array

if let movies = json["entry"].array {
  for movie in movies {
     // Do stuff
  }
}

Also a general tip. Do not cast the values e.g.

movie["something"] as? String

Rather use the built in features:

movie["something"].string

Update

Looking closer on your code I see that you are acctually not using SwiftyJSON.swift at all. To use Swifty you parse the json text like this and get a JSON object:

let jsonObj = JSON(data: yourData) // data is a NSData

Please have another look at the documentation:

https://github.com/SwiftyJSON/SwiftyJSON

I think you are reading the section "Why is the typical JSON handling in Swift NOT good?". That section explains the native and "bad" way of managing json in Swift, the real documentation is further down.

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

1 Comment

still not working, it only prints the bbbbb out in the console and nothing more after that >:(

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.