【问题标题】:Passing data from JSON to table view cell in Swift 3在 Swift 3 中将数据从 JSON 传递到表格视图单元格
【发布时间】:2017-06-06 14:28:50
【问题描述】:

我正在尝试将数据从 JSON 响应传递到表格视图单元格。我在捕获我在 URLSession.shared.dataTask 中提取的响应值时遇到问题。

    func callYouTubeAPIToGetAllVideos() {

    let url = URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=XYZ&maxResults=50&order=date&key=ABC")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print(error!)
        } else {
            if let usableData = data {
                let json = try? JSONSerialization.jsonObject(with: usableData, options: [])
                if let dictionary = json as? [String: Any?] {
                    if let array = dictionary["items"] as? [Any] {
                        for object in array {
                            if let objectAsDictionary = object as? [String: Any?] {
                                if let objectWithKindAndVideoId = objectAsDictionary["id"] as? [String: String] {
                                    if let videoId = objectWithKindAndVideoId["videoId"] {
                                        //pass data to table cell
                                    }
                                }
                                if let snippet = objectAsDictionary["snippet"] as? [String: Any] {
                                    if let description = snippet["description"] {
                                        //pass data to table cell
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    task.resume()
}

我尝试将值附加到实例变量,但它不起作用。

抱歉代码混乱,这是我第一次在 Swift 中使用 JSON。

【问题讨论】:

    标签: ios json swift uitableview tableviewcell


    【解决方案1】:

    首先从不将接收到的 JSON 字典声明为 [String:Any?]。接收到的字典值不能是nil

    • 声明一个自定义结构Video

      struct Video {      
          let videoId : String
          let description : String
      }
      
    • 声明一个数据源数组。

      var videos = [Video]()
      
    • 将 JSON 解析成数组并在主线程上重新加载表格视图。

      func callYouTubeAPIToGetAllVideos() {
      
          let url = URL(string: "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=XYZ&maxResults=50&order=date&key=ABC")
      
          let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
             if error != nil {
                  print(error!)
              } else {
                  do {
                      if let dictionary = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
                          let array = dictionary["items"] as? [[String: Any]] {
                          for object in array {
                              if let objectWithKindAndVideoId = object["id"] as? [String: String],
                                 let snippet = object["snippet"] as? [String: Any] {
                                     let videoId = objectWithKindAndVideoId["videoId"] ?? ""
                                     let description = snippet["description"] as? String ?? ""
                                     let video = Video(videoId: videoId, description: description)
                                     self.videos.append(video)
                               }
      
                          }
                          DispatchQueue.main.async {
                              self.tableView.reloadData()
                          }
                      }
                  } catch {
                      print(error)
                  }
              }
          }
          task.resume()
      }
      
    • 在 cellForRow 中将值分配给文本属性

      let video = videos[indexPath.row]
      cell.textLabel!.text = video.videoId
      cell.detailTextLabel?.text = video.description
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多