Trouble with unresolved identifier self with NSTimer Swift [duplicate] - swift

This question already has answers here:
How to use NSTimer to fire off multiple times?
(4 answers)
Closed 7 years ago.
I have the code bellow and I am finding a error message. Note that the code in question is not in the viewcontroller class in Swift. The images code for moving is in the viewdidappear function.
var timer = NSTimer(timeInterval:3, target: self, selector:Selector("randomnumbers:"), userInfo: nil, repeats: true)
func randomnumbers(timer:NSTimer) {
var rockNamesArray:[String] = ["bird", "rock2", "rock3"]
var rockpos = Int(arc4random_uniform(UInt32(3)))
}
Edit:
if rockNamesArray[rockpos] == "rock2" {
UIView.animateWithDuration(3.0, animations: {
self.mrock.frame = CGRect(origin: CGPoint(x: 167, y: 600), size: self.mrock.frame.size)
},
completion: { _ in
self.mrock.frame = moriginalFrame
})
}

First you have to declare your timer at your view controller class:
var timer = NSTimer()
var rockNamesArray:[String] = []
var rockpos = 0
then at viewDidLoad you schedule the timer:
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "randomnumbers", userInfo: nil, repeats: true)
}
//
func randomnumbers() {
rockNamesArray = ["bird", "rock2", "rock3"]
rockpos = Int(arc4random_uniform(UInt32(rockNamesArray.count)))
}

Related

Error in Swift 5 with Xcode when creating a timer out of a label

I'm using Swift 5 in Xcode to code an app. On one view controller, I am creating a timer, which counts from 20 minutes down to 0. I have what I think is a successful code, but it throws back one error. In the line
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(SkippingViewController.updateTimer), userInfo: nil, repeats: true)
it gives an error saying Type 'SkippingViewController' has no member 'updateTimer' (SkippingViewController is the name of the view controller for the page of the app my timer is on)
How can I resolve this issue?
import UIKit
class SkippingViewController: UIViewController {
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var startWorkoutButton: UIButton!
#IBOutlet weak var pauseWorkoutButton: UIButton!
var timer = Timer()
var counter = 20.00
var isRunning = false
override func viewDidLoad() {
super.viewDidLoad()
timeLabel.text = "\(counter)"
startWorkoutButton.isEnabled = true
pauseWorkoutButton.isEnabled = false
// Do any additional setup after loading the view.
}
#IBAction func startWorkoutButtonDidTouch(_ sender: Any) {
if !isRunning {
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(SkippingViewController.updateTimer), userInfo: nil, repeats: true)
startWorkoutButton.isEnabled = false
pauseWorkoutButton.isEnabled = true
isRunning = true
}
}
#IBAction func pauseWorkoutButtonDidTouch(_ sender: Any) {
func updateTimer() {
counter -= 0.01
timeLabel.text = String(format: "%.01f", counter)
}
}
}
Your problem is, that there is no method called 'updateTimer' in SkippingViewController.swift. You falsely put the method inside of the method 'pauseWorkoutButtonDidTouch'. In order to resolve the error insert the following code into SkippingViewController.swift:
#objc func updateTimer() {
counter -= 0.01
timeLabel.text = String(format: "%.01f", counter)
}

AVAudioplayer no resetting on viewDidAppear

