How can I stop the videobackground? [duplicate] - ios

This question already has answers here:
How do i keep UISwitch state when changing ViewControllers?
(3 answers)
Closed 4 years ago.
How can I stop the videobackground when I move to another viewcontroller?
because when I move to another viewcontroller, the video and background music continue to be played, and when I go back to the main page two videos overlap. so I would like the video and the music to stop when I move to another viewcontroller, such as when I move in the viewcontroller for the sign up
import UIKit
import SwiftVideoBackground
import Firebase
import FirebaseAuth
class ViewController: UIViewController {
private let videoBackground = VideoBackground()
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var mute_img: UIImageView!
#IBOutlet private var muteSwitch: UISwitch!
#IBAction func `switch`(_ sender: UISwitch) {
if (sender.isOn == true)
{
mute_img.isHidden = false
videoBackground.isMuted = true
}
else
{
mute_img.isHidden = true
videoBackground.isMuted = false
}
let shouldMute = sender.isOn
videoBackground.isMuted = shouldMute
UserDefaults.standard.set(shouldMute, forKey:"isMuted")
}
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
let shouldMute = userDefaults.bool(forKey: "isMuted")
videoBackground.play(view: view, videoName: "intro", videoType:
"mp4", isMuted: shouldMute, willLoopVideo : true)
muteSwitch.isOn = shouldMute
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == usernameField {
passwordField.becomeFirstResponder()
} else if textField == passwordField {
textField.resignFirstResponder()
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Follow the steps:
1) Make an IBOutlet for the switch
#IBOutlet private var muteSwitch: UISwitch!
Don't forget to connect it to the switch in the storyboard.
2) Read the saved value from UserDefaults ( in viewDidLoad ):
override
func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
let shouldMute = userDefaults.bool(forKey: "isMuted")
videoBackground.play(view: view, videoName: "intro", videoType: "mp4", isMuted: shouldMute, alpha : 0.25, willLoopVideo : true)
muteSwitch.isOn = shouldMute
}
3) Save the switch value to UserDefaults ( in #IBAction func `switch`...) :
#IBAction func `switch`(_ sender: UISwitch) {
let shouldMute = sender.isOn
videoBackground.isMuted = shouldMute
UserDefaults.standard.set(shouldMute, forKey:"isMuted")
}

