在swift中初始化json api后出错

时间:2016-01-24 21:36:10

标签: arrays json swift

到目前为止我已经完成了所有工作。在构建项目并运行该函数时,它会解析api内容然后崩溃。 这是代码:

//
//  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

}
}

崩溃在线:     让homeTeam = JsonObject [“homeTeam”]为!串 信息:

  

致命错误:在解包可选值时意外发现nil

1 个答案:

答案 0 :(得分:1)

你缺少json格式。您要查找的值在数组“Schedule”

所以你的代码将是

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