类型“ Any”的值没有成员“ valueForKeyPath”

时间:2018-06-30 15:02:25

标签: swift

我在寻找其他堆栈溢出问题,但似乎不适用于我的情况。

我正在制作YouTube应用,下面是我的代码。

     if let JSON = response.result.value as? NSDictionary{

            var arrayOfVideos = [Video]()

            for video in JSON["items"] as! NSArray{
                print(video)

                //Create video onjects off of the JSON response
                let videoObj = Video()
      //I got errors following part
                videoObj.videoId = video.valueForKeyPath("snippet.resourceId.videoId") as! String
                videoObj.videoTitle = video.valueForKeyPath("snippet.title") as! String
                videoObj.videoDescription = video.valueForKeyPath("snippet.description") as! String
                videoObj.videoThumbnailUrl = video.valueForKeyPath("snippet.thumbnails.maxres.url") as! String

                arrayOfVideos.append(videoObj)
            }

            self.videoArray = arrayOfVideos
        }else{
            print("couldn't get video information")
        }

我还有一个Video类,用于定义标题,描述和缩略图。

class Video: NSObject {

 var videoId:String = ""
 var videoTitle:String = ""
 var videoDescription:String = ""
 var videoThumbnailUrl:String = ""
}

我得到了这些错误。

  

类型“任意”的值没有成员“值ForKeyPath”

还有这个

  

线程1:致命错误:在展开可选值时意外发现nil

感谢您的帮助。预先谢谢你。

1 个答案:

答案 0 :(得分:0)

您可以尝试

if let JSON = response.result.value as? [String:Any] {

   var arrayOfVideos = [Video]()

   if let videos = JSON["items"] as? [[String:Any]] {

      for video in videos {

          let videoObj = Video()

          if let videoId = video["snippet.resourceId.videoId"] as? String {

              videoObj.videoId = videoId 
          }
          if let videoTitle = video["snippet.title"] as? String {

              videoObj.videoTitle = videoTitle
          }
          if let videoDescription = video["snippet.description"] as? String {

              videoObj.videoDescription = videoDescription
          }
          if let videoThumbnailUrl = video["snippet.thumbnails.maxres.url"] as? String {

              videoObj.videoThumbnailUrl = videoThumbnailUrl
          }

          arrayOfVideos.append(videoObj)
      }
   }
}