1. Objective - C Version
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UISwitch *bluetoothSwitch;
- (IBAction)saveSwitchState:(id)sender;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"SwitchState"])
self.bluetoothSwitch.on = [defaults boolForKey:#"SwitchState"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)saveSwitchState:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([self.bluetoothSwitch isOn])
[defaults setBool:YES forKey:#"SwitchState"];
else
[defaults setBool:NO forKey:#"SwitchState"];
}
#end
Swift Version
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var stateSwitch: UISwitch!
#IBAction func buttonClicked(_ sender: Any) {
if stateSwitch.isOn {
textField.text = "The Switch is Off"
stateSwitch.setOn(false, animated:true)
} else {
textField.text = "The Switch is On"
stateSwitch.setOn(true, animated:true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
stateSwitch.addTarget(self, action: #selector(stateChanged), for: UIControlEvents.valueChanged)
}
#objc func stateChanged(switchState: UISwitch) {
if switchState.isOn {
textField.text = "The Switch is On"
} else {
textField.text = "The Switch is Off"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
if userDefaults.value(forKey: "isMuted") != nil{
let object = userDefaults.value(forKey: "isMuted") as? NSNumber
yourSwitch.isOn = (object?.boolValue)!
}
}
#IBAction func switchChanged(sender: UISwitch) {
let uDefault = UserDefaults.standard
if sender.isOn {
uDefault.setValue(NSNumber(value: true), forKey:"isMuted")
}
else {
uDefault.setValue(NSNumber(value: false), forKey:"isMuted")
}
}

Related

How can I stop the video background when I move to another viewcontroller?

How can I stop the video background when I move to another UIViewController?
because when I move to another UIViewController, the video and background music continue to be played, and when I go back to the main page two videos overlap. so I would like the video and the music to stop when I move to another UIViewController, such as when I move in the UIViewController for the sign up
import UIKit
import SwiftVideoBackground
import Firebase
import FirebaseAuth
class ViewController: UIViewController {
private let videoBackground = VideoBackground()
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var mute_img: UIImageView!
#IBOutlet private var muteSwitch: UISwitch!
#IBAction func `switch`(_ sender: UISwitch) {
if (sender.isOn == true)
{
mute_img.isHidden = false
videoBackground.isMuted = true
}
else
{
mute_img.isHidden = true
videoBackground.isMuted = false
}
let shouldMute = sender.isOn
videoBackground.isMuted = shouldMute
UserDefaults.standard.set(shouldMute, forKey:"isMuted")
}
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = UserDefaults.standard
let shouldMute = userDefaults.bool(forKey: "isMuted")
videoBackground.play(view: view, videoName: "intro", videoType:
"mp4", isMuted: shouldMute, willLoopVideo : true)
muteSwitch.isOn = shouldMute
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == usernameField {
passwordField.becomeFirstResponder()
} else if textField == passwordField {
textField.resignFirstResponder()
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Forward navigation :
videoBackground.pause()
Back navigation :
videoBackground.resume()
As per the Documentation:
You can simply use the pause()
When leaving the Controller
videoBackground.pause()
When Back to Controller:
videoBackground.resume()

Using same button to Play/Pause and loop audio in AVFoundation

I have tried linking the action to the same button but this stops the button from working altogether. I can get it working using the same code if I create a separate button:
#IBAction func Play(sender: AnyObject) {
SoundPlayer.play()
}
#IBAction func stop(sender: AnyObject) {
SoundPlayer.stop()
}
I also need the audio to loop.
Using Nirav code:
class ViewController: UIViewController {
var SoundPlayer:AVAudioPlayer = AVAudioPlayer()
#IBOutlet var btnPlay: UIButton!
#IBOutlet var btnStop: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let FileLocation = NSBundle.mainBundle().pathForResource("Aspirin", ofType: ".mp3")
do {
SoundPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: FileLocation!))
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)
}
catch {
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func btnTap(sender: UIButton) {
if (sender == self.btnPlay) {
}
else if (sender == self.btnStop) {
}
}
}
1 - Screenshot of storyboard
You can do that just create IBOutlet of both button like this
#IBOutlet var btnPlay: UIButton!
Now bind this action to both button
#IBaction func btnTap(sender: UIButton) {
if (!sender.selected) {
SoundPlayer.play()
}
else {
SoundPlayer.stop()
}
sender.selected = !sender.selected
}
Hope this will help you

segmentedcontrol / textfield / DidChange

I have a segmentedControl that give a string to a textfield. also i have 2 another textfields. one is for user input and the second for make a calculation from segmentedcontrol textfield and user input textfield. How can i automatically update the calculation textfield when segmentedcontrolindex will change.
For user input textfield the textfielddidchangemethod works. Thanks
#IBOutlet weak var segmentedcontrol: UISegmentedControl!
#IBOutlet weak var textf: UITextField!
#IBOutlet weak var textf1: UITextField!
#IBOutlet weak var textf2: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textf.delegate = self
textf1.delegate = self
textf2.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func textf1(sender: AnyObject) {
let result = (textf.text! as NSString).doubleValue * (textf2.text! as NSString).doubleValue
textf1.text = String(format:"%.2f", result)
}
#IBAction func segmentedcontrolAction(sender: AnyObject) {
if(segmentedcontrol.selectedSegmentIndex == 0)
{
textf2.text = "5";
}
else if(segmentedcontrol.selectedSegmentIndex == 1)
{
textf2.text = "10";
}
else if(segmentedcontrol.selectedSegmentIndex == 2)
{
textf2.text = "15";
}
}
#IBAction func segmentedcontrolAction(sender: AnyObject)
{
if(segmentedcontrol.selectedSegmentIndex == 0)
{
textf2.text = "5";
}
else if(segmentedcontrol.selectedSegmentIndex == 1)
{
textf2.text = "10";
}
else if(segmentedcontrol.selectedSegmentIndex == 2)
{
textf2.text = "15";
}
let result = (textf.text! as NSString).doubleValue * (textf2.text! as NSString).doubleValue
textf1.text = String(format:"%.2f", result)
}

Swift 2 + Xcode 7: Sound playing when wrong button is pressed