The idea is simple and I do not think that the question has been asked in the past.
I want to build a simple mp3 player.
some songs displayed in a collection view the user selects a song
segue to another view with options to play, pause or stop only issue
is when you go back to the home screen to select a new song with the
current still playing. It is impossible to deactivate the current
player. When you need to play the 2 songs, the 2 are playing together
I have tried a lot of things
- create a new instance of player (player = AVAudioPlayer())
- player.pause() and player.play()
I do not see what I am doing wrong really.
this is my code :
import UIKit
import AVFoundation
class LecteurViewController: UIViewController {
var chansonSelected: Chanson? = nil
var lecteur:AVAudioPlayer = AVAudioPlayer()
var timer1 = Timer()
var timer2 = Timer()
#IBOutlet weak var dureeChansonSlider: UISlider!
#IBOutlet weak var chansonImageView: UIImageView!
#IBOutlet weak var chansonVolumeSlider: UISlider!
#IBOutlet weak var debutLabel: UILabel!
#IBOutlet weak var finLabel: UILabel!
#IBAction func stopMusicAction(_ sender: UIBarButtonItem) {
var player = AVAudioPlayer()
lecteur.stop()
LecteurManager.isActive = false
}
#IBAction func pauseMusicAction(_ sender: UIBarButtonItem) {
var player = AVAudioPlayer()
lecteur.pause()
LecteurManager.isActive = false
}
#IBAction func jouerMusicAction(_ sender: UIButton) {
if LecteurManager.isActive {
changeSong()
print("lecteur déjà en cours")
} else {
var player = AVAudioPlayer()
lecteur.play()
}
print(LecteurManager.isActive )
LecteurManager.isActive = true
}
func changeSong() {
lecteur.stop()
//lecteur = AVAudioPlayer()
jouerLecteurMp3()
print(chansonSelected!)
lecteur.play()
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
jouerLecteurMp3()
}
func configureView() {
self.title = (chansonSelected!.titre!).capitalized
chansonImageView.image = UIImage(named: "\(chansonSelected!.image).jpgs")
//formatter 'back' button
let backBtn = UIBarButtonItem(title: "< Playlist", style: .plain, target: self, action: #selector(LecteurViewController.reset(_sender:)))
self.navigationItem.leftBarButtonItem = backBtn
self.navigationController?.navigationBar.tintColor = UIColor.white
//contrôler volume chanson
chansonVolumeSlider.addTarget(self, action: #selector(LecteurViewController.ajusterVolume(_ :)), for: UIControlEvents.valueChanged)
//contrôler durée chanson
dureeChansonSlider.addTarget(self, action: #selector(LecteurViewController.ajusterDurée(_ :)), for: UIControlEvents.valueChanged)
updateUI()
}
func updateUI() {
//indiquer position chanson
timer1 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(LecteurViewController.mettreAJourDurée), userInfo: nil, repeats: true)
//afficher durée chanson
timer2 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(LecteurViewController.afficherDurée), userInfo: nil, repeats: true)
}
func reset(_sender:UIBarButtonItem) {
self.navigationController?.popViewController(animated: true)
}
func ajusterVolume(_ sender:UISlider) {
//print("volume ajusté \(chansonVolumeSlider.value)")
lecteur.volume = chansonVolumeSlider.value
}
func ajusterDurée(_ sender:UISlider) {
lecteur.currentTime = TimeInterval(dureeChansonSlider.value)
}
func mettreAJourDurée() {
dureeChansonSlider.value = Float(lecteur.currentTime)
}
func afficherDurée() {
print("durée actuelle: \(lecteur.duration - lecteur.currentTime)")
debutLabel.text = retournerPositionActuelle()
finLabel.text = retournerDureeTotal()
}
func retournerPositionActuelle() -> String {
let seconds = Int(lecteur.currentTime) % 60
let minutes = (Int(lecteur.currentTime) / 60) % 60
return String(format: "%0.2i:%0.2i", minutes, seconds)
}
func retournerDureeTotal() -> String {
let seconds = Int(lecteur.currentTime) % 60
let minutes = (Int(lecteur.currentTime) / 60) % 60
return String(format: "%0.2i:%0.2i", minutes, seconds)
}
func jouerLecteurMp3() {
let chanson = "bensound-\(chansonSelected!.titre!)"
let fichierMp3 = Bundle.main.path(forResource: chanson, ofType: "mp3")
do {
try lecteur = AVAudioPlayer(contentsOf: URL(string: fichierMp3!)!)
dureeChansonSlider.maximumValue = Float(lecteur.duration)
} catch {
print("erreur lecture mp3")
}
}
}
Try this:
func reset(_sender:UIBarButtonItem)
{
self.navigationController?.popViewController(animated: true)
lecteur.stop()
}

Why does Xcode say "expected declaration" with an arrow pointing to the word "timer"? [duplicate]

This question already has an answer here:
Expected Declaration Error using Swift
(1 answer)
Closed 5 years ago.
I get an error on the line below func pauseAction that says "expected declaration" and there is an arrow pointing to the word "timer"
var timeLeft = 10
var timer = Timer()
var score: Int = 0 {
didSet {
scoreLabel.text = "\(score)"
}
}
#IBOutlet var scoreLabel: UILabel!
#IBAction func tapButton(_ sender: Any) {
score += 1
}
#IBAction func pauseAction(_ sender: Any) {
}
timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector: Selector(("updateTimer")), userInfo: nil, repeats: true)
func updateTimer() {
timeLeft -= 1
timeLabel.text = String(timeLeft)
if timeLeft == 0 {
timer.invalidate()
}
}
In this case expected declaration means the code must be inside a method / function for example
func startTimer()
{
timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
}

