Perform a connected-check every n seconds on iOS

262 views Asked by At

I am currently writing an app for the iOS platform which communicates to a server through TCP. The problem is: I want to start an NSThread which runs into an infinite loop that checks that my

- (BOOL)connected

still returns true every 10 seconds, once the connect function has returned successful.

How can I make a timer that runs a function and checks its return value every 10 seconds?

Any help is appreciated, thanks in advance.

2

There are 2 answers

1
doptimusprime On BEST ANSWER

Why do not you use NSTimer to run a timer which will run every 10 seconds to check the status of connection?

NSTimer reference is given here. There are many static methods to create a timer. You can use for example:

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

You can use it as

NSTimer * timer = [NSTimer timerWithTimeInterval:10 target:myobject selector:checkConnectionStatus userInfo:nil repeats:YES];

where myobject will be an Objective-C object and its method -checkConnectionStatus or which method you like will check the status of the connection.

1
Joride On

You should checkout the Reachability sample code from Apple. I don't know much about TCP, but what you are describing sounds like it is going to burn through the battery quickly. Unless TCP works without waking the radios off course.