I have a problem with a little App I am programming & learning with. I finally added a sound that it's supposed to play when you press a Stepper, and it does, the problem is that it's also playing when you press a different button.
I honestly have no idea why it happens and how to fix it.
Any help?
here's my code:
ViewONE (here the button that shouldn't be playing the audio file is "BotonLetsBegin"
//
// ViewONE.swift
// Simple Score
//
// Created by Juan Francisco Mellado on 10/1/15.
// Copyright © 2015 Juan Francisco Mellado. All rights reserved.
//
import Foundation
import UIKit
class ViewONE: UIViewController, UITextFieldDelegate {
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
#IBOutlet weak var ScrollViewOne: UIScrollView!
#IBOutlet weak var teamRedName: UITextField!
#IBOutlet weak var initScoreRed: UITextField!
#IBAction func BotonLetsBeginAction(sender: UIButton) {
}
#IBOutlet weak var BotonLetsBegin: UIButton!
#IBOutlet weak var teamBlueName: UITextField!
#IBOutlet weak var initScoreBlue: UITextField!
#IBAction func userTappedBackground(sender: AnyObject) {
view.endEditing(true)
}
#IBAction func userTappedThisView(sender: AnyObject) {
view.endEditing(true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let DestViewController : ViewTwo = segue.destinationViewController as! ViewTwo
// Cambiamos los valores si no existen a 0
if(initScoreRed.text == ""){
initScoreRed.text = "0"
}
if(initScoreBlue.text == ""){
initScoreBlue.text = "0"
}
//---------
DestViewController.RedName = teamRedName.text!
DestViewController.BlueName = teamBlueName.text!
DestViewController.RedScore = initScoreRed.text!
DestViewController.BlueScore = initScoreBlue.text!
}
override func viewDidLoad() {
super.viewDidLoad()
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
BotonLetsBegin.layer.cornerRadius = 5
self.initScoreBlue.delegate = self
self.initScoreRed.delegate = self
}
let TEXT_FIELD_LIMIT = 3
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
switch textField {
case initScoreBlue:
return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= TEXT_FIELD_LIMIT
case initScoreRed:
return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= TEXT_FIELD_LIMIT
case teamBlueName:
return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= 25
case teamRedName:
return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= 25
default:
return true
}
}
//For Swift 1.2
//return count((textField.text ?? "").utf16) + count(string.utf16) - range.length <= TEXT_FIELD_LIMIT
override func shouldAutorotate() -> Bool {
return false
}
func textFieldDidBeginEditing(textField: UITextField) {
if (textField == initScoreBlue){
ScrollViewOne.setContentOffset(CGPointMake(0, 250), animated: true)
}
if (textField == teamBlueName){
ScrollViewOne.setContentOffset(CGPointMake(0, 250), animated: true)
}
if (textField == teamRedName){
ScrollViewOne.setContentOffset(CGPointMake(0, 100), animated: true)
}
if (textField == initScoreRed){
ScrollViewOne.setContentOffset(CGPointMake(0, 100), animated: true)
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
ScrollViewOne.setContentOffset(CGPointMake(0, 0), animated: true)
}
// - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//[textField resignFirstResponder];
//}
}
Here is ViewTwo where the steppers are
//
// ViewTWO.swift
// Simple Score
//
// Created by Juan Francisco Mellado on 9/29/15.
// Copyright © 2015 Juan Francisco Mellado. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
class ViewTwo : UIViewController, AVAudioPlayerDelegate {
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
/// Actions de sonido -------
#IBAction func stepperSoundRed(sender: UIStepper) {
audioPlayer.play()
}
#IBAction func stepperSoundBlue(sender: UIStepper) {
audioPlayer.play()
}
/////////////////////////
// el nombre del equipo Blue
#IBOutlet weak var teamBlueTextLabel: UILabel!
var BlueName = String()
// nombre del equipo rojo
#IBOutlet weak var teamRedTextLabel: UILabel!
var RedName = String()
// score inicial del equipo rojo
#IBOutlet weak var RedScoreLabel: UILabel!
var RedScore = String()
// score initcial equipo azul
#IBOutlet weak var BlueScoreLabel: UILabel!
var BlueScore = String()
// que funcionen los Steppers
#IBOutlet weak var RedStepperUI: UIStepper!
#IBOutlet weak var BlueStepperUI: UIStepper!
// Botón Done
#IBOutlet weak var BotonDone: UIButton!
#IBAction func BlueStepperValueChange(sender: UIStepper) {
BlueScoreLabel.text = Int(sender.value).description
}
#IBAction func RedStepperValueChange(sender: UIStepper) {
RedScoreLabel.text = Int(sender.value).description
}
// archivos de sonidos
var sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping2", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
required init? (coder aDecoder: NSCoder){
super.init(coder: aDecoder)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: sound, fileTypeHint: nil)
audioPlayer.prepareToPlay()
audioPlayer.delegate = self
audioPlayer.play()
} catch {
// Errors here
}
}
// VIEW DID LOAD
override func viewDidLoad() {
// No se para que es esto??
super.viewDidLoad()
BotonDone.layer.cornerRadius = 5
// Checamos si están vacios los nombres
if BlueName.isEmpty {
BlueName = "TEAM BLUE"
}
if RedName.isEmpty {
RedName = "TEAM RED"
}
// Proseguimos a asignarlos a las Labels
teamBlueTextLabel.text = BlueName
teamRedTextLabel.text = RedName
RedScoreLabel.text = RedScore
BlueScoreLabel.text = BlueScore
// Aqui vemos el Red +/-
RedStepperUI.wraps = true
RedStepperUI.autorepeat = false
RedStepperUI.value = Double(RedScore)!
RedStepperUI.maximumValue = 999
// aqui vemos el Blue +/-
BlueStepperUI.wraps = true
BlueStepperUI.autorepeat = false
BlueStepperUI.value = Double(BlueScore)!
BlueStepperUI.maximumValue = 999
//
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
override func shouldAutorotate() -> Bool {
return false
}
}
Your issue is in init(...) method of ViewTwo. You create a player and call the play() method :
required init? (coder aDecoder: NSCoder){
super.init(coder: aDecoder)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: sound, fileTypeHint: nil)
audioPlayer.prepareToPlay()
audioPlayer.delegate = self
audioPlayer.play() // this is your problem ;)
} catch {
// Errors here
}
}

