1

On the main view in my app, there is a refresh button. I would like for NSTimer to start on click and if 15 seconds pass and the app cannot connect to the server, I would like for it to stop trying to refresh and give an alert saying it could not connect. Thanks!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Chase Kretch
  • 19
  • 1
  • 7
  • You could just call `[self performSelector:@selector(cancelConnection) withObject:nil afterDelay:15.0]`, and implement the function `cancelConnection` to stop the connection if it is running. – Greg May 17 '13 at 23:17
  • Or you can look at a detailed explanation of how to use `NSTimer` here: http://stackoverflow.com/q/1449035/834998 – Greg May 17 '13 at 23:18
  • I posted it as an answer so you can mark it as accepted so this question isn't shown in the unanswered section anymore. – Greg May 18 '13 at 00:00

2 Answers2

2

You don't need a timer for this. Use NSURLConnection to connect to the server, and initialize it with a request made with requestWithURL:cachePolicy:timeoutInterval:. If it takes longer than the timeInterval, it will invoke connection:didFailWithError:. You can query that to see if the reason for failure was that the connection timed out, and present your alert.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
1

Implement a cancelConnection method to stop the connection:

- (void)cancelConnection {
    ... // If the connection is still open, stop it and alert the user
}

Then simply call

[self performSelector:@selector(cancelConnection) withObject:nil afterDelay:15.0]

when you open the connection, and if it is still running 15 seconds later, it will be stopped when the method is called.

Alternatively, you can look at this question for a detailed explanation of NSTimer.

Community
  • 1
  • 1
Greg
  • 9,068
  • 6
  • 49
  • 91