How to use NSTimer to stop an action? - objective-c

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!

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.

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.

Related

How to get the application terminated notification quickly cocoa

To get the application terminated notification I have something like the following
NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter];
[center addObserver:self
selector:#selector(appTerminated:)
name:NSWorkspaceDidTerminateApplicationNotification
object:nil
];
- (void)appTerminated:(NSNotification *)note
{
NSLog(#"+ appTerminated");
}
actually my concern is when the firefox application quits/restarts,I need to update its database.When the firefox quits manually I can update with the help of appTerminated as firefox releasing its lock to the database.When it is running state,I am not able to update the database as firefox is locking it.when the firefox is restarted ,it is quitting and restarting too quickly so that I cannot update the database as it is in running stateI need to update database before it restarts.i.e.when the firefox is in quit state.
So,I need the notification just before firefox is going to quit.
Is any api availabe for this or please give some ideas.
Thanks in advance
I take it you have two applications, one that watches the other. Your concern seems to be that you don't want the watched app to start really doing anything until the watcher finishes its work.
You just need to communicate between the processes in this case. The watched application should wait until the watcher finishes its work. You can achieve this using a lock, or you could use NSDistributedNotification (or other IPC mechanism) to send messages from the watcher to the watched to let it know it may continue.
I prefer the locking mechanism since it behaves correctly if the watcher fails. The most correct place to put the lock would be on the database, since that's the resource you're trying to protect.
I would try something like that:
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
if (isMyDatabaseClosed) {
[self closeMyDatabaseAndQuit];
return NSTerminateLater;
} else {
return NSTerminateNow;
}
}
-(void)closeMyDatabaseAndQuit
{
/* close your database, etc...*/
[NSApp replyToApplicationShouldTerminate: YES];
}
The code is not tested, but you should get an idea.

Pausing the Current function for some time iphone

