Video won't show on UIView Swift 5 - ios

So I'm building an app that has a view that will play a video when the segue is activated. When you run the simulator, you can hear the audio but not the image. Below is the code that I am using:
import UIKit
import AVFoundation
import AVKit
class CongratsVideoController: UIViewController {
#IBOutlet weak var videoView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
private func setupView() {
let path = URL(fileURLWithPath: Bundle.main.path(forResource: "Congrats Screen Apuntalo", ofType: "mov")!)
let player = AVPlayer(url: path)
let newLayer = AVPlayerLayer(player: player)
newLayer.frame = self.videoView.frame
self.videoView.layer.addSublayer(newLayer)
newLayer.videoGravity = AVLayerVideoGravity.resize
player.play()
}
//End of class
}
Any suggestions?

Related

Autoplaying an MP4 video in a UIView that is on loop like a GIF?

Once users go to this specific page, I want the video to immediately start playing inside of a UIView with no controls. It will just loop like a gif. This is code I found off of github and it doesn't seem to work. It just shows the white UIView when I pull up the page. My file name is correct as well.
import Foundation
import UIKit
import AVKit
import AVFoundation
class RampWallPush: UIViewController {
#IBOutlet weak var videoView: UIView!
var player: AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
// Load video resource
if let videoUrl = Bundle.main.url(forResource: "small", withExtension: "mp4") {
// Init video
self.player = AVPlayer(url: videoUrl)
self.player?.isMuted = true
self.player?.actionAtItemEnd = .none
// Add player layer
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
playerLayer.frame = view.frame
// Add video layer
self.videoView.layer.addSublayer(playerLayer)
// Play video
self.player?.play()
// Observe end
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
}
}
// MARK: - Loop video when ended.
#objc func playerItemDidReachEnd(notification: NSNotification) {
self.player?.seek(to: CMTime.zero)
self.player?.play()
}
}
Your code is works you need to verify the file exists in your project and .......
// Load video resource
if let videoUrl = Bundle.main.url(forResource: "sample", withExtension: "mp4") {
// exists
}
else {
print("NoFile")
}
So select the file and
You need to change the frame
playerLayer.frame = CGRect(x:0,y:0,width:200,height:300)
self.videoView.layer.addSublayer(playerLayer)
playerLayer.center = videoView.center
Created a demo Here

xcode: How to Play a video within the ViewController

I want to play a video in my ViewController(not in seperate ViewController).
in another words, i want to play my video in a rectangular View in my viewController. just like instagram posts. but i didn’t found any view in object library for that...!
You can try something like this
import AVKit
import AVFoundation
class VideoPlayerViewController: UIViewController {
#IBOutlet weak var videoPreviewLayer: UIView!
private var player: AVPlayer!
private var playerViewController = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
playVideoInView()
}
func playVideoInView() {
guard let path = NSBundle.mainBundle().pathForResource("videoName", ofType: "mp4") else {
return
}
let url = NSURL.fileURLWithPath(path)
player = AVPlayer(url: url)
playerViewController = AVPlayerViewController()
playerViewController.player = player
playerViewController.view.frame = videoPreviewLayer.frame
self.addChildViewController(playerViewController)
self.view.addSubview(playerViewController.view)
}
}
playVideoInView function has what you need

play video in background swift 3

