【问题标题】:Getting error after initialising json api in swift在swift中初始化json api后出现错误
【发布时间】:2016-01-24 21:36:10
【问题描述】:

到目前为止,我一切正常。在构建项目并运行该函数时,它会解析 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

【问题讨论】:

  • 两个选项:JsonObject 没有密钥 homeTeamhomeTeam 不是 String。除非你别无选择,否则我更喜欢原生 Swift 集合类型。

标签: arrays json swift


【解决方案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)
            }
        }

【讨论】:

  • 应用程序没有崩溃,但除了调试监视器之外我仍然没有得到任何输出
  • 在调用 tableview.reloadData() 之前尝试打印游戏计划变量
  • 好的,知道了。但是数组游戏计划看起来像这样:[Football_Life.Games, Football_Life.Games, Football_Life.Games, Football_Life.Games, Football_Life.Games, Football_Life.Games,...]
猜你喜欢
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多