【问题标题】:After parsing Json acquired with API, it can not be assigned to a variable in Swift解析API获取的Json后,在Swift中无法赋值给变量
【发布时间】:2019-01-26 06:22:54
【问题描述】:

我使用 swift4 创建了一个 iOS 应用

我遇到了一个问题。 解析API获取的Json后,无法赋值给var stores : [categories.stores]?。打印值为 nil

但是printlet json = try decoder.decode(categories.self, from: data),我可以得到Json数据。

并且没有错误。所以我不知道为什么我不能替代

请帮帮我。

StoreListViewController

class StoreListViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var TableView: UITableView!


var category_id = ""
let cellReuseIdentifier = "cell"
// use json 
var stores : [categories.stores]?

override func viewDidLoad() {
    super.viewDidLoad()
    TableView.delegate = self
    TableView.dataSource = self

    let url = URL(string: "http://127.0.0.1:8000/search/api/category?category_id=" + category_id)
    let request = URLRequest(url: url!)
    let session = URLSession.shared

    let encoder: JSONEncoder = JSONEncoder()
    encoder.dateEncodingStrategy = .iso8601
    encoder.outputFormatting = .prettyPrinted

    session.dataTask(with: request){(data, response, error)in if error == nil,
        let data = data,
        let response = response as? HTTPURLResponse{

        let decoder: JSONDecoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        do {

            let json = try decoder.decode(categories.self, from: data)

            // in to stores variable
            self.stores = json.stores

            DispatchQueue.main.async {
                self.TableView.reloadData()
            }
        } catch {
            print("error:", error.localizedDescription)

        }

        }

        }.resume()

    print(stores as Any)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return stores?.count ?? 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as? TableViewCell
        else {
            fatalError("The dequeued cell is not an instance of TableViewCell.")
    }

    cell.storeName.text! = stores![indexPath.row].name
    cell.storeLocation.text! = stores![indexPath.row].location


return cell
}

}

数据模型

struct categories : Codable {
let id : Int
let name : String
let stores : [stores]

struct stores : Codable {
    let id : Int
    let name : String
    let location : String
    let price : String
    let open_time : String
    let closed_day : String
    let photos : [photos]
    let tags : [tags]

    struct photos:Codable {
        let id : Int
        let path : String
    }

    struct tags:Codable {
        let id : Int
        let name : String
    }
}
}

【问题讨论】:

  • 它打印nil,因为print 行在闭包之外,将在返回数据之前执行。将线放入封闭件内。如果没有显示数据,则错误必须在其他地方。请以大写字母开头并以单数形式 (struct Photo : Codable) 命名您的结构。该结构的一个实例是一个Photo 而不是一个Photos
  • 我明白了。我变了。非常感谢
  • PS: 并将数据源数组stores 声明为非可选var stores = [Category.Store]() 以摆脱一堆丑陋的问号和感叹号以及stores?.count ?? 0 之类的怪异语法

标签: ios json iphone swift4


【解决方案1】:

我在关闭前工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多