I have a short mp4
video file that I've added to my current Xcode6 Beta project.
I want to play the video in my app.
After hours searching, I can't find anything remotely helpful. Is there a way to accomplish this with Swift or do you have to use Objective-C? Can I get pointed in the right direction? I can't be the only one wondering this.
Sure you can use Swift!
Add the video (lets call it video.m4v
) to your Xcode project
Open the Project Navigator
cmd + 1
Then select your project root
> your Target
> Build Phases
> Copy Bundle Resources
.
Your video MUST be here. If it's not, then you should add it using the plus button
Open your View Controller and write this code.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
private func playVideo() {
guard let path = Bundle.main.path(forResource: "video", ofType:"m4v") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true) {
player.play()
}
}
}