Ben Thomas
Ben Thomas

Reputation: 105

removeFromSuperview not working - Swift

Please see below code. I am trying to remove the video subview from view when the 'done' button is pressed or video stops playing. I show no errors in the code but the removeFromSubview method does not seem to be working. I am not sure if my syntax is wrong or if it is something to do with having the movieplayer code within the IBAction method and the moviePlayBackDidFinish outside below the viewDidLoad. Any advise much appreciated. Thanks

import Foundation
import UIKit
import MediaPlayer

class VideoViewController: UIViewController {

var moviePlayer:MPMoviePlayerController!

@IBAction func videoLaunch(sender: AnyObject) {
playVideo()
}
func playVideo() {
let path = NSBundle.mainBundle().pathForResource("MyVideo", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
moviePlayer = MPMoviePlayerController(contentURL: url)
if let player = moviePlayer {
player.view.frame = self.view.bounds
moviePlayer?.controlStyle = MPMovieControlStyle.Fullscreen
player.prepareToPlay()
self.view.addSubview(player.view)

}  
}


override func viewDidLoad() {
super.viewDidLoad()

NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "moviePlayBackDidFinish:",
    name: MPMoviePlayerPlaybackDidFinishNotification,
    object: moviePlayer)


func moviePlayBackDidFinish(notification: NSNotification){
    self.view.removeFromSuperview()
}



}
}

Upvotes: 1

Views: 3934

Answers (1)

Midhun MP
Midhun MP

Reputation: 107131

You are trying to remove self.view not moviePlayer.view.

Change your moviePlayBackDidFinish code to:

func moviePlayBackDidFinish(notification: NSNotification)
{
    if let player = moviePlayer
    {
      player.view.removeFromSuperview()
    }
}

Upvotes: 1

Related Questions