Swift - NSTimer passing wrong value for userInfo param - ios

I recently took it upon myself to learn the Swift programming language and I love it. To help me learn, I have been working on a couple of simple apps using XCode 7. One of those apps is a flashlight and one of the features is a strobe light. I decided on using the NSTimer class to schedule the flashlight toggle functionality to be called at a set time interval, thus giving a nice strobe effect. My first crack at the timer code is as follows :-
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self.torch, selector: "toggleTorch:", userInfo: false, repeats: true)
As you can see here, I am using my own custom made Torch object to handle the flash toggle functionality. I pass the torch object I have specified as an instance variable as the target param and then I call the following function in the Torch class, which I pass as selector :-
func toggleTorch(adjustingBrightness: Bool) -> Bool {
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
defer {
device.unlockForConfiguration()
}
guard device.hasTorch else {
return false
}
do {
try device.lockForConfiguration()
if !adjustingBrightness && device.torchMode == AVCaptureTorchMode.On {
device.torchMode = AVCaptureTorchMode.Off
}
else if !adjustingBrightness && device.torchMode == AVCaptureTorchMode.Off {
try device.setTorchModeOnWithLevel(brightnessLevel)
}
else if adjustingBrightness && device.torchMode == AVCaptureTorchMode.On {
try device.setTorchModeOnWithLevel(brightnessLevel)
}
} catch {
return false
}
return true
}
The problem I am encountering is that when the timer calls the toggleTorch method, it is passing the value of true as the parameter even though I have specifically passed false to the timer as the userInfo param.
So I scratch my head and think "Ah" let's try using a default value of false in the selector/method parameter and pass nil in the timer userInfo param. That way I can rely on the default value of false being invoked every time. So my new selector signature looks as follows:-
func toggleTorch(adjustingBrightness: Bool = false) -> Bool
And the timer that now calls it has changed to:-
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self.torch, selector: "toggleTorch:", userInfo: nil, repeats: true)
However, despite the default parameter and no parameter passing going on via the timer, the value being passed through is still true. So I tinker some more and decide to see if using my ViewController as the target object will make a difference. I place a new selector in my ViewController like so:-
func toggleTorch() {
torch.toggleTorch(false)
}
I then update my timer to call this new method within the ViewController :-
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "toggleTorch", userInfo: nil, repeats: true)
'Hey Presto' it now works fine and the correct boolean value of false is being passed because I have passed the value myself. Why is this happening? For info, I'v been learning Swift for about three wks so am no expert

NSTimer does not pass the userInfo information as the parameter to the selector. It passes itself as the parameter so that you know which timer was called.
You should set it up as follows:
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self.torch, selector: "strobeTimerFired:", userInfo: nil, repeats: true)
And have a method as follows in your Torch object:
func strobeTimerFired(timer: NSTimer) {
toggleTorch(false)
}
In this case you don't need to access the timer object in the strobeTimerFired method, but it's good practise to include it anyway (it can be skipped). You could add additional checking to ensure the timer that triggered the method is the one you expected for example.
If you did need to use the userInfo for something, (don't think you'd need it in this case), you could pass an object in the original scheduledTimerWithTimeInterval call as the userInfo parameter, and then you would access that in the strobeTimerFired method by accessing: timer.userInfo.

Related

How do you make a timer controller with a condition?

I'm a beginner in Swift and have a task to change the bottom sheet message when the process of the app doesn't work in three minutes. So, the message will change from "available" to "not available" if the process does not work.
I found code syntax like:
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
What I think:
var waktu = 0
Timer.scheduledTimer(withTimeInterval: 180.0, repeats: false) {
if waktu == 180 {
timer.invalidate()
//run the change message function
}
}
You can add observer on your property, so it will invalidate the timer when condition met, like so:
var waktu = 0 {
didSet {
if waktu == 180 {
timer.invalidate()
}
}
}
Your code creates a timer that will fire once in 3 minutes.
You’re using a variation on the timer method you list, scheduledTimer(withTimeInterval:repeats:block:)
That variant takes a closure instead of a selector. Then you’re using “trailing closure syntax” to provide that closure in braces outside the closing paren for the function call. That’s all good.
However, you define a variable waktu And give it a starting value of 0. You don’t show any code that will change that value, so your if statement if waktu == 180 will never evaluate to true and run your change message function. You need to update that if statement to determine if “the process of the app works”, whatever that means. (Presumably you have some definition of what your app working/not working means, and can update that if statement accordingly.)

