1

I am trying to get items from an api (JSON) and to parse it into a predefined swift array. I have searched and looked for hours but due to my lack of skills I wasn't able to find anything suitable my case.

My predefined array looks like this:

init?(participants: String, photoguest: UIImage?, photohome: UIImage?, time: String, stadium: String, channel: String)

the JSON structure is like this(entire json file):

{"gameId":"255","gameWeek":"17","gameDate":"2016-01-03","awayTeam":"SEA","homeTeam":"ARI","gameTimeET":"4:25 PM","tvStation":"FOX","winner":"SEA"}

My current code looks like this (Games is the class where I connect variables from array with table cell items):

var gameplan = [Games]()

func loadNFLgames(){

    let apiURL = NSURL(string: "http://www.fantasyfootballnerd.com/service/schedule/json/test/")
    let data: AnyObject? = NSData(contentsOfURL: apiURL!)


    let homeTeam = (data as! NSDictionary)["homeTeam"] as! String
    let awayTeam = (data as! NSDictionary)["awayTeam"] as! String
    let gameDate = (data as! NSDictionary)["gameDate"] as! String
    let gameTimeET = (data as! NSDictionary)["gameTimeET"] as! String
    let tvStation = (data as! NSDictionary)["tvStation"] as! String

    /*
    for schleife mit API daten:
        for gameWeek = currentWeek{ //every game where gameWeek matches currentWeek
    */

    // create variables from api calls
    let api_guest = awayTeam
    let api_home = homeTeam
    let api_tvhost = tvStation
    let api_time = gameDate + ", " + gameTimeET + " ET" // convert gameDate to day e.g. SUN
    let api_stadion = "N/A"

    // prepare data for array
    let gamedata = Games(participants: api_guest+" @ "+api_home, photoguest: UIImage(named: api_guest), photohome: UIImage(named: api_home), time: api_time, stadium: api_stadion, channel: api_tvhost)!

    // add data to array
    gameplan.append(gamedata)
}

I am getting the following error:

Could not cast value of type '_NSInlineData' (0x1a0cfd428) to 'NSDictionary' (0x1a0cf3380).

EDIT: The error is being thrown here:

let homeTeam = (data as! NSDictionary)["homeTeam"] as! String

Your help is highly appreciated. Thanks in advance!

5
  • 1
    Um .. Whats the question Commented Jan 24, 2016 at 19:42
  • sorry updated the post Commented Jan 24, 2016 at 19:46
  • And which line is throwing the error, or we suppose to guess? Commented Jan 24, 2016 at 19:48
  • NSDictionary error is throwing in the line: let homeTeam = (data as! NSDictionary)["homeTeam"] as! String Commented Jan 24, 2016 at 19:53
  • U need to parse the schedule array, then you loop for each nsdictionary Commented Jan 24, 2016 at 19:55

2 Answers 2

1

hello your data variable doesn't contain the Json you r looking for. so you have to serialize it to json like alexander suggested but NSJSONSerialization can throw an error so we have tu put in in try so your code will be something like this (i suggest always using dispatch_async to make it in background thread than use the completion closure to get your result)-->

    func loadNFLgames(completionClosure: (result : [Games]) ->()){
        let queue: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        dispatch_async(queue, {
            let URL = "http://www.fantasyfootballnerd.com/service/schedule/json/test/"
            print(URL)
            if let data = NSData(contentsOfURL: NSURL(string: URL)!){
                if let JsonObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary{
                    print(JsonObject)
                    //here you can loop through the JsonObject to get the data you are looking for
                    //when you get your array of Games just pass it the the completion closure like this
completionClosure(result: gameplan)
                }
            }

        })
    }

PS: please let me know if you need more help.

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

9 Comments

Thanks, this seems to work without an error but I get a warning: Cast from 'NSData' to unrelated type 'NSDictionary' always fails. The cells are not being displayed in the end but at least the table loads. Do you know a fix for that? Thanks in advance
nevermind I fixed it :) . Sorry I just started developing with swift.
its ok . im glad it helped
I am still having problems with displaying the cells but at least I don't run into errors anymore.
could you paste your code ? it would be helpful. dont forget to call tableView.reloadData() in the completion closure.
|
0

Your data variable is NSData type (not NSDictionary). You have to convert it in order to use it. Try something like that:

let decodedJson = NSJSONSerialization.JSONObjectWithData(data, options: nil) as! NSDictionary

And than you can use it like standard dictionary

let homeTeam = decodedJson["homeTeam"] as! String

3 Comments

I can somehow not use nil nor can I use 0 as NSReadoptions
fixed it with options: [] but getting another error on the NSJSONSerialization call can throw but it is not marked with try
try the following: do { let decodedJson = try NSJSONSerialization.JSONObjectWithData(data, options: nil) as! NSDictionary } catch error { // error handle } Or, if you 100% sure, that transformation will be without any errors you can do it in the following way ' let decodedJson = try! NSJSONSerialization.JSONObjectWithData(data, options: nil) as! NSDictionary'

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.