0

I got everything working so far. When building the project and running the function it parses the api content and then crashes. Here is the code:

//
//  GamesTableViewController.swift
//  Football Life
//
//  Created by David Seyboth on 18/01/16.
//  Copyright © 2016 David Seyboth. All rights reserved.
//

import UIKit

class GamesTableViewController: UITableViewController {

    // MARK: Properties
    var gameplan = [Games]()


    override func viewDidLoad() {
        super.viewDidLoad()

        //load NFL Games
        loadNFLgames { (result) -> () in
            self.gameplan = result
            dispatch_async(dispatch_get_main_queue(),{
                self.tableView.reloadData()
            })
        }
    }



    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)


                    let homeTeam = JsonObject["homeTeam"] as! String
                    let awayTeam = JsonObject["awayTeam"] as! String
                    let gameDate = JsonObject["gameDate"] as! String
                    let gameTimeET = JsonObject["gameTimeET"] as! String
                    let tvStation = JsonObject["tvStation"] as! String

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

                    self.gameplan.append(gamedata)

                    completionClosure(result: self.gameplan)
                }
            }

        })
    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return gameplan.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier = "GamesPrototypeCell"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! GamesTableViewCell

        // Fetches the appropriate meal for the data source layout.
        let game = gameplan[indexPath.row]

        cell.participants_label.text = game.participants
        cell.photoguest_image.image = game.photoguest
        cell.photohome_image.image = game.photohome
        cell.time_label.text = game.time
        cell.stadium_label.text = game.stadium
        cell.channel_label.text = game.channel


        return cell

}
}

the crash is at line: let homeTeam = JsonObject["homeTeam"] as! String with the message:

fatal error: unexpectedly found nil while unwrapping an Optional value

1
  • Two options: JsonObject has no key homeTeam or homeTeam is not a String. I'd prefer native Swift collection types unless you have no choice. Commented Jan 24, 2016 at 21:41

1 Answer 1

1

you are missing the json format. the values your looking for are in array "Schedule"

so your code will be

        if let JsonObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary{

//this is your array of games
            let items = JsonObject["Schedule"] as! NSMutableArray
            print(items)
//loop in items and add the values to your array 
            for item in items {
                let homeTeam = item["homeTeam"] as! String
                let awayTeam = item["awayTeam"] as! String
                let gameDate = item["gameDate"] as! String
                let gameTimeET = item["gameTimeET"] as! String
                let tvStation = item["tvStation"] as! String
                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)!

                self.gameplan.append(gamedata)
            }
        }
Sign up to request clarification or add additional context in comments.

3 Comments

the app isn't crashing but I still get no output besides the debug monitor
try printing the gameplan variable just before calling tableview.reloadData()
ok, got it. But the array gameplan looks like this: [Football_Life.Games, Football_Life.Games, Football_Life.Games, Football_Life.Games, Football_Life.Games, Football_Life.Games,...]

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.