NSTimer is being triggered only one time after invalidating and reinitializing

I have the following function setPath() which is called whenever the user taps on a button:
var loadSuccessfulTimer: Timer? = nil
func setPath(index: Int) {
self.loadSuccessfulTimer?.invalidate()
self.loadSuccessfulTimer = nil
print("setting path")
self.pause(releaseAudioSession: false)
self.reset(index: index)
let song = DataManager.getInstance().getQueueSong(index: index)
superpowered.setPath(song.url, true)
self.loadSuccessfulTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(checkLoadSucess), userInfo: nil, repeats: true)
self.loadSuccessfulTimer!.fire()
}
#objc func checkLoadSucess() {
let status = self.superpowered.getLoadSuccessful()
print(status)
if(status != -1) {
self.loadSuccessfulTimer?.invalidate()
self.loadSuccessfulTimer = nil
if(status == 1){
print("success")
} else if(status == 2){
print("failed")
}
}
}
So whenever the setPath() function gets called, I want the timer to trigger every 0.2 seconds to check on a the value of status = self.superpowered.getLoadSuccessful(). The variable status would have values -1, 1, 2 I want to stop the timer when it's either 1 or 2. However, the following scenario is happening:
On the first tap it is working as expected and printing the following:
setting path
-1
-1
-1
-1
-1
-1
1
success
On the second tap the timer is only triggered one time (I guess it is from the .fire()) and the following is being printed:
setting path
-1
I tried to look up what might be going wrong, but all I could see was this is the recommended way of using a Timer.
Update
The second time setPath() is being called from DispatchQueue.global(), maybe this is related to the issue.
NSTimer requires run loop to work properly. The main queue has a run loop for free, for other queues you need to make sure run loop is available.
Make sure you read the documentation: https://developer.apple.com/documentation/foundation/nstimer
Also, remember to invalidate NSTimer object from the same run loop (thread) is has been created (scheduled) from.

iOS turn based match, push notifications not working, GKTurnBasedEventListener functions not called

In my iOS turn based match, I'm trying to receive notifications and to get the
public func player(_ player: GKPlayer, receivedTurnEventFor match: GKTurnBasedMatch, didBecomeActive: Bool)
to be called, with no success.
I register my view model to the local player
GKLocalPlayer.localPlayer().register(self)
and I would expect that to fire after the other player executes
func endTurn(withNextParticipants nextParticipants: [GKTurnBasedParticipant], turnTimeout timeout: TimeInterval, match matchData: Data, completionHandler: ((Error?) -> Swift.Void)? = nil)
but no success.
If I force a reload of the matchData then I will get the data the second player just submitted. So the endTurn works correctly.
Is there something I'm doing wrong?
Update:
So I create a new project, copied all my files over,
in the capabilities only Game Center was enabled.
When developing it was working perfect, I had two devices attached (with different apple IDs). Notifications were working and Turnbasedlistener was firing.
As soon as I released it for internal testing it stopped working!!!
I had very similar issue. My solution was to manually recheck my status while waiting for my turn.
FIrst, I defined global variable var gcBugTimer: Timer
In endTurn(withNextParticipants:turnTimeOut:match:completionHan‌​dler:) completion handler:
let interval = 5.0
self.gcBugTimer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(self.isMatchActive), userInfo: nil, repeats: true)
self.gcBugTimer.tolerance = 1.0
Code above also should be called in case when a player is joying to a new match and other player in a turn.
Then timer method:
func isMatchActive() {
// currentMatch - global variable contains information about current match
GKTurnBasedMatch.load(withID: currentMatch.matchID!) { (match, error) in
if match != nil {
let participant = match?.currentParticipant
let localPlayer = GKLocalPlayer.localPlayer()
if localPlayer.playerID == participant?.player?.playerID {
self.player(localPlayer, receivedTurnEventFor: match!, didBecomeActive: false)
}
} else {
print(error?.localizedDescription ?? "")
}
}
}
And I add following code at the very beginning of player(_:receivedTurnEventFor:didBecomeActive):
if gcBugTimer != nil && gcBugTimer.isValid {
gcBugTimer.invalidate()
}
What ended up working for me, was to test on an actual device, rather than in simulator. The receivedTurnEvents function doesn't seem to work in simulator.
Grigory's work around is great for testing with simulator.

