ViewController没有调用deinit方法swift 4

时间:2017-10-13 05:55:42

标签: iphone swift ios11 swift4

我有这个VC,我在那里播放视频背景登录。 两个按钮作为出口直接从故事板触发UIStoryboard Push Segue。

我想要达到的目标是:一旦我通过segue访问任何一个VC,视频登录VC就会停止进一步保留周期,一旦我回到我的应用程序的正常流程。

提前感谢。

@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var registerButton: UIButton!
weak var avPlayer: AVPlayer!
weak var avPlayerLayer: AVPlayerLayer!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.loginButton = Util.roundBorderButton(button: self.loginButton, color: UIColor.white.cgColor, radius: 5, width: 1)
    self.registerButton = Util.roundBorderButton(button: self.registerButton, color: UIColor.white.cgColor, radius: 5, width: 1)

    if let resourceUrl = Bundle.main.url(forResource: "porsche-trimmed", withExtension: "mp4") {
        if FileManager.default.fileExists(atPath: resourceUrl.path) {

            avPlayer = AVPlayer(url: resourceUrl)
            avPlayerLayer = AVPlayerLayer(player: avPlayer)
            avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
            avPlayer.volume = 0
            avPlayer.actionAtItemEnd = .none

            avPlayerLayer.frame = view.layer.bounds
            view.backgroundColor = .clear
            view.layer.insertSublayer(avPlayerLayer, at: 0)

            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(playerItemDidReachEnd(notification:)),
                                                   name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                                   object: avPlayer.currentItem)
        }
    }
}

@objc func playerItemDidReachEnd(notification: Notification) {
    let p: AVPlayerItem = notification.object as! AVPlayerItem
    p.seek(to: kCMTimeZero, completionHandler: nil)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    avPlayer.play()
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    NotificationCenter.default.removeObserver(self)
}

deinit {
    print("deinit video")
}

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

2 个答案:

答案 0 :(得分:0)

通知中心可能会保留您的控制器吗?尝试评论通知订阅,看看问题是否消失。如果是,请选择一个合适的位置(viewWillDisappear?)来取消订阅。

答案 1 :(得分:0)

案例1:

尝试在NotificationCenter.default.removeObserver(self)中撰写override func viewWillDisappear(_ animated: Bool)行。 可能是通知中心保留viewController的对象。

案例2: 如果您使用Segue从控制器导航,则UIStoryboardSegue将viewController的对象保留为源viewController。 在这种情况下,第一种情况也可以解决您的问题。