I am playing a video in my app in TVos. I am using AVPlayerViewController to play the video. But when i press Menu button on Apple Tv remote i goes back to the view controller from which i came here but video continues to play and after 8 or 10 second it gets deallocated. This is really a bad bug and i am stuck on this for few days. Any help will be highly appreciated.
Here is my code for the view controller.
import Foundation
import UIKit
import AVKit
class ViewController : UIViewController {
var avplayerVC : AVPlayerViewController?
var recentlyWatchedTimer : NSTimer?
var lessonToWatch : Lesson?
override func viewDidLoad() {
super.viewDidLoad()
if let urlVideo = lessonToWatch?.lessonurl {
let activityIndicator = UIActivityIndicatorView(frame: CGRectMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0, 30.0, 30.0))
let asset : AVURLAsset = AVURLAsset(URL: NSURL.init(string: urlVideo)!, options: nil)
let keys = ["playable"];
avplayerVC = AVPlayerViewController()
weak var weakSelf = self
asset.loadValuesAsynchronouslyForKeys(keys) { () -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
weakSelf!.avplayerVC?.player = AVPlayer(playerItem: AVPlayerItem(asset: asset))
weakSelf!.avplayerVC?.player?.seekToTime(kCMTimeZero)
print("Status 1: " + "\(self.avplayerVC?.player?.status.rawValue)")
print(self.view?.frame)
// doesn't work
weakSelf!.avplayerVC?.view.frame = self.view.frame
activityIndicator.stopAnimating()
activityIndicator.removeFromSuperview()
weakSelf!.view.addSubview((self.avplayerVC?.view!)!)
weakSelf!.avplayerVC?.player?.play()
weakSelf!.recentlyWatchedTimer = NSTimer.scheduledTimerWithTimeInterval(20.0, target: self, selector: "addToRecentlyWatched" , userInfo: nil, repeats: false)
})
}
print("In LessonPlayViewController View Did Load")
self.view.addSubview(activityIndicator)
activityIndicator.startAnimating()
}
}
func addToRecentlyWatched() {
if let lesson = lessonToWatch {
DataManager.sharedInstance.addRecentlyWatch(lesson)
}
recentlyWatchedTimer?.invalidate()
}
deinit {
print("deinit")
avplayerVC?.view.removeFromSuperview()
avplayerVC?.player = nil
avplayerVC = nil
}
// MARK : AVPlayerViewControllerDelegate
}