2017-06-06 39 views
0

我試圖將數據從JSON響應傳遞到表格視圖單元格。我在捕獲我在URLSession.shared.dataTask中提取的響應值時遇到問題。將數據從JSON傳遞到Swift 3中的表格視圖單元

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。

回答

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 
    
相關問題