How to repeat every X seconds in Swift?

I am trying to build a simple single view app which runs an infinite slide show of a selection of images with a time delay between each image change.
The code I wrote for this is below. I tried to put this into viewDidLoad and viewDidAppear but the screen remained blank which I guess is because the function never finishes due to the infinite loop.
I learnt a bit of Python before iOS and with tkinter, your code would go into the mainloop. But I am not quite sure how to do the equivalent in Swift
Could someone please explain why I am having this problem and how to do this in Swift. Thanks.
var arrayimages: [UIImage] = [UIImage(named: "charizard")!,UIImage(named:"Flying_Iron_Man")!]
var x: Int = 0
var images: UIImage
let arraycount = arrayimages.count
repeat{
images = arrayimages[(x % arraycount)]
sleep(1)
slideshow.image = images
x++
} while true
NB: slideshow is an image view outlet.
You're looking for NSTimer
let timer = NSTimer.scheduledTimerWithTimeInterval(
1.0, target: self, selector: Selector("doYourTask"),
userInfo: nil, repeats: true)
The first argument is how frequently you want the timer to fire, the second is what object is going to have the selector that gets called, the third is the selector name, the fourth is any extra information you want to pass as a parameter on the timer object, and the fifth is whether this should repeat.
If you want to stop the code at any future point:
timer.invalidate()
Create a repeating NSTimer:
var timer = NSTimer.scheduledTimerWithTimeInterval(2.0,
target: self,
selector: "animateFunction:",
userInfo: nil,
repeats: true)
Then write a function animateFunction:
func animateFunction(timer: NSTimer)
{
//Display the next image in your array, or loop back to the beginning
}
Edit: Updated for modern Swift versions: (>= Swift 5)
This has changed a lot since I posted this answer. NSTimer is now called Timer in Swift, and the syntax of the scheduledTimer() method has changed. The method signature is now scheduledTimer(timeInterval:target:selector:userInfo:repeats:)
Also, the way you create a selector has changed
So the call would be
var timer = Timer.scheduledTimer(timeInterval: 2.0,
target: self,
selector: #selector(animateFunction(_:)),
userInfo: nil,
repeats: true)
And the animateFunction might look like this:
func animateFunction(timer: Timer)
{
//Display the next image in your array, or loop back to the beginning
}

How to check if a NSTimer is running or not in Swift?

How to check if NSTimer is running or not in Swift. In obj-c the code should be like this as I guess:
if (!myTimer) {
//DO
}
I'm trying to set it in Swift like this and it's showing errors.
if !myTimer {
// DO
}
What I do (in both languages) is to make my timer weak. In swift it would be a weak optional.
weak var myTimer: NSTimer?
Then I create a timer with
myTimer = NSTimer.scheduledTimerWithTimeInterval(1,
target: self,
selector: "timerFired:",
userInfo: nil,
repeats: false)
And then you can use
if timer == nil
to tell if it's running.
To stop the timer you just call
myTimer?.invalidate()
In Objective-C it would be
[myTimer invalidate];
That works in Objective-C because sending messages to nil pointers is valid, and just does nothing.
If you don't want to use a weak optional, you can query a timer to see if it's running by looking at it's valid property.
How about the below option? Can you see if this works for you
if myTimer.valid {
}
if !myTimer.valid {
//DO
}
Swift 4 answer:
if timer.isValid{
}
https://developer.apple.com/documentation/foundation/timer

Resources