2017-07-30 26 views
0

我正在使用YouTube數據API和Alamofire來顯示我的YouTube頻道的視頻並動態更新。這裏是我的代碼:使用YouTube數據API和Alamofire時出錯

func getFeedVideo() {   

Alamofire.request("https://www.googleapis.com/youtube/v3/playlists", parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in 

     if let JSON = response.result.value { 

      if let dictionary = JSON as? [String: Any] { 

       var arrayOfVideos = [Video]() 

       for video in dictionary["items"] as! NSArray { 
        // Create video objects off of the JSON response 
        let videoObj = Video() 
        videoObj.videoID = (video as AnyObject).value(forKeyPath: "snippet.resourceId.videoId") as! String 
        videoObj.videoTitle = (video as AnyObject).value(forKeyPath: "snippet.title") as! String 
        videoObj.videoDescription = (video as AnyObject).value(forKeyPath: "snippet.description") as! String 
        videoObj.videoThumbnailUrl = (video as AnyObject).value(forKeyPath: "snippet.thumbnails.maxres.url") as! String 

        arrayOfVideos.append(videoObj) 

       } 
       self.videoArray = arrayOfVideos 
       if self.delegate != nil { 
        self.delegate!.dataReady() 
       } 
      } 
     } 
    } 
} 

我得到一個錯誤

主題1:EXC_BAD_INSTRUCTION

就行for video in dictionary["items"] as! NSArray {。在控制檯中,我看到

fatal error: unexpectedly found nil while unwrapping an Optional value 
(lldb) 

數據顯示在UITableView中。有想法該怎麼解決這個嗎?

回答

0

這意味着您沒有字典中項目的值,或者您不正確地訪問它。

0

你正試圖對NSArray施加強制轉換。如果dictionary["items"]不是NSArray,這會使應用程序崩潰。
我建議你在循環前加一個斷點來檢查dictionary["items"]的類型。

例子:

guard let items = dictionary["items"] as? NSArray else { return } 
1

,請不要使用武力類型轉換。它可能導致你的應用程序崩潰。如果讓或放鬆讓我們永遠使用。儘量重複這樣說,這

if let dictionary = JSON as? [String: Any] { 
var arrayOfVideos = [Video]() 
if let playlist = dictionary["items"] as? [Any] { 

    for i in 0..<playlist.count { 

     let videoObj = Video() 
     if let video = playlist[i] as? [String: Any] { 
      if let videoId = video["id"] as? String { 
       videoObj.videoID = videoId 
      } 

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

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

      if let thumbnails = video["thumbnails"] as? [String: Any]{ 
       if let maxres = thumbnails["maxres"] as? [String: Any] { 
        if let url = maxres["url"] as? String { 
         videoObj.videoThumbnailUrl = url 
        } 
       } 
      } 
      arrayOfVideos.append(videoObj) 
     } 
    } 
} 

}

+0

我收到一個錯誤'int類型對線沒有下members''如果讓視頻ID =視頻[「ID」]作爲?字符串{','如果讓snippet = video [「snippet」] as? [字符串:任何] {',和'如果讓縮略圖=視頻[「縮略圖」]? [字符串:任何] {' –

+0

請參閱我編輯的答案。雖然爲時已晚。 –