Application tried to present modally a view controller that has a parent view controller crash

Thread 1: "Application tried to present modally a view controller <AVPlayerViewController: 0x15f83ee00> that has a parent view controller <ValorantAgentsApp.AbilitiesDetailsViewController: 0x15e918670>."

I get error when tried to play video in my app. My application crashes when it comes to the screen where I will play a video. I don’t have a problem when I play the video with by pressing a button. But when I want to play as the screen loads, I get a crash.


import UIKit
import AVKit
import AVFoundation
import MediaPlayer
import MobileCoreServices


class AbilitiesDetailsViewController: UIViewController, AVPlayerViewControllerDelegate {

    @IBOutlet var skillDetailsLabel: UILabel!
    @IBOutlet var skillNameLabel: UILabel!
    @IBOutlet var heroIconImageView: UIImageView!
    var agentAbilitiesVideoURL = ""
    var choosenAgentSkillName = ""
    var choosenAbilitiesImages : UIImage?
 
    override func viewDidLoad() {
       
        skillNameLabel.text = choosenAgentSkillName
        heroIconImageView.image = choosenAbilitiesImages
        super.viewDidLoad()
  
playAbilitiesVideos()
        
    }
  
    
    func playAbilitiesVideos() {
        let player = AVPlayer(url: URL(string: agentAbilitiesVideoURL)!)
                let controller = AVPlayerViewController()
                                       present(controller, animated: true) {  }
                controller.player = player
                                       addChild(controller)
                view.addSubview(controller.view)
        controller.view.frame = CGRect(x: 50 , y: 50, width: 300, height: 300)
       
                controller.player = player
                controller.showsPlaybackControls = true
                player.isClosedCaptionDisplayEnabled = false
                player.play()
    }

   
    /*
    @IBAction func playVideoUsingURL(_ sender: Any) {
            playGlobalVideo()
        }

        func playGlobalVideo() {
            guard let videoURL = URL(string: agentAbilitiesVideoURL) else {
                return
            }
            let player = AVPlayer(url: videoURL)
            let vc = AVPlayerViewController()
            vc.player = player
            present(vc, animated: true) {
                player.play()
            }
        }
 
    */
}

This is my third screen and view controller.

>Solution :

either do:
view.addSubview(controller.view)
OR
present(controller, animated: true) { }
not both

Leave a Reply