我尝试使用MPMoviePlayerController播放视频。设置是:我推送一个新的ViewController,然后在viewDidLoad中设置视图和电影播放器实例,然后使用NSURLSession.sharedSession()。dataTaskWithURL(),我在其中加载电影的REST资源以给我URL。在完成块中,我将电影播放器实例的contentUrl设置为此URL并说出播放。但是,电影画面保持黑色。如果我在viewDidLoad,viewWillAppear或viewDidAppear中将contentUrl硬编码为url,则电影显示正常。 errorLog和accessLog都是零。 所以我假设异步URL加载和分配电影contentUrl有问题。
设置:Swift,Xcode 6 beta,iOS 8。
下面是一些代码段:
class PresentationsViewController {
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let presentationViewController = PresentationViewController(presentations[indexPath.row])
navigationController.pushViewController(presentationViewController, animated: true)
}
}
class PresentationViewController {
var presentation: Presentation?
var moviePlayer: MPMoviePlayerController?
convenience init(_ presentation: Presentation) {
self.init()
self.presentation = presentation
}
override func viewDidLoad() {
super.viewDidLoad()
moviePlayer = MPMoviePlayerController()
moviePlayer!.view.frame = CGRect(x: X, y: Y, width: W, height: H)
moviePlayer!.movieSourceType = MPMovieSourceType.Unknown
moviePlayer!.controlStyle = MPMovieControlStyle.Embedded
NSURLSession.sharedSession().dataTaskWithURL(presentation.url) { data, response, error in
// Some JSON parsing etc.
self.moviePlayer!.contentURL = presentation.videoUrl
self.moviePlayer!.prepareToPlay()
self.moviePlayer!.play()
}.resume()
view.addSubview(moviePlayer.view)
}
}
答案 0 :(得分:1)
我不确定这是否是Swift测试版或iOS 8测试版中的错误,但更改代码以使用AVPlayer工作。
import AVFoundation
import AVKit
let playerViewController = AVPlayerViewController()
// In async block:
if let player = AVPlayer.playerWithURL(url) as? AVPlayer {
playerViewController.player = player
}