首页 文章

致命错误:在展开可选值时意外发现nil //(JSON为!NSDictionary)[“items”] [重复]

提问于
浏览
0

这个问题在这里已有答案:

我以前遇到过JSON数据的问题但是找到了一个解决方案,正如 alexcurylo 在下面的链接中所建议的那样;

Ambiguous use of 'subscript' with NSArray & JSON

它工作正常一段时间,但现在它返回 fatal error: unexpectedly found nil while unwrapping an Optional value 在下一行: for video in (JSON as! NSDictionary)["items"] as! NSArray { . 有什么建议吗?我认为这可能与没有maxres的缩略图有关,但更改默认值或高也不起作用 .

let API_KEY = "BrowserKey"


    let UPLOADS_PLAYLIST_ID = "playlistID"


    var videoArray = [Video]()


    var delegate: VideoModelDelegate?


    func getFeedVideos() {

//Fetch the videos dynamically through the Youtube DATA API
Alamofire.request(.GET, "https://www.googleapis.com/youtube/v3/playlists", parameters: ["part":"snippet", "playlistId":UPLOADS_PLAYLIST_ID,"key":API_KEY], encoding: ParameterEncoding.URL, headers: nil).responseJSON { (response) -> Void in


if let JSON = response.result.value {

    var arrayOfVideos = [Video]()


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


        // create video objects off of the JSON response

        let videoObj = Video()
        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.default.url") as! String


        arrayOfVideos.append(videoObj)

    }

    //when all the video objects constructed, assign the array to the VideoModel property
    self.videoArray = arrayOfVideos

    //Notify the delegate that the data is ready

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

}

}

1 回答

  • 0

    这就是为什么你没有像这样滥用强制解包操作符( ! ) .

    在表达式 (JSON as! NSDictionary)["items"] as! NSArray 中:

    • 你强行将 JSON 施放到 NSDictionary . 如果 JSON 不是 NSDictionary 或它的子类,则此强制转换将失败并导致崩溃 .

    • 您正在订阅以获取密钥 "items" 的值 . 这可能会返回 nil ,如果没有 "items" 的映射

    • 您强行将该值转换为 NSArray . 如果值为 nil ,则会崩溃 . 如果该值不是 NSArray 或其子类之一,则会崩溃 .

    ! 应该谨慎使用 . 它创建了一个断言,无论它是什么计划,例如在 if let / else 语句的情况下,程序崩溃了 . This is an intentional design choice ,以防止程序继续以不可预见的,无法预料的状态执行 .

    您应该使用 if letguard 来安全地处理此数据,并对错误做出反应 .

相关问题