I am posting this question (along with the answer) so that other people can benefit from a neat technique I have evolved to have modules automatically detect (and respond to) iOS app state changes. The (formatted) blog discussion is here My Blog
How to detect iphone app state changes?
5.5k Views Asked by software evolved At
1
There are 1 best solutions below
Related Questions in IPHONE
- UIWebView Screen Fitting Issue
- ios responsive design not working (too wide in portrait orientation)
- Setting View orientation to portrait is ignored
- How do I add custom cells to TableView in Swift?
- UIWebView not loading URL in simulator
- What is the limit for number of subscribers to a stream(publisher's) in opentok/tokbox iOS SDK?
- How to generate request format for WCF web service method for Mac and iPhone
- Difference between gethostname() and [NSProcessInfo hostName]?
- How to force close ipad/iphone keypad when input element is not focused using JS?
- iOS app rejected because of in-app purchase
- iOS coordinates for iPad and iPhone game using spritekit
- What is the best practice when making a storyboard for iPhone and iPad?
- Labels properties changing in Xcode
- Terminating app due to uncaught exception
- Exchange plist data between 2 iPad using iCloud
Related Questions in AUTOMATION
- Installing Teamcity build agent as a user: failed to install the service. selected account does not have enough rights
- Automating Telnet Scripts from .bat with a teamspeak instance
- schedule and automate sqoop import/export tasks
- Dynamic @Test generation in TestNG
- detecting a file downloaded in selenium java
- Can I automate auto-app installation on my Android device?
- C# Program automation - Program hangs/doesn't work
- Saving Excel workbook as PDF gives me an OLE error 800A03EC
- Appium-How to send SMS for login verification purpose during automation test
- How to maximize browser window with helium using Java?
- Appium iOS automation using Java : get element using accessibility Id?
- Looking to run automated jobs in .NET application
- How to click the back navigation button of the browser using helium?
- Firefox automatically choose certificate, without ui dialog
- Test class not found in selected project
Related Questions in BACKGROUND
- X3DOM Inline Background skyColor
- CSS background property applied to HTML Input element within Table cell
- Changing background of button every second
- jQuery background animation - better performance
- Starting a ScheduledExecutorService from a servlet with a set of parameters
- Change button background with an action
- How to control multithreaded background jobs in for loop in shell script
- background is not working properly
- Fixed background adjusted to the monitor size
- How to print an ArrayList in processing and how to update the background
- Background image animation not working in Firefox
- How can i add an image as background in Chartjs?
- backgrounds Slideshow, but text scrolling
- Java replacing the background of an image
- Is there a way to override default CSS of HTML5 form validation messages
Related Questions in COCOA-DESIGN-PATTERNS
- iOS Design Pattern Implementation
- What is the correct system design when dealing with third party API?
- How to detect iphone app state changes?
- How to use tabbar in mac Application
- Avoiding coupling in a document-based Cocoa app?
- Singleton with a delegate: Good idea or bad?
- Coordinating Controller design pattern in Cocoa Touch
- Cocoa: How to dynamically size the NSTextField?
- Database sync on three different platforms
- Is it good to access View controller from Custom Gesture via the view it is connected to?
- Data structure based on JSON object
- Notification Center in C++
- Core Data backed UITableView with indexing
- Best practice for assigning new objects to retained properties?
- Exchange data between two iPhone child views
Related Questions in UIAPPLICATIONDELEGATE
- applicationState is UIApplicationStateInactive in application:didReceiveRemoteNotification:fetchCompletionHandler:
- Disabling UI interaction of iPad till the data is downloading on main thread in backend
- Is applicationWillEnterForeground always called after applicationDidEnterBackground?
- ios Core Plot - symbolforScatterPlot not being called
- Why isn't UIWebView loading an NSURLRequest at applicationWillTerminate: in my app delegate?
- False positive respondsToSelector with UIApplicationDelegate leading to NSInvalidArgumentException
- How to detect iphone app state changes?
- why does this application delegate code work
- where to store main table view data? (appDelegate or rootViewController)
- Intermittent crash on startup with iPhone 4
- Is it good practice to use AppDelegate for data manipulation and Handling?
- iOS: Push notifications, UIApplicationStateInactive and fast app switching
- Error during trying opening file in predefined app
- Is it possible to add an AppDelegate to an independent watchOS SwiftUI app?
- Objective-C Alternative to using ApplicationDelegate or singleton to pass data
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
If you google around for solutions to having code execute in response to app state changes, you’ll find code examples where you add in calls to your code into your app delegate, because it gets called whenever the application didFinishLaunchingWithOptions, or didBecomeActive, or WillEnterBackground.
But let’s say you start working on another app, which re-uses a lot of your code. Wouldn’t it be nice if you could just copy over some files and get all the functionality, without having to worry about re-wiring up the app delegate methods?
To summarize, we want drop-in modules that, just by the virtue of being in the project, will perform their work, without any additional effort or wiring up. At this point you may be saying “and I also want unicorns and elves to bring me a pizza”. Bear with me.
I’m not sure how I missed this when reading the docs, but when iOS applications change state, it isn’t just the app delegate that knows about it. NSNotifications also get posted for all major state changes. Here is text taken directly from the api reference:
After calling [applicationDidBecomeActive], the application also posts a UIApplicationDidBecomeActiveNotification notification to give interested objects a chance to respond to the transition.
Similarly, there is a UIApplicationDidFinishLaunchingNotification that gets posted immediately after the application finishes launching, and other notifications for entering the background, or entering the foreground.
So this simplifies our code: instead of having to call
in the app delegate’s implementation of applicationDidBecomeActive, we just have to have RobustWebService respond to UIApplicationDidFinishLaunchingNotification.
Now pondering this a moment, you might realize that in order for the RWS class to handle the notification, it has to register as an observer. That call looks something like
And where can that get done? Remember, we do not want to touch the app delegate because that would defeat the intent of having a self-contained drop-in module. If only there were some way to have the addObserver function call happen automatically for the class. If only…
At this point we have to drop out of “Cocoa” and dig into the underlying technology of Objective-C. Sure enough, there is a class method, called “load” which, if present in your class definition, will automatically be called when the class is first loaded. Let’s restate that in code. If you write this function in any class.m file
It will run when the class is loaded by iOS. Interestingly enough, it is run before your app’s main() routine is called so you have to be very careful about what you try to do! Most of your app is NOT actually up and running at this point, but you are guaranteed that all frameworks that your class links too will be loaded first. Frameworks such as NSNotificationCenter, so if you include this in your class.m
Then your handleAppBecomeActive method WILL get called when your app becomes active, without you having to do anything other than include the class.h and class.m in your project.
And if you include this code in your class.m file
Your class will get notified of all app state changes, with no other work required. This is so cool that it still makes me feel tingly. Enjoy!
Terry