iPhone indefinite background exectuion Xcode mystery - ios

I am writing an app for personal use that needs continuous background execution. Apple tries to make this difficult, but I found that declaring that my app uses background location updates and then creating background task (with no content, just a blank task) allows my app to run indefinitely when I run the project from Xcode. I do not understand why this works. I noticed that after about three minutes, when presumably the task is supposed to be terminated, I get the following error:
Can't endBackgroundTask: no background task exists with identifier 174256fe0, or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.
After this message, the app continues to run in the background normally. So, it seems that this indefinite execution is a bit of an exploit, which I'm fine with because I just want to make the app work.
However, when I run the app from the phone (i.e. not pressing the run button in my Xcode project), the background execution seems to stop after 3 minutes. This is a problem, and I can't seem to figure out why execution continues in one case but not in the other. What is the difference between running an app normally and running it through Xcode? Is there a simpler or better way to get the indefinite background execution I'm looking for given that I'm not trying to get this app published to the app store?

Since you're not submitting to the store - why not try this:
Enable the app for background audio services. Then, just play a silent audio file in the background on a constant loop?

The difference is that you are running through Xcode. Normal background limits are removed when running through the debugger.

Related

Differences between normal app startup and a wakeup from WatchKit's sendMessage?

According to the docs, sending sendMessage from the WatchKit app will wake the iPhone app if it is inactive.
I would like to know the differences between such a wakeup app startup and a normal one. Surely a background process has a lot of differences to a normal foreground app. However, I could not find a thorough documentation on the subject.
Here's what I found so far:
Since such a "wakeup" is not a normal app startup, I expect didFinishLaunchingWithOptions to receive a special launchOptions key. After all, the user did not start the app on the home screen, so there should be an indication in launchOptions. But when I tried it out, launchOptions was nil. Doesn't that contradict the docs?
I also thought there should be differences because there is no UI present in a background process. So perhaps [UIScreen mainScreen] might be nil. But there seems to be no difference in mainScreen in the background process. In my AppDelegate.m, the code that creates the main window seems to run exactly the same way as in the foreground process.
I also expect that there are limits to the background process. Since the user did not actively start the process, I'm pretty sure that it cannot run for an infinite amount of time. Maybe there are also stricter memory limits.
Is there a way I can debug such a background process in XCode? Can I tell XCode "wait until the app runs on the iPhone", such that the debugger gets attached as soon as the app runs?
I also tried this in a React Native app. The Objective-C code in AppDelegate.m seemed to run exactly the same way, regardless of background or foreground process. However, the whole Javascript part of the app did not run (which is kind of expected, because in a background process, we do not need any React UI). But there must be a difference in the process that causes the Javascript part to not run.
Please don't consider this question to be about "more than one question". The question of this post is quite clear: I want to know all the differences between a didReceiveMessage background process and a normal one. In the enumeration above, I just listed all the differences I would expect or that I have encountered so far, and the lack of documentation on those topics.
I think the background mode is just a UIKit concept. The app is started (thanks to the UIApplicationMain function) as a regular one but your app UI is not rendered.
It is just a warning: this is a transition state, your app can be suspended at any moment, be concise. The documentation is clear.
Regular UIKit APIs are available (if it was not the case, imagine all the potential crashs). But you won't receive any external events like touches.
Some external tasks like asking permissions, launching audio sessions etc would probably not be available too.
You can wait for the app to be launched by using the wait for the executable to be launched option in the scheme panel.
But when I tried it out, launchOptions was nil. Doesn't that contradict the docs?
Unfortunately LaunchOptions doesn't cover all ways an app gets launched. So if you see it nil then your case is one them too.
But there seems to be no difference in mainScreen in the background process.
That's true and expected. Things all get launched using the main thread. See here
Is there a way I can debug such a background process in XCode?
GaetanZ Has already answered this. Additionally you can use os.log and console together. That gives you a more realistic approach. Xcode interruptions are not fun to deal with. The wait for the executable to be launched scheme change often makes debugging super slow or often Xcode just disconnects or even throws you weird errors and the app gets killed without even giving you the option to attach to the debugger again.
I often use reboot the phone entirely. And then use oslog to see what happens to my app without ever having Xcode connected. For more on that see here.
A reboot is different to user-termination because often things don't get launched after-user termination. That being said I don't think the OS restricts app launch if user engages with their watch — even after a user-termination. Because user-engagement trumps everything.
However, the whole Javascript part of the app did not run (which is kind of expected, because in a background process, we do not need any React UI).
You then also said "which is kind of expected, because in a background process, we do not need any React UI"
I know very little of React, but also I'm confused what your question is about if you say it's expected.
But the part that the AppDelegate goes through all it's life-cycle is expected as previously mentioned.
You need to add a gazzilion amount of logs to see where you have a different code-path.
Most developers don't know that launching the app into the background will go all the way till the root viewController of your app and all its child viewcontrollers and stuff. But you learned it the hard way. Just as I did. Congratulations!
But once you know of that then the next thing is making sure your app doesn't segue into a different code-path i.e. on a normal launch you get WillBecomeActive and willEnterForeground, for a launch into the background you get something else. I'm not sure what it is right now. I think it's WillBecomeActive & didEnterBackground. Not sure.
Or like you may not be setting the delegate of your webview before things fire off and you miss its callbacks.
Remember app being in a background state doesn't mean things get executed on background queue. everything gets executed on the same queue/thread as it would in a foregrounded app. The only thing different is that the OS will often restrict network calls when an app isn't provisioned for them.
Likely that's what's happening. Like the OS doesn't want a webview to make network calls when it hasn't informed the app to be using and background Tasks as mentioned here or here

