Reputation: 123
I am very new to coding and have no experience. I have found a way to make a video play but it autoplays / autopens. I need the video to only open and play when a button is pressed. Please can someone help me tweak my code to do this.
This is my current code:
import UIKit
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var playerviewcontroller = AVPlayerViewController()
var playerview = AVPlayer ()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
var fileURL = NSURL(fileURLWithPath:"/Users/MorganEvans/Documents/Apps/Warm Up/Video View/Video View/ViewController.swift")
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Upvotes: 2
Views: 1849
Reputation: 578
this is how a button would set up to look, this example is pulling a movie from firebase but other than that this is how it would look
@IBAction func playV(sender: UIButton) {
let amovieUrl:NSURL? = NSURL(string: "https://firebasestorage.googleapis.com/v0/b/messenger-test-d225b.appspot.com/o/test%2FTestVideo.mov?alt=media&token=bd4ccba3-b446-43bc-809e-b1152aa3c2ff")
if let aurl = amovieUrl {
self.avPlayer = AVPlayer(url: aurl as URL)
self.avPlayerViewController.player = self.avPlayer
self.present(self.avPlayerViewController, animated: true) { () -> Void in
self.avPlayerViewController.player?.play()
}
}
}
Upvotes: 1
Reputation: 7736
Try this:
@IBAction func playMusic(sender: AnyObject) {
var fileURL = NSURL(fileURLWithPath:"/Users/MorganEvans/Documents/Apps/Warm Up/Video View/Video View/ViewController.swift")
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}
You can simply put it anywhere in your ViewController
, as long as it is not inside another function.
Then connect it with a button in your storyboard:
Upvotes: 1
Reputation: 8193
viewDidAppear
to the action you created in step 1.Also, you don't need those default implementation for viewDidLoad
and didReceiveMemoryWarning
:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var playerviewcontroller = AVPlayerViewController()
var playerview = AVPlayer ()
@IBAction func yourActionForButton(sender: UIButton) {
// Your code.
}
Upvotes: 0