NSTimer scheduledTimerWithTimeInterval - not calling funciton - ios

I want to run a timer in the background. So I created a singleton.
The problem is that after the set 5.0 seconds, it does not call the function timeEnded(). Xcode proposes to add #Objc in front of the function (like this: #Objc func timeEnded() {...) to solve some problem (I don't get what, though). But it still doesn't call that function. Any ideas?
class TimerService {
static let instance = TimerService()
var internalTimer: NSTimer?
func startTimer() {
guard internalTimer != nil else {
return print("timer already started")
}
internalTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(TimerService.timeEnded), userInfo: nil, repeats: false)
}
func timeEnded() {
//NSNotificationCenter.defaultCenter().postNotificationName("timerEnded", object: nil)
print("timer Ended")
}
}

You never actually start the timer because your startTimer() function will always return before reaching the line of code where you create the timer.
In your guard statement you only continue the execution of the function if internalTimer != nil but the only place where you set the timer is after that statement. Thus, your timer is never created and internalTimer will always be nil.
This should fix your problem:
func startTimer() {
guard internalTimer == nil else {
return print("timer already started")
}
internalTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(TimerService.timeEnded), userInfo: nil, repeats: false)
}

Selectors are a feature of Objective-C and can only be used with methods that are exposed to the dynamic Obj-C runtime. You cannot have a selector to a pure Swift method.
If your class inherits from NSObject then its public methods are exposed to Obj-C automatically. Since your class does not inherit from NSObject you have to use the #objc attribute to indicate that you want this method exposed to Obj-C so that it may be called with an Obj-C selector.
#selector() is the new syntax in Swift 2.2. It allows the compiler to check that the selector you're trying to use actually exists. The old syntax is deprecated and will be removed in Swift 3.0.

Related

Swift - Timer not able to access updated instance property

Im my react native project's native module I need to send some data periodically from Objective-C to Swift so I am using NSNotificationCenter. I receive the data successfully in my Swift class, inside the function attached to the observer, and I store it in a property.
If I access this property from any instance method call I can see that the value has updated.
However if I access the same property in the selector function attached to the Timer it appears as if the value has not been updated and I cannot figure out why? It seems as if the timer selector function does not have access to anything except the initial value of the property - I have also tried passing the property as part of userInfo to the Timer but the issue is the same.
[[NSNotificationCenter defaultCenter] postNotificationName:#"stateDidUpdate" object:nil userInfo:state];
class StateController {
var state: Dictionary<String, Any> = Dictionary()
var timer: Timer = Timer()
func subscribeToNotifications() {
NotificationCenter.default.addObserver(
self, selector: #selector(receivedStateUpdate),
name: NSNotification.Name.init(rawValue: "stateDidUpdate"), object: nil)
}
#objc func receivedStateUpdate(notification: NSNotification) {
if let state = notification.userInfo {
self.state = (state as? Dictionary<String, Any>)!
print("\(self.state)") // I can see that self.state has been updated here
}
}
func runTimer() {
self.timer = Timer(timeInterval: 0.1, target: self, selector: #selector(accessState(timer:)), userInfo: nil, repeats: true)
self.timer.fire()
RunLoop.current.add(self.timer, forMode: RunLoop.Mode.default)
RunLoop.current.run(until: Date(timeIntervalSinceNow: 2))
}
#objc func accessState(timer: Timer) {
print("\(self.state)") // state is an empty Dictionary when accessed here
}
func printState() {
"\(self.state)" // value printed is the updated value received from the notification
}
}
I figured out that multiple instances of my Swift class being created was causing the issue. I assumed that React Native would create a singleton when calling a native module but it appears multiple instances are created as I could see how many times the init method was called. Switching to a Singleton pattern resolved the issue for me following this excellent video and this excellent gist on how to create a singleton in a react native project
class StateController {
static let shared = StateController()
private override init() {
}
}

I keep getting errors in my code, specifically "Type 'FirstViewController' has no member" and "Use of unresolved identifier"

