使用Alamofire调用数据并在Viewcontroller上传入customcell。错误:在展开Optional值

时间:2018-05-08 10:15:33

标签: ios swift null tableview uinib

Crashed Image 当我通过Alamofire检索数据时遇到问题。在这里,我定义了一个函数,其中数据传递给视图控制器并完成。

func getVideoDetail(video_id: String, completionHandler: @escaping (VideoDetail!) -> Void) {
   let PageURL = URL(string: "\(websiteLinks.api)/?type=get_detailss&video_id=\(video_id)")

    Alamofire.request(PageURL!).responseJSON { (response) in
        switch response.result {

        case .success:
            var getDetail: VideoDetail?
            let jsonData = response.data

            do {
                let root = try JSONDecoder().decode(DetailsData.self, from: jsonData!)
                getDetail = root.data
                //THIS IS WHERE YOUR PREVIOUS ERROR OCCURRED
            } catch {
                print("Error: \(error)")
            }
            DispatchQueue.main.async {
               completionHandler(getDetail!)
            }
        case .failure(let error):
            print(error)
        }
    }
}

使用以下代码,我在ViewController中获取数据。

videoModel.getVideoDetail(video_id: video_Id) { (Details) in
        self.videoDetails = Details
        self.playVideo()
    }

这是我的TableView: 这个Cell是Customcell。我在viewDidLoad上注册了所有Customcell(UINIBS)

// REGISTER NIBS FOR THE CELLS
tableView.register(UINib(nibName: "DetailsCell", bundle: nil), forCellReuseIdentifier: "DetailsCell")



 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        switch indexPath.row {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "DetailsCell") as! DetailsCell
            cell.likeLabel.text = videoDetails!.category_name!
            cell.dislikeLabel.text = videoDetails!.category_name!
            cell.delegate = self
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerUserCell") as! PlayerUserCell
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "newestCell") as! NewestCell
            return cell

        }
    }

但是,如果我现在启动应用程序并选择一个单元格,程序将崩溃。我在这里做错了什么?

这是我的HomeController上的didSelectRow代码。我在这里传递了getDetails函数的video_id:

    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let playerVC = storyboard.instantiateViewController(withIdentifier: "playervc") as! PlayerVC
    playerVC.videoURL = URL(string: featuredVideos[indexPath.row - 2].video_location!)
    playerVC.video_Id = featuredVideos[indexPath.row - 2].video_id
    playerVC.commentVideoId = featuredVideos[indexPath.row - 2].id
    self.present(playerVC, animated: true, completion: nil)
}

3 个答案:

答案 0 :(得分:0)

像这样替换;

if let data = jsonData {
    let root = try? JSONDecoder().decode(DetailsData.self, from: data)
    getDetail = root.data
}

如果您的jsondata为零,它将使您的申请崩溃,不会被捕获。

顺便说一下,你应该停止强制变量。那不安全。使用if或guard来防止崩溃。

答案 1 :(得分:0)

      there is nil  `incategory_name` or  `category_name`

像这样使用

 cell.likeLabel.text = videoDetails!.category_name ?? "" 
 cell.dislikeLabel.text = videoDetails!.category_name ?? "" 

答案 2 :(得分:0)

我已经解决了这个问题。

我将详细信息直接加载到CustomCell文件中,然后使用didSet加载UI。代码看起来像这样。

DetailCell:

class DetailsCell: UITableViewCell {
// Temp Helper for Like Video
var like = false
var unlike = false
var likeDislike = LikeDislikeHelper()
var videoModel = VideoModel()

var videoDetails: VideoDetail! {
    didSet {
        updateUI()
    }
}

weak var delegate: DetailsCellDelegate?
@IBOutlet weak var likeButton: AnimatableButton!
@IBOutlet weak var dislikeButton: AnimatableButton!
@IBOutlet weak var shareButton: AnimatableButton!
@IBOutlet weak var playlistButton: AnimatableButton!

@IBOutlet weak var likeLabel: UILabel!
@IBOutlet weak var dislikeLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

}

func getDetails(video_id: String) {
    videoModel.getVideoDetail(video_id: video_id) { (Details) in
        self.videoDetails = Details
    }
}

func updateUI() {
    self.likeLabel.text = "\(videoDetails.likes)"
    self.dislikeLabel.text = "\(videoDetails.dislikes)"
}

的ViewController:

 let cell = tableView.dequeueReusableCell(withIdentifier: "DetailsCell") as! DetailsCell
            cell.checkIsLiked(commentVideoId: commentVideoId)
            cell.getDetails(video_id: video_Id)
            cell.delegate = self
            return cell

感谢所有帮助过的人