使用Alamofire

时间:2017-01-30 18:43:33

标签: ios youtube swift3 cocoapods alamofire

我已经四处寻找我的问题的答案,但我没有运气。我是编码的新手,尤其是使用Swift 3.0。

我正在尝试使用项目中的Alamofire cocoa pod在tableview中动态解析YouTube播放列表。我的项目包含:一个名为“videosViewController”的视图控制器,它包含tableview,一个名为“Video”的类,它保存我正在从youtube API解析的项目,另一个名为“VideoModel”的类保存了削减这些项目的方法。当我运行我的项目时,控制台成功解析了项目,但随后项目在代码行崩溃:

for video in (data["items"] as? NSDictionary)! 

“无法将类型'__NSArrayI'(0x10d2ebd88)的值转换为'NSDictionary'(0x10d2ec288)。”错误如下所示

Project crash

Console details

这里是我使用的代码片段:

videosViewController:

 import UIKit

 class videosViewController: UIViewController, UITableViewDelegate,      UITableViewDataSource {

@IBOutlet var tableView: UITableView!

var videos:[Video] = [Video]()
var selectedVideo: Video?


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    let model = VideoModel()

     model.fetchVideos()

    self.tableView.dataSource = self
    self.tableView.delegate = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return (self.view.frame.size.width / 320)  * 180
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return videos.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "BasicCell")!

    let videoTitle = videos[indexPath.row].videoTitle
    let label = cell.viewWithTag(2) as! UILabel
    label.text = videoTitle

    let videoThumbnailUrlString = "https://i1.ytimg.com/vi/" + videos[indexPath.row].videoId + "/maxresdefault.jpg"

    let videoThumbnailUrl = NSURL(string: videoThumbnailUrlString)

    if videoThumbnailUrl != nil {

        let request = URLRequest(url: videoThumbnailUrl! as URL)

        let session = URLSession.shared

        let task = session.dataTask(with: request,
                                    completionHandler: { (data:Data?,
                                        response:URLResponse?,
                                        error:Error?) -> Void in

                                        DispatchQueue.main.async {

                                        let imageView = cell.viewWithTag(1) as! UIImageView


                                        imageView.image = UIImage(data: data!)

                                        }


        })



    task.resume()
    }

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.selectedVideo = self.videos[indexPath.row]

    self.performSegue(withIdentifier: "goToDetail", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let detailView = segue.destination as! videoDetailViewController

    detailView.selectedVideo = self.selectedVideo
}



}

视频课程:

import UIKit

class Video: NSObject {

var videoId:String = ""
var videoTitle:String = ""
var videoDescription:String = ""
var videoThumbnailURL = ""

}

VideoModel类:

import UIKit
import Alamofire

class VideoModel: NSObject {

let parameters: Parameters = ["part":"snippet","playlistId":"PLMRqhzcHGw1ZRUB86rmNqG15Sr5jV-2NU","key":"AIzaSyDdNXhz3H7ifXB-qfOVakz0Xps2Y-kP0R0"]

var videoArray = [Video]()

func fetchVideos() {


    Alamofire.request("https://www.googleapis.com/youtube/v3/playlistItems", method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in


        switch(response.result) {
        case .success(let JSON):
            print("Success with JSON: \(JSON)")



            if let data = response.result.value as? [String: AnyObject] {
                // print(response.result.value)

                var arrayOfVideos = [Video]()

                for video in (data["items"] as? NSDictionary)! {

                    let videoObj = Video()


                    videoObj.videoId = (video.value as? NSDictionary)?["snippet.resourceId.videoId"] as? String ?? ""
                    videoObj.videoTitle = (video.value as? NSDictionary)?["snippet.title"] as? String ?? ""
                    videoObj.videoDescription = (video.value as? NSDictionary)?["snippet.description"] as? String ?? ""
                    videoObj.videoThumbnailURL = (video.value as? NSDictionary)?["snippet.thumbnails.maxres.url"] as? String ?? ""

                    print(video)

                    // You need to parse the items into the video data
                    arrayOfVideos.append(videoObj)
                }



                self.videoArray = arrayOfVideos

                // }



            }

        case .failure(let error):
            print("Request failed with error: \(error)")
        }
    }

}

1 个答案:

答案 0 :(得分:0)

替换

as? NSDictionary

as? [String:Any]

for video in (data["items"] as? NSDictionary)!

Bcs:你必须将类型Any转换为Swift字典类型[String:Any]。

if let JSON = response.result.value  as?  [String : Any] {
   if let items =  JSON["items"] as? [[String : Any]] {
        for video in items {
              //Other code
        }
   }

}