I get errors saying, "Type 'FirstViewController' has no member 'keepTimer'" and "Use of unresolved identifier 'keepTimer'".
What am I doing wrong? How should I change this?
My main goal is to have a stopwatch start keeping track of time. When I press Save, it should add the stopwatch value as an event in Calendar.
I have made sure all are identical. They are identical in terms of spelling, but some have () at the end. When I add () at the end, I still get errors.
#IBAction func startButton(_ sender: Any) {
captureStartDateTime()
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(FirstViewController.self.keepTimer), userInfo: nil, repeats: true)
keepTimer()
startOutlet.isHidden = true
} ...
func keepTimer() {...}
#IBAction func startButton(_ sender: Any) {
captureStartDateTime()
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(keepTimer), userInfo: nil, repeats: true)
startOutlet.isHidden = true
}
#objc func keepTimer() {
}
In Swift, to use a method in a #selector(), the method must be marked with #objc
In your case you should be getting an error saying, Argument of '#selector' refers to instance method 'keepTimer()' that is not exposed to Objective-C
All you have to do is add #objc to expose this instance method to Objective-C.
i.e. your code should look like #objc func keepTimer() {...}
Is the keepTimer() in the FirstViewController? If not, the Xcode may cannot recognise the function

Selector is not fired from scheduledTimerWithTimeInterval

I checked the existing posts on this topic and also googled it, but I am not able to identify my mistake or make this work for me. I have a function iterativeDeepening() inside the class ChessPlayer. After say 15 seconds I want to stop further iterations within the function. In the code below, the function "flagSetter" is never invoked. If I use NSTimer.fire() the function is invoked immediately and not after 15 seconds. I tried placing the flagSetter function before or after iterativeDeepening(). Either case does not work. What have I done incorrectly?
class ChessPlayer {
var timeoutFlag = false
//Code
func iterativeDeepening() {
***//variables and constants***
let timer = NSTimer.scheduledTimerWithTimeInterval(15.0, target: self, selector: #selector(self.flagSetter), userInfo: nil, repeats: false)
***while minDepth <= maxDepth
{
// Loop iteration code
if timeoutFlag { break out of loop }
}***
}
#objc func flagSetter(timer: NSTimer) {
print("flag changed to true")
self.timeoutFlag = true
timer.invalidate()
}
}
The requirement:
computerThinking() is fired from GameScene from human move's action completion handler.
GameScene.computerThinking() invokes ChessPlayer.iterativeDeepening()
iterativeDeepening runs a while loop incrementing "depth". For each "depth" an optimal move at that depth is evaluated. Higher the depth, more detailed the evaluation.
after 15.0 seconds i want to break out of the while loop with the depth and optimal move available at that point of time.
I am a lover of Objective-c and never used Swift yet in my projects. Googling NSTimer Swift, I found out the following steps to implement NSTimer correctly.
we need to define our NSTimer. The first variable that we are going to need is a variable called timer of type NSTimer. We do this like:
var timer = NSTimer()
Start NSTimer timer:
timer = NSTimer.scheduledTimerWithTimeInterval(15.0, target:self, selector:#selector(ChessPlayer.flagSetter(_:)), userInfo: nil, repeats: false)
And your method flagSetter should be defined as this:
func flagSetter(timer: NSTimer) {
print("flag changed to true")
self.timeoutFlag = true
timer.invalidate()
}
This will now surely work as I've made my very first app, just for this question, made in Swift. Check how I put my selector. You're right with the warnings by the way.
If you need more information about Selectors, check this thread: #selector() in Swift?
Here is your solution: define timer outside of the function so you can invalidate it from another function. Right now, your timer is defined inside a function so it can only be altered inside that function, but that is not what you want. Fix it by doing the following: right below var timeoutFlag = false put var timer = NSTimer(). Then inside your function iterativeDeepening() get rid of the let. Then it will all work!!
Here's what your code should be, adapted from Hasya's answer and your provided code.
class ChessPlayer {
// Declare timer and timeoutFlag
var timer = NSTimer()
var timeoutFlag = false
func iterativeDeepening() {
self.timer = NSTimer.scheduledTimerWithTimeInterval(15.0, target: self, selector: “timerEventOccured”, userInfo: nil, repeats: true)
}
func timerEventOccured() {
print("timerEventOccured was called.")
timeoutFlag = true
self.timer.invalidate()
}
}
override func viewDidUnload() {
super.viewDidUnload()
self.timer.invalidate()
}
}