iOS app getting killed in background - how to debug?

My iOS app gets terminated when put in background. I get the following logs in the device console:
Background Task 160 (""), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.
followed by
Background task still not ended after expiration handlers were called: . This app will likely be terminated by the system. Call UIApplication.endBackgroundTask(_:) to avoid this.
and the app terminates and restarts on resuming from background
The new metric kit background exit data (iOS 14) is also reporting that BackgroundTaskAssertionTimeoutExits are killing my app
On breaking on UIApplicationEndBackgroundTaskError, I get the following backtrace:
I have not implemented any background tasks myself but there are some third party libraries integrated in the app that do.
What is the right way to debug this?
If you did not start any background task, and you do not perform anything most likely some of your 3rd party frameworks are causing the crash.
Update to latest version of all your dependencies, to see if the issue was fixed.
If your issue is easily reproducible, try to disable them 1 by 1 to see which is causing the crash.
After that go on the library support page and see if there are any bugs for your issue and if not open a bug.
Start with the usual suspects, Analytics, Loggers and go on.
Have a look also at this thread: App is crashing on only iOS 13 in the background mode

How to debug a crash which happened when come back from background

There is a crash happen when coming back from background through app icon.
However I cannot see any detail info in console log. There is a signal to terminate, but we cannot find signal number.
<FBApplicationProcess: 0x117bcb930; Maixxxx; pid: 1762> exited abnormally via signal.
Process exited: <FBApplicationProcess: 0x117bcb930; Maixxx; pid: -1> -> <FBApplicationProcessExitContext: 0x17103f820; exitReason: signal; terminationReason: (none)>
The procedures to reproduce my crash is as follow:
Start app through click on app icon.
Use the app as normal user.
Press home to put it in background.
Wait for some minutes.
Click the app icon on springboard screen in order to use it again.
The app crash&exit.
Since the crash only happen when coming back from background, and required to enter background for some minutes, I cannot run in debug mode with lldb attached.
I didn't use any of background features.
Also, I didn't see any crash report in Fabric's Crashlytics. So I think signal handler could not be called neither?
How to investigate this kind of problem?
These things can be tough, I know that from similar experiences. Without knowing more about your app I can only offer hints and no definitive answer, but perhaps this helps you.
The fallback and tedious approach to use direct logging with print and so on notwithstanding there are a two ways to try to "catch" a process.
However, first let me stress that "background" is not always the same and people unfortunately use the term often loosely. Depending on what state transition causes your crash you might run out of luck and have to simply experiment using manual logging. Apps can be in background, i.e. not in the foreground, but still running. This is usually the case when the debugger is attached, otherwise it couldn't do its job. Alternatively they can be suspended (or even terminated) by the OS. The debugger prevents this, which you probably already figured out.
The two things that might help you are:
If you're using background fetch, i.e. "coming back from background mode" as you describe it happens automatically you can activate the "Launch due to a background fetch event" option in your build scheme's "Run" configuration section.
Run your app from the Home screen, put it into background with the Home button and wait a bit (you've probably done so in the past already to get a feeling for when the crash would happen). Your app should eventually go into the suspended state (but you have no way to actually see that anywhere AFAIK). Instead of getting it to the foreground again via the multitasking UI, simply attach the debugger again via the "Debug - Attach to process" menu. This should get your app from the suspended state back into the background state, where the crash probably really happens (if it were to happen when coming from background to foreground you probably would have been able to debug it as usual). Hopefully the debugger has finished attaching to it in time, otherwise I'm out of ideas. :(
I haven't run into this specific problem myself personally, but I know background stuff can be tricky. Maybe this discussion also helps you (I took part of my info from there as well).
Run the app in debug mode on a real device. Press the Home button to send the app to background and continue the debugging. Then you can bring the app to foreground and keep debugging, or put a breakpoint at applicationWillEnterForeground.
You can't debug this on the real device. When the debugger is attached, your apps will never go to background mode in the real device.
You can try to debug this on a simulator.
Anyway please check your class attributes and set attributes to strong to make sure this is not happened by missing attributes.
I have read several StackOverflow questions that have FBApplicationProcess. Usually, this one happened by missing array or something when the app started.
Best regards.
I have gone through all the above answers and all have given proper answers. Though, I would like to share my point of view.
If the app is running on any iOS real device with debug mode and wire plug-in or even on Simulator, App will never go in the background.
If the app is running without wire plug-in or run without Xcode(directly launch the app in iPhone) and then put the app in the background, the app will be running in the background of next 3 mins. After 3 mins, the App will automatically be suspended and removed from the main thread. Now, when we open the app again, It will be considered a fresh launch.
If your app having any Background Capabilities ON, then your app will be alive even in the background, but you can't do any UI changes during that time.
To keep app alive in the background, Background Capabilities must be handled properly. ie. If Location is used in your app with 'While-App is in Foreground' condition, app will not run more than 3 mins in background. So, If you want to run your app continuously in background, you must have to represent proper reason in Info.plist file with Battery drain word, or else, Apple will reject it.
Ping me for more detail on your question.
Thanks.
Crash logs still available on your test device.
To get the crash log try the following steps:
Connect your test device to the Mac through USB.
Launch Xcode. Go to Windows > Devices and Simulators.
Choose your device from the devices section on the left side of the screen.
Select View Device Logs button.
Identify and select the Crash Log to see the contents.

How to test Background App Launch in case of NSURLSession(Background Session) event?

How can one test the scenario of Application Launch in background for handling Background NSURLSession's event?
Flow:
Application starts a upload/download task using Background URL
session.
User hits home button. App is in suspended or in background
state.
OS decides to Exit the application. I know, one can exit the app by double-tapping home button and swipe-up the particular app. But in that case OS will never re-launch the app in background for event handling.
Upload/download task needs some event handling. OS re-lauches App in background.
So the question is how do I make OS exit the app like it may normally do after some-time. The purpose is to test the code for this scenario. I tried using UIApplicationExitsOnSuspend but it does not work since then App can not be launched in Background.
It's not a perfect solution, but I was able to manually test the launch of an app due to a Background URLSession on a physical device as follows:
Connect device for debugging via USB
Disable Internet connectivity on device (i.e. disable WiFi/Cellular)
Start the app via Xcode
Issue a request using background URLSession. The request shouldn't fail, it will just be waiting around for an Internet connection until it times out, so use a reasonably long timeout to make testing easier.
Kill the app via Xcode (press stop button)
View the device logs via Windows > Devices and Simulators
Enable Internet connectivity on the device again without starting the app
The requests from the background URLSession should then complete and in the device logs (from step 6.) you should see any NSLog statements issued as a result of the app being launched via the application(_:handleEventsForBackgroundURLSession:completionHandler:) app delegate method.
They key point is that killing the app via Xcode, as opposed to killing it using device itself, does not prevent the app from being relaunched for background event handling.
A possible alternative to killing the app manually via Xcode might be to intentionally crash the app in code - this might be more suitable for automated testing.
You could write an app that has a button that allocates and intentionally leaks chunks of memory. If you get this thing to allocate enough RAM, the OS will start killing other apps to get their RAM back.
Hopefully this would exhibit the behavior you need.

iOS: Does force quitting the app disables background upload using NSURLSession?

The question is around NSURLSession and NSURLSessionUploadTask.
I'm uploading large files to server and noticed that when I force quit the app the whole background upload just stops. However, when upload starts while app is running through the Xcode/debugger, then my upload completes just fine even when I stop the app running via Xcode 'stop' button. I suspect that force quitting the app using Xcode simulates an iOS system command and not a user action.
So my question is whether it's true that iOS would immediately cancel NSURLSessionUploadTask when user force quit the app?? For some reason I would at least expect an error callback to the app, however nothing happens.
I can confirm now after a bunch of testing that background task will run ok if the app is just put into background. However, if user force quit the app manually, then iOS cancels all scheduled background tasks. So next time the app is launched I'm getting all the callbacks to the delegate with the error code of a canceled task.
Hope it helps someone looking into the same thing.
From Apple's docs about background execution:
If tasks have not yet finished and the system terminates your app, the
system automatically continues managing the tasks in the background.
If the user terminates your app, the system cancels any pending tasks.

Resources