hello im trying to play video in background but its give an error and the error is " unexpectedly found nil while unwrapping an Optional value " and im already set the video in Bundle and select copy if need
this the my code
import UIKit
import AVFoundation
class ViewController: UIViewController {
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "Grad_Cap_Toss", withExtension: "mp4")
avPlayer = AVPlayer(url: url!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEnd.none
avPlayerLayer.frame = view.layer.bounds
view.backgroundColor = UIColor.clear;
view.layer.insertSublayer(avPlayerLayer, at: 0)
NotificationCenter.default.addObserver(self,selector: Selector(("playerItemDidReachEnd:")),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: avPlayer.currentItem)
}
please any body have ideas for that , thank you
First, drag and drop video file in your project.
Then import AVFundation.
Add example: var player: AVPlayer?
#IBOutlet weak var videoView: UIView! - Connect view from storyboard to your VC class.
After that, you paste this code into your ViewController.
call "playBackgoundVideo()" in your viewDidLoad()
private func playBackgoundVideo() {
if let filePath = Bundle.main.path(forResource: "your_video_here", ofType:"mp4") {
let filePathUrl = NSURL.fileURL(withPath: filePath)
player = AVPlayer(url: filePathUrl)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.videoView.bounds
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: nil) { (_) in
self.player?.seek(to: kCMTimeZero)
self.player?.play()
}
self.videoView.layer.addSublayer(playerLayer)
player?.play()
}
}
This is swift 4.0
it works ^__^
I had a similar problem and followed the instructions from Rick's answer to resolve it.
My problem was that I didn't have the video file in the bundle resources.
Check if your video file is listed in Copy Bundle Resources under Build Phases in the project. If not , use the + button to add the file in there.
Also you might be missing the avPlayer.play() statement in your code.
I was also trying to play a video in the background of my login page's view controller. I think the main issue is that the syntax you're using is deprecated.
Your code might look like the following:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet var blackOverlay: UIView!
// init video background and its path
var player: AVPlayer?
let videoURL: NSURL = Bundle.main.url(forResource: "videoName", withExtension: "mp4")! as NSURL
override func viewDidLoad() {
super.viewDidLoad()
// Adds a black overlay to the looped video in question
blackOverlay.alpha = 0.75;
blackOverlay.layer.zPosition = 0;
// begin implementing the avplayer
player = AVPlayer(url: videoURL as URL)
player?.actionAtItemEnd = .none
player?.isMuted = true
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
playerLayer.zPosition = -1
playerLayer.frame = view.frame
view.layer.addSublayer(playerLayer)
player?.play()
// add observer to watch for video end in order to loop video
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.loopVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player)
// if video ends, will restart
func playerItemDidReachEnd() {
player!.seek(to: kCMTimeZero)
}
}
// maybe add this loop at the end, after viewDidLoad
// func loopVideo() { player?.seek(to: kCMTimeZero) player?.play()}}
Please let me know if this helps!
Drag and drop video file in your project.
Then import AVFundation
List item
#IBOutlet weak var videoView: UIView!, #IBOutlet weak var label: UILabel!,#IBOutlet weak var image: UIImageView!,#IBOutlet weak var loginBtn: UIButton!
Connect view from storyboard to your VC class.
And then paste the given code in your ViewController and call playVideo() function in viewDidLoad().
func playVideo(){
guard let path = Bundle.main.path(forResource: "intro", ofType: "mp4") else {
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
playerLayer.videoGravity = .resizeAspectFill
self.videoLayer.layer.addSublayer(playerLayer)
player.play()
videoLayer.bringSubviewToFront(image)
videoLayer.bringSubviewToFront(label)
videoLayer.bringSubviewToFront(loginBtn)
videoLayer.bringSubviewToFront(signupBtn)
}
If url is nil and the video is being successfully copied into the bundle, the likely problem is case sensitivity. Make sure the filename is using the correct case. The iOS device filesystem is case sensitive, where as the iPhone simulator is not.
I had a same problem when I tried to play video background. I think it is the problem of video resource.
I resolved the problem like this way.
When you drag your video, you should check both of 'Copy items if needed' and 'Add to targets'.
Or you can just right click on the project navigator, click 'Add' to add resource.

AVPlayer playback with Swift 2.0

I'm having issues with playing back a video. All I want is for the video to playback after the launch image has been displayed. I followed this (https://www.youtube.com/watch?v=iYATp9--VIM) tutorial but when I simulated I received a blank screen.
Here is the code:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet var videoView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupView() {
let path = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("streetview", ofType: "mov")!)
let player = AVPlayer(URL:path)
let newLayer = AVPlayerLayer(player: player)
newLayer.frame = self.videoView.frame
self.videoView.layer.addSublayer(newLayer)
newLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
player.play()
}
}
Please help me if you can!
If you're just getting a blank black screen, it would generally point to an issue with the source of the video. I'd check that you're spelling the name of your file correctly and that it definitely is a .mov file.
I use this code to launch the AVPlayer and play my video. It plays a video from a URL from the internet. I have it inside my button function so it happens when the user presses the play button I have:
let videoURL = NSURL(string: "YOUR URL") {
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
I can confirm this works for me in Swift 2.0

Implementing video view in the Storyboard

I want to build simple video app thats views a video form youtube links thats users add.
I didn't find "VideoView" I mean If image view is for image what is UIView for videos.
There is no object in the original library that performs video viewing function. But you can import the MediaPlayer framework in your project and add it programmatically.
Here is a Swift example
import MediaPlayer
class Step1ViewController: UIViewController {
var moviePlayer: MPMoviePlayerController?
override func viewDidLoad() {
super.viewDidLoad()
playVideo()
}
func playVideo() {
let videoView = UIView(frame: CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y, self.view.bounds.width, self.view.bounds.height))
let pathToEx1 = NSBundle.mainBundle().pathForResource("myVideoFile", ofType: "mp4")
let pathURL = NSURL.fileURLWithPath(pathToEx1!)
moviePlayer = MPMoviePlayerController(contentURL: pathURL)
if let player = moviePlayer {
player.view.frame = videoView.bounds
player.prepareToPlay()
player.scalingMode = .AspectFill
videoView.addSubview(player.view)
}
self.view.addSubview(videoView)
}
}
As for further customisations and app notifications it has a bunch of in-build possibilities. So check it out.
To play video apple has provided MPMovieViewController
see this https://developer.apple.com/library/prerelease/ios/documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/index.html
and this
http://www.brianjcoleman.com/tutorial-play-video-swift/
In youtube Video case we got embedded links are used so for that you will get help from this https://github.com/gilesvangruisen/Swift-YouTube-Player
import AVFoundation
import AVKit
class ViewController: UIViewController {
var player = AVPlayer()
var playerController = AVPlayerViewController()
func playVideo() {
let videoURL = NSURL(string: videoUrl)
player = AVPlayer(url: videoURL! as URL)
let playerController = AVPlayerViewController()
playerController.player = player
self.addChildViewController(playerController)
// Add your view Frame
playerController.view.frame = self.view.frame
// Add subview in your view
self.view.addSubview(playerController.view)
player.play()
}
func stopVideo() {
player.pause()
}
}
In Xcode 10 (with a bit less code):
In the interface builder (Storyboard), add "AVKit Player View Controller"
Create a View Controller that derives from AVPlayerViewController:
import UIKit
import AVKit
class VideoPlayerViewController: AVPlayerViewController {
override func viewDidLoad() {
super.viewDidLoad()
let videoURL = Bundle.main.url(forResource: "video", withExtension: "mp4")!
self.player = AVPlayer(url: videoURL)
}
override func viewDidAppear(_ animated: Bool) {
self.player?.play()
}
}
Don't forget to connect this custom class in the storyboard's identity inspector :)
Note: this example uses video URL pointing to a bundle's resource.

Resources