Swift selector to protocol function?

I have code like this:
protocol FooP {
...
}
extension FooP {
func doFoo() {
print("foo")
}
func doFoo(timer: NSTimer) {
doFoo()
}
}
class A : NSObject, UITableViewDataSource, FooP {
var timer : NSTimer?
...
func startUpdating() {
timer = NSTimer.scheduledTimerWithTimeInterval(
1.0,
target: self,
selector: Selector("doFoo:"),
userInfo: nil,
repeats: true
)
}
}
Unfortunately it crashes when I start timer the program crashes with
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[xyz.A doFoo:]: unrecognized selector sent to instance 0x7fb2041c4ac0'
How i can make it work (I want to keep implementation of doFoo inside protocol)?
If I move doFoo into A class definition everything works fine, but as i said i want to implement this function inside protocol.
In other words I need selector that says
"Hey I point to function named "doFoo" that is implemented as extension to FooP"
Right now selector seems to say
"Hey I point to function named "doFoo" that is implemented in A class"
Try to play in your playground. Your trouble is, that there is no possibility to define #objc func in protocol extension. So, see possible workaround
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
import Foundation
protocol FooP {
}
extension FooP {
func doFoo() {
print("foo")
}
func doFoo(timer: NSTimer) {
print("dofoo")
doFoo()
}
}
class A: FooP {
var timer : NSTimer?
#objc func foo(timer: NSTimer) {
doFoo(timer)
}
func startUpdating() {
timer = NSTimer.scheduledTimerWithTimeInterval(
1.0,
target: self,
selector: "foo:",
userInfo: nil,
repeats: true
)
}
}
let a = A()
a.startUpdating()
Why it works for you if you move doFoo inside class A? That is because your class inherits from NSObject, so #objc keyword is not necessary.
The problem is, NSTimer and the whole Selector() business are Objective-C stuff and do work in Swift domain thanks to bridging. However, Swift's default protocol implementations are not bridged to Objective-C wonderland (yet), and that's why your timer fails. Basically, from Objective-C perspective objects of type A do not respond to a selector doFoo:, period.
So, report this use-case to swift-evolution for the long-term solution. Short-term, use some sort of a workaround.
BTW, you might find it interesting to read (or even participate) in this thread.

How to implement callback/selector with performSelector in swift?

I am trying to create an equivalent of below method signature (Objective-C) in swift language. I couldn't get an answer on how to get the right equivalent for this. Any help is highly appreciated.
- (void)myMethod:(MyObject*)firstParam
setCallbackObject:(id)obj
withMySelector:(SEL)selector {
[obj performSelector:selector withObject:nil afterDelay:0]
}
First:
NOTE
The performSelector: method and related selector-invoking methods are not imported in Swift because they are inherently unsafe.
If you still want to implement it that way, read below.
You could use NSTimer:
var myTimer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.0, target: self, selector: "selectorMethod", userInfo: nil, repeats: false)
String can be used where Selector is needed. It will automatically be converted (autoboxing).
The delay can be of course higher: 0.1 is then equal to 1 tenth of a second.
To call a method like:
func selectorMethod() {
...
}
We need to check before using the selector on the class. But the respondsToSelector: is in the NSObject protocol, so you have to derive at least from that (or one that subclasses from it).
To make it clear, here is the example.
Code:
class Test {
func myMethod(firstParam: String, setCallbackObject obj: AnyObject, withMySelector selector: Selector) {
if obj.respondsToSelector(selector) {
var myTimer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.0, target: obj, selector: selector, userInfo: nil, repeats: false)
myTimer.fire()
} else {
println("Warning: does not respond to given selector")
}
}
}
class Test2: NSObject {
func selectorMethod() {
print("worked")
}
}
var test: Test = Test()
var callBackObj: Test2 = Test2()
test.myMethod("thisfirstis", setCallbackObject: callBackObj, withMySelector: Selector("selectorMethod"))
Output:
workedProgram ended with exit code: 0

Resources