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 answers
Related Questions in IPHONE
- How to control the volume of an iPhone programmatically in objective-c
- my website crash on safari The site sometimes crashes and I can't recover the crash
- Postal Framework crash in iPhone but runs successfully in simulator
- Xcode 15 building failure when using iphone 15 as simulator, using ios 17
- Images uploaded via Active Storage not displaying in Active Admin or on certain devices
- Any problem with creating provisioning profile with old Iphone?
- Does anyone know how to make iPad layout the same as iPhone's? Size wise the text and overall layout get's smaller when I run the app on the iPad
- Keyboard not appearing when connecting smart card reader to iPhones with type-c port. i.e. iPhone 15/ 15 pro
- Access the list of SIM mobile numbers installed in the iPhone
- Can we produce haptics and record from microphone the haptic sound at the same time on iOS?
- SwiftUI's localized string do not load from main bundle despite using the main bundle identifier (an xcode bug?)
- Cordova iOS only app upload through transport requires WKWatchKitApp
- Amazon s3 video is not played on Iphone
- build getting failed for ios xcode build -flutter app
- "Error when Importing 'mysdk' into iOS Demo App: dyld Library not loaded: @rpath/MQTTClient.framework/MQTTClient"
Related Questions in AUTOMATION
- Applescript To Select Sound Output stops at opening Sound Preferences Screen
- I am automating web scraping using python
- Autofill data from previous cell to next cell in openpyxl
- In spotfire, IronPython script: No Module named Selenium
- Python selenium automation browser
- Specflow defination not showing references
- Expect: Any way to match a specific rule only once?
- Automate the update of a pivot table in Excel via Power Automate Web
- Encountering a problem to interact with a weird button which is a combobox (select)
- Unable to Login through Automation(Cypress) to app, while the credentails are true. It allows manual login but unable to login through Cypress
- Selecting an option in the mobile app drop down which is not visible when the app is loaded for the first time
- Unable to launch WebDriverAgent
- How do I automate a video download with Selenium and Python (Meta Quest Store Trailer Download)
- Error: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure
- Trouble uploading with playwright
Related Questions in BACKGROUND
- Problem with Android App background service stoping
- flutter stripe_android:verifyReleaseResources'. > A failure occurred while executing com.android.build.gradle.tasks > Android resource linking failed
- How to Properly Interrupt the Download of a Background Image Using JavaScript
- Maintaining Background Consistency as Button Count Decreases
- Issue with simple java app that removes background from one image and overlays it onto another image and downloads the processed image
- Is there a way to gather the SSIDs of the connected networks in the background?
- Unity 2D - animated background
- CSS Animating Button Background - how to make this background move horizontally not vertically
- Change background on Tab react native app
- How can I edit ggMarginal background to match the plot background?
- How to structure a SwiftUI Push To Talk App backend?
- MPAndroidChart - Fill gradient horizontally
- Chrome Extension Highlight Feature Not Applying Background Color
- CSS image in div ignoring padding
- Under the swiftUI framework, the timer cannot continue to count in the background
Related Questions in COCOA-DESIGN-PATTERNS
- How to implement simple MVC design pattern in Swift?
- What design pattern do I need for a single object which can receive data from different sources?
- iOS Design Patterns | Singleton
- Collecting data from multiple ViewControllers in Swift
- object communication when object is not kvc compliant in Swift
- Patterns for Showing a Toast Popup with Custom UITableViewCell
- Should I check user auth ( user name , password, device token) in webservice every time when my mobile application is launch?
- Where should custom, reusable animation code go?
- Real scenario for implementation of MVC vs MVVM vs VIPER for iOS based projects
- In Interface Builder, how do I bind to a property of a class via another class?
- Do I really need a shared instance on a singleton?
- Why Cocoa design patterns not representing best practices on Apple documentation anymore?
- Use Case involving Stack Views, Table Views & Scroll Views in Swift 2/Xcode7
- Is this singleton design pattern bad? Is it wrong to use Singleton in this case?
- iOS Design Pattern Implementation
Related Questions in UIAPPLICATIONDELEGATE
- UIApplicationDelegate supportedInterfaceOrientationsFor not called when supported by Multitasking on iOS
- sourceApplication: UIApplication.OpenURLOptionsKey is always empty
- Type of expression is ambiguous without more context Swift map CBPeripheralDelegate
- how we can dismiss default call sheet(which used to make default call in iOS) and push a controller on complition of dismiss
- Trigger onOpenUrl with specific url programmatically within SwiftUI App
- applicationDidBecomeActive get called when iPhone's Lock Screen button is pressed
- iOS universal links not entering in UIApplicationDelegate callback
- iOS. Interface orientation on launch
- How to handle a file shared from another app to my own iOS app?
- SwiftUI - 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows
- SceneDelegate.init() is being called when killing the app
- iOS - Opening files with custom extension from external apps into my app not working
- Is it possible to add an AppDelegate to an independent watchOS SwiftUI app?
- Error during trying opening file in predefined app
- How to keep an app from quitting after closing its window on Mac Catalyst?
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?
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)
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