NSTimer Value does not update UILabel? in SWIFT

I am trying to update a label using the NSTimer.scheduledTimerWithTimeInterval method although the timer works fine my label is not changing as it should, can someone tell me what I am doing wrong? code:
class Questions: UIViewController, UITextFieldDelegate {
var timerVal = 10
var timerLbl :UILabel!
var timer:NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
startTimer()
}
func timerLabel() {
var timerLbl = UILabel(frame: CGRectMake(250, 20, 50, 50))
timerLbl.text = "\(10)"
timerLbl.textColor = UIColor.blackColor()
timerLbl.font = UIFont(name: Font.FuturaBlack, size: 30)
timerLbl.textAlignment = NSTextAlignment.Center
view.addSubview(timerLbl)
}
func updateTimer(dt:NSTimer) {
timerVal--
if timerVal == 0{
timerVal = 11
}else if timerVal < 0{
timer.invalidate()
} else{
println(timerString) //PRINTS CORRECT AS THE TIMER DECREASES BY ONE SECOND
timerLbl.text = "\(timerVal)" //NOTHING HAPPENS ON THE LABEL
}
}
func startTimer(){
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTimer:"), userInfo: nil, repeats: true)
}
}
the function timerLabel which creates your timerLbl is never called.

How do I switch my play button to a pause button in Swift?

working on my first stopwatch app.
I currently have a play button, pause button, and stop button.
I'd like to combine the play and pause button so that they switch back and forth.
My code looks like this:
var timer = NSTimer()
var count = 0
func updateTime() {
count++
time.text = "\(count)"
}
#IBAction func pauseButton(sender: AnyObject) {
timer.invalidate()
}
#IBOutlet weak var time: UILabel!
#IBAction func stopButton(sender: AnyObject) {
timer.invalidate()
count = 0
time.text = "0"
}
#IBAction func playButton(sender: AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
Any help is appreciated.
Try adding booleans. See my code below.
#IBOutlet weak var label: UILabel!
var time = NSTimer()
var count = 0
var running = false
func result (){
count++
label.text = String(count)
println(count)
}
#IBAction func playpause(sender: AnyObject) {
if running == false {
time = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
running = true }
else {
time.invalidate()
running = false
}
}
Hope this helps!
You'll have a variable bound to the button, something like this:
#IBOutlet var thePlayPauseButton : UIButton!
This button will be linked with some action:
#IBAction func togglePlayPauseButton (button: UIButton) {
// If we are 'paused', then play:
if button.titleLabel!.text == "Pause" {
button.titleLabel!.text = "Play"
// do actual play ...
timer = NSTimer.scheduledTimerWithTimeInterval (1,
target: self,
selector: Selector("updateTime"),
userInfo: nil,
repeats: true)
}
else if button.titleLabel!.text == "Play" {
button.titleLabel!.text = "Pause"
// do actual pause ...
timer.invalidate()
}
else { /* error */ }
}
Of course, structurally you can use a switch//case and you can perform the toggle behavior by calling your preexisting pause and play methods.
I know this post is somewhat dated, but I was working with the same problem and I came up with a slightly different answer and wanted to share it to help others. Here is what I came up with in toggling the pause and play buttons.
class ViewController: UIViewController {
var time = NSTimer()
var seconds = 0
var running = false
func timer() {
seconds++
timeLabel.text = "\(seconds)"
}
func playing() {
time = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timer"), userInfo: nil, repeats: true)
running = true
}
func pausing() {
time.invalidate()
running = false
}
#IBOutlet weak var timeLabel: UILabel!
#IBAction func stopButton(sender: AnyObject) {
time.invalidate()
seconds = 0
timeLabel.text = "0"
}
#IBAction func pausePlayToggleButton(sender: AnyObject) {
if running == false {
return playing()
} else {
return pausing()
}
}
I had both a pause and play button and I essentially took their effects and placed them in functions and used them as return values for a single button.