How do i keep UISwitch state when changing ViewControllers?

When I move from one view controller to another, the switch on the first controller resets itself and does not retain its state.
How can I make it save its state when come back to it after viewing other controllers? And how do I make it save its state after closing the app. I have looked at the various stackOverflow questions and responses and the apple documentation, but nothing seems to work.
Here is my class for the View Controller that has the switch.
class Days: UIViewController {
#IBOutlet weak var switchButton: UISwitch!
var switchState = true
let switchKey = "switchState"
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func saveSwitchPressed(sender:AnyObject) {
if self.switchButton.on {
self.switchState = true
NSUserDefaults.standardUserDefaults().setBool(self.switchState, forKey: switchKey)
NSUserDefaults.standardUserDefaults().synchronize()
println(NSUserDefaults.standardUserDefaults().boolForKey(switchKey))
} else {
self.switchState = false
NSUserDefaults.standardUserDefaults().setBool(self.switchState, forKey: switchKey)
NSUserDefaults.standardUserDefaults().synchronize()
println(NSUserDefaults.standardUserDefaults().boolForKey(switchKey))
}
}
}
I'm a beginner to Swift and generally Xcode. Thank you in advance for your time and help :)
Xcode 8.3 • Swift 3.1
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var switchButton: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
switchButton.isOn = UserDefaults.standard.bool(forKey: "switchState")
}
#IBAction func saveSwitchPressed(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
}
}
Since you're syncing the on/off state of the switch you could on viewWillAppear: or viewDidAppear: set the state of the switch to the value stored in NSUserDefaults
Something along the lines of
override func viewWillAppear(animated: Bool) {
self.switchButton.on = NSUserDefaults.standardUserDefaults().boolForKey(switchKey)
}
just after code connect UISwitch to IBoutlet.
class ViewController: UIViewController {
#IBOutlet weak var switchButton: UISwitch!
#objc func switchStateDidChange(_ sender:UISwitch!)
{
if (sender?.isOn == true){
print("on")
}
else {
print("off")
}
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
UserDefaults.standard.synchronize()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
switchButton?.isOn = UserDefaults.standard.bool(forKey: "switchState")
switchButton?.addTarget(self, action: #selector(switchStateDidChange(_:)), for: .touchUpInside)
}
}

Resources