Hi all im trying to pause a function so some time in the middle of execution because ill have to wait for the call back functions from GData api and get my data ready to put in that function i dont know how to do that. I am developing in Xcode 4.2 really need some help
You need to consider redesigning a little bit. What ever portion of code you expect to process after callback happens, let that code called by the callback. That way it will give you the guarantee that it always executes after the callback.
where you want to wait your functionality write this code [self performSelector:#selector(WaitForTwoSecond) withObject:nil afterDelay:2]; and implement - (void)WaitForTwoSecond { //write your code here } this method wait for two second and after that you cant access all data and put it in appropriate place .
we can say that this function is working like in background process

Determining how much time has passed since the app was used

I am looking to make an app that, after a given time of no use, will close or give a message to the user.
How can I implement this?
UKIDleTimer is what you're looking for. You create a timer that only fires when the system becomes idle and implement the following method in its delegate:
-(void) timerBeginsIdling: (id)sender {
// terminate app
[NSApp terminate];
}
How about:
[NSApp performSelector:#selector(terminate:)
withObject:nil
afterDelay:[your delay...]];
Look at various Hello World examples on the net for Objective C. Once you have a hello world example going, you'll want to add some event listeners to monitor user activity. When any of those event handlers are called as a result of a users' actions, they should set a variable with the time of that action. Finally, set up a timer to check for user inactivity, say once every 30 seconds, which checks that value, to see if it's exceeded the time at which you want the application to close. If so, then send an exit command.

Where to put reachability check to ensure data to be loaded before viewing it?

I have read
this question and found its answer to be useful to check an internet connection for the iPhone. I implemented the check in my viewDidLoad message.
However my App does load Data from an XML file from a server (within viewWillAppear). In this case the check has to be done before the app tries to load the data from the internet source. My problem here is that the network check requires some seconds but the app does proceed with the code.
This results in delaying the check. So there is a valid internet connection, but the bool variable that stores this information is set too late.
Code in viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];
The selected message is implemented in the same way like in the example in the link above. Additionally it sets some bool-properties so I can access the connection state within the app.
Code in viewWillAppear
if(internetActive == TRUE)
{
NSLog(#"connected");
//Code to load XML stuff
}
else
{
NSLog(#"not connected");
}
The console shows me "not connected". But a few seconds later the debug logs within "checkNetworkStatus" show me that the internet connection is available and the bool "internetActive" would be set.
I assume that the network check delivers his report about the connection state too late for my purpose. Is there a way to delay the app until the connection is established? Or would this lead to crashing the app cause the view isn't displayed within a few seconds?
Are there any other possibilities to ensure the connection?
My second question is how to ensure a specific internet address is available? I the link above there is mentioned
hostReachable = [[Reachability reachabilityWithHostName: #"www.apple.com"] retain];
[hostReachable startNotifier];
to detect the connection to a host, but I want to go in detail and try to detect if the host deserves a specific address or not. But entering the full address path (e.g. "localaddress.mylan.de/lan/xml/") instead of the host leads to a not reachable connection state for the host. Entering the mentioned address in the browser address bar shows me the correct result. I guess I have to check it otherwise but how?
Thanks for reading :)
After getting more experiences with IOS development my first question is solved with three steps.
First step is to start all necessary notifiers once. This can be done by starting them in viewDidLoad of the first loaded ViewController.
Check current connection state by evaluating property named currentReachabilityStatus of reachability-objects. This state can be "not connected" even if a connection is available. This happens if the check is done within the ViewController who is starting the notifier. Reason for this is the time it takes while the notifier recognizes the connection. If currentReachabilityStatus property is evaluated as connected then data loading processes can be started.
Evaluating the connection state within the method whose selector is added during adding the notifier. This method will start every time the connection state changes. First call will be directly after starting the notifier. If connection state is evaluated as connected then data loading processes can be started.
The second question stays unresolved up to now. May be there is no way other than sending a request to the target and waiting for a response or a timeout.
Did you try dispatch_async & dispatch_sync(dispatch_get_main_queue( reload data here ) ?

How do I pause my app until a crash report has been submitted?

Background
I'm using UKCrashReporter in my app.
I've installed my own Uncaught
Exception Handler.
I'm setting up the
managedObjectContext of the object
activeItemController in
applicationDidFinishLaunching (1)
The Problem
If the managedObjectContext method throws an exception, the crash reporter dialog box only flashes up before the app crashes and so the user never gets to report the crash.
I want my app to continue only after the crash has been reported, not whilst the window is showing.
What I've tried
If UKCrashReporterCheckForCrash()
were an objective C method, I assume
I could call
performSelectorOnMainThread:waitUntilDone:YES
but it's not.
I've looked at some other Stack
Overflow questions about using
Conditional Locks to pause apps,
but I can't understand how I'd use it
for a C function.
How would I go about doing this in a nice way? Do people have any advice
for me? Any responses would be much
appreciated.
The Code
// In app delegate
-(void)applicationWillFinishLaunching:(NSNotification *)aNotification {
UKCrashReporterCheckForCrash(); // A C function which then creates a window if
// it detects a crash has happened.
}
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[activeItemController setMoContextDisk:[self managedObjectContext]];
[activeItemController setMoContextMemory:[self managedObjectContextMemory]];
}
Update 1
I've been asked for more details on what I'm trying to do, so here goes.
The bug that triggered this thinking was an exception when merging managedObjectModels. My app got caught in a loop printing "Uncaught exception" to the console every few milliseconds.
And when I installed the uncaught exception handler before this exception happened, I'd get the described behaviour - my app would fire up, display the crash report dialog briefly, then continue to load and crash again.
Summary - I want to be able to handle errors that happen on startup.
(1) I'm not using bindings to do this, as I thought bindings would make testing the class more problematic.
I think your problem is with thinking of it as "pausing" your app. Think of it more as a different initial UI state. Your attempts to block the run loop will prevent any interactive window from ... well, being interactive. :-)
Your best bet is to show your main UI (and connect data sources, etc) only if the "am I prompting the user to submit a crash report" method says "no, go ahead and start normally". Otherwise, show your window and, when the user sends or declines to send the report, close the window and ask your app controller to continue the normal startup.
I looked at UKCrashReporterCheckForCrash() and it doesn't appear to create a window of any kind. It merely submits the crash. Could you describe what you're doing with more detail?