Background Tasks

RSS for tag

Request the system to launch your app in the background to run tasks using Background Tasks.

Background Tasks Documentation

Pinned Posts

Posts under Background Tasks tag

137 Posts
Sort by:
Post not yet marked as solved
3 Replies
147 Views
We have an iOS app built using Capacitor. We are seeing a large increase in app crashes on iOS 17.4 (iPhone). Other OS versions seem to be showing significantly fewer crash numbers. We are unsure what is causing this, as our app did not go through any major releases. I have attached the crash log below. Thanks Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: RUNNINGBOARD 0xd00d2bad
Posted Last updated
.
Post not yet marked as solved
1 Replies
74 Views
I have an app with which users take photos and upload them in batches. It's used often on older devices, in areas with less than ideal network, and for durations of a full workday - so often the device has low power. The current implementation of uploads uses an NSURLSession configured for the foreground, and as a result my users are used to having to keep the app in the foreground while an upload completes. However, these uploads are big and connectivity is often low, so this takes a long time - often users are stuck waiting with the app foregrounded for 15 minutes or so while the upload completes. So, I created a build which uses an NSURLSession configured for the background. In the ideal case, users could start the upload, put the device in their pocket and continue their workday, and the next time they open their device it will be complete. For some users this ideal case has come true. However, for others, the uploads sit in progress for an indeterminate amount of time, making no progress. My suspicion is that this is because the OS is deferring them until a time when network and power is more available. However, my users are using work devices at a work location - reliable power and network might never be available. Being able to background the app and continue working is valuable for these users, but having the upload complete promptly is essential for them. My questions are: Is it true that background configured NSURLSessions will defer network requests when connectivity or power is low, even if discretionary = NO? Is the exact behavior for when requests will be attempted in the background documented? Is there a way to reliably test background configured NSURLSessions in XCode? I've attempted throttling my connection with Charles Proxy, and using my device in Low Power Mode, but I'm unable to reproduce the request stalling behavior my users are experiencing in the wild. Is there a way to create an NSURLSession that will muscle through difficult or inefficient uploads in the background, with the same reliability as a foreground session? If not, what is Apple's recommended approach to situations like mine? I've considered queueing both a background and foreground upload, and cancelling the other once one completes, but this seems disrespectful to the user's resources. Will setting timeoutIntervalForResource to a lower value cause the OS to more aggressively attempt uploads? Or simply to throw an error sooner? I want the OS to give the upload a long time to complete, but I also want it to attempt it right away. Thanks for any information!
Posted Last updated
.
Post not yet marked as solved
0 Replies
88 Views
I am running two different background modes(not at the same time), 1 with a workout and 1 with a location. I noticed that the app logo appears above the watch face for both background modes but does not show up consistently. I wonder what the significance of the logo showing up above watch face is? Additionally why does it show up sometimes but not others? Thanks
Posted Last updated
.
Post not yet marked as solved
2 Replies
118 Views
We are developing an app which connects to a BLE peripheral in the background whenever it gets close to it. What we have used so far is that we monitor a circular region. When the phone enters the region the app will start scanning for peripherals and when it discovers the peripheral it connects to it. This worked pretty well for the last few iOS versions, perhaps iOS 14-16. It wasn't perfect but for the most part it would feel like it connected rather quickly when you would approach the BLE peripheral. If you listen to music via BLE or talk to someone using your BLE headset then it could sometimes work noticeably worse. But, as said, for the most part it would work satisfactory. Starting with iOS 17 and analyzing the functionality over the past 6 months or so we've noticed a clear worsening of it. It does generally connect to the peripheral but the user might often have to wait for quite some time. Rather frequently the user must even light up the screen of the phone before anything even happens. It appears that some sort of resource allocation, battery saving feature or similar has affected this functionality greatly. The time difference between entering a region and physically approaching the device is generally around 2-3 minutes. We have tried to do it more in line with documentation and follow the guidelines that we find in: https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html So in doing this we do not start scanning for peripherals when a region is entered, but instead we directly invoke connectPeripheral:options:. This way we offload to the system that we want to connect to that peripheral. However, when testing this we see no real improvement. Sometimes it connects satisfactorily. Sometimes it doesn't really connect at all. Many times it connects if the user lights up the screen. So just looking at what the user is experiencing our analysis is that doing it this way works even worse than what we previously did. I understand that the system has many resources to consider and that some may have to wait while others perform things. But are there any documentation on what one could expect from initiating a connectPeripheral:options: from the background? In the link I posted it simply states the iOS device will reconnect when the user returns home. So not much detail in terms of performance which is crucial for our application. If there aren't any further details on the performance, are there any other ways to improve this functionality? We are not looking at draining the battery whatsoever but we simply need our background running app to be as responsive as possible for a few minutes after it has been launched by the region monitoring. We understand that battery life is important but since this happens rarely and sparsely (not more than a few times per day) it seems reasonable that there should be a way to be able to make it function properly.
Posted
by pontusa.
Last updated
.
Post not yet marked as solved
2 Replies
115 Views
First off - I have read and fully understand this post - Apple doesn't want us abusing users' hardware so as to maximize the quality of experience across apps for their customers. I am 100% on board with this philosophy, I understand all design decisions and agree with them. To the problem: I have an app that takes photo assets, processes them for network (exportSession.shouldOptimizeForNetworkUse = true), and then uploads them. Some users have been having trouble, did some digging, they're trying to upload 4K 60FPS videos. I think that is ridiculous, but it's not my place. The issue is that the export time for a 4K60FPS video that is ~40s long can be as long as 2m. So if they select a video to upload, and then background the app that upload will ALWAYS fail because the processing fails (I have BG uploads working just fine). My understanding is that default I have 30s to run things in the background. I can use UIApplication.pleasegivemebackgroundtime to request up to 30 more seconds. That is obviously not enough. So my second option is BGProcessingTask - but that's not guaranteed to run ever. Which I understand and agree with, but when the user selects a video while the app is in the foreground the expectation is that it immediately begins processing. So I can't use a BGProcessingTask? Just wondering what the expected resolution here is. I run tasks, beg for time, if it doesn't complete I queue up a BGTask that may or may not ever run? That seems ****** for a user - they start the process, see it begin, but then if the video is too big they just have to deal with it possibly just not happening until later? They open up the app and the progress bar has magically regressed. That would infuriate me. Is there another option I'm not seeing? Some way to say "this is a large background task that will ideally take 30-60s, but it may take up to ~5-7m. It is user-facing though so it must start right away"? (I have never seen 5-7m, but 1-2m is common) Another option is to just upload the full 4K60FPS behemoth and do the processing on my end, but that seems worse for the user? We're gobbling upload bandwidth for something we're going to downsample anyway. Seems worse to waste data than battery (since that's the tradeoff at the end of the day). Anyway, just wondering what the right way to do this is. Trivially reproducible - record 1m 4K60FPS video, create an export session, export, background, enjoy failure.
Posted Last updated
.
Post not yet marked as solved
2 Replies
191 Views
So, we've got a mobile app that is using background processing to occasionally scan for nearby BLE beacons. When running a debug / local build of the app, everything behaves as expected, but if we upload a build to TestFlight and install from there, the background processing doesn't happen. This behavior would seem to point to a capability in the App ID not being provisioned, but when I look in the Identifiers section of Apple Developer, Background Modes as a capability isn't listed for either the existing Application Identifier or when creating a brand new one. The app has the Background Modes capability assigned if I look at it in XCode. Any thoughts as to where to look next or what I'm missing?
Posted Last updated
.
Post not yet marked as solved
0 Replies
92 Views
We are developed app based on driver behaviour using location and sensor data. It's working in both background and foreground using region monitoring. Its consume more battery comparing other apps like. Its reduce 5% for every 5 to 10 mins of duration. We are using for our app functionality Location (Always) - every 1sec Sensor - Accelerometer - every 20data for 1sec Background - Region monitoring Time Action - 1sec for 20time Any possible way to reduce battery consuming? If any please suggest your points. Thanks in advance for your comments.
Posted Last updated
.
Post marked as solved
1 Replies
150 Views
Hi All, I have a strange issue. I am using enableBackgroundDelivery for updating user step count in background mode using health kit. It works fine when I execute the app by pressing 'Run' in xcode. But the code is not triggering when I am directly launching it on my device. I have tried many different things but cannot figure out the issue from 2 days 😭. I would really appreciate any suggestions. Thanks
Posted Last updated
.
Post not yet marked as solved
2 Replies
283 Views
Hi, I have a watchOS app that records audio for an extended period of time and because the mic is active, continues to record in background mode when the watch face is off. However, when a call comes in or Siri is activated, recording stops because of an audio interruption. Here is my code for setting up the session: private func setupAudioSession() { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(.playAndRecord, mode: .default, options: [.overrideMutedMicrophoneInterruption]) try audioSession.setActive(true, options: .notifyOthersOnDeactivation) } catch { print("Audio Session error: \(error)") } } Before this I register an interruption handler that holds a reference to my AudioEngine (which I start and stop each time recording is activated by the user): _audioInterruptionHandler = AudioInterruptionHandler(audioEngine: _audioEngine) And here is how this class implements recovery: fileprivate class AudioInterruptionHandler { private let _audioEngine: AVAudioEngine public init(audioEngine: AVAudioEngine) { _audioEngine = audioEngine // Listen to interrupt notifications NotificationCenter.default.addObserver(self, selector: #selector(handleAudioInterruption(notification:)), name: AVAudioSession.interruptionNotification, object: nil) } @objc private func handleAudioInterruption(notification: Notification) { guard let userInfo = notification.userInfo, let interruptionTypeRawValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt, let interruptionType = AVAudioSession.InterruptionType(rawValue: interruptionTypeRawValue) else { return } switch interruptionType { case .began: print("[AudioInterruptionHandler] Interruption began") case .ended: print("[AudioInterruptionHandler] Interruption ended") print("Interruption ended") do { try AVAudioSession.sharedInstance().setActive(true) } catch { print("[AudioInterruptionHandler] Error resuming audio session: \(error.localizedDescription)") } default: print("[AudioInterruptionHandler] Unknown interruption: \(interruptionType.rawValue)") } } } Unfortunately, it fails with: Error resuming audio session: Session activation failed Is this even possible to do on watchOS? This code worked for me on iOS. Thank you, -- B.
Posted
by trzy.
Last updated
.
Post not yet marked as solved
2 Replies
320 Views
Hi all, My application requires to create a WebSocket server on an iOS application for other devices can connect and transfer data with my application. I used Vapor library to create a socket server and it works well when the application is in the foreground. I am trying to keep the server alive when my app moves to the background or the suspended state so that my app and other devices can continue to communicate with each other. Is there any ways to achieve that? I tried to turn on a mode: "Audio, Airplay, and Picture in Picture" in background modes section in Signing & Capabilities and then my application can still communicate with clients when it is background mode. But my application is an application for user can edit image and send it to other devices through sockets and it does not have audio, airplay,.. feature. Is it ok to publish the app to the app store in the future? Thank you!
Posted
by lgminh.
Last updated
.
Post not yet marked as solved
1 Replies
299 Views
Hello, I have an app that receives critical alarms. This is usually done through remote push notifications from the server, but to add redundancy I'd like to add a MQTT connection as well. There are scenarios where internet connection might be missing (but there is a local WiFi connection to the server) hence I'd like to deliver the alarms directly from server to client without going out via the Internet. The problem is that according to all restrictions on iOS, the MQTT connection will not be maintained in the background and disconnect occurs within 20-30 sec after going in the background and shutting the screen. I'm aware of all the background modes that iOS allows but none fall within this scenario. Is there a way to maintain a MQTT connection (or some other type of network connection) in the background on iOS?
Posted
by codenea1.
Last updated
.
Post marked as solved
6 Replies
514 Views
My App keeps crashing in the background and I don't know why. I'm using SwiftData and SwiftUI. I'm setting up a .backgroundTask like this: import SwiftUI import SwiftData import TipKit @main struct MyAppName: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate @State var navManager = NavigationManager.load() @State var alerter: Alerter = Alerter() var sharedModelContainer: ModelContainer = { do { return try ModelContainer(for: DataController.schema, configurations: [DataController.modelConfig]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { SetupView() .accentColor(.myAccentColor) .environment(alerter) .alert(isPresented: $alerter.isShowingAlert) { alerter.alert ?? Alert(title: Text(verbatim: "")) } .task { try? Tips.configure([ .displayFrequency(.immediate), .datastoreLocation(.applicationDefault) ]) } .onAppear { setUpAppDelegate() } } .modelContainer(sharedModelContainer) .backgroundTask(.appRefresh(Const.backgroundAppRefreshId)) { @MainActor in let container = sharedModelContainer await RefreshManager.handleBackgroundVideoRefresh(container) } .environment(navManager) } func setUpAppDelegate() { appDelegate.navManager = navManager } } The RefreshManager.handleBackgroundRefresh(...) goes on to load data and then insert models for them via SwiftData. It only happens occasionally and afaik only in the background. Weirdly enough the issue seems to be there even when I only print something in the background task. Even when I don't schedule/set a background task at all. How can that be? The crashes started in the version that included the .backgroundTask, although perhaps it's related to something else. I'm still trying to further narrow it down. This is the crash report that I'm getting: Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x00000001a1bb98c0 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [809] Triggered by Thread: 0 Thread 0 name: Thread 0 Crashed: 0 libswiftCore.dylib 0x00000001a1bb98c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 libswiftCore.dylib 0x00000001a1c27d14 swift_unexpectedError + 664 (ErrorType.swift:188) 2 _SwiftData_SwiftUI 0x000000024310cd78 one-time initialization function for empty + 300 (ModelContainer+Extensions.swift:5) 3 libdispatch.dylib 0x00000001ab16add4 _dispatch_client_callout + 20 (object.m:576) 4 libdispatch.dylib 0x00000001ab16c654 _dispatch_once_callout + 32 (once.c:52) 5 _SwiftData_SwiftUI 0x000000024310cdf8 one-time initialization function for empty + 124 (ModelContainer+Extensions.swift:12) 6 libdispatch.dylib 0x00000001ab16add4 _dispatch_client_callout + 20 (object.m:576) 7 libdispatch.dylib 0x00000001ab16c654 _dispatch_once_callout + 32 (once.c:52) 8 _SwiftData_SwiftUI 0x0000000243122170 key path getter for EnvironmentValues.modelContext : EnvironmentValues + 140 (<compiler-generated>:0) 9 libswiftCore.dylib 0x00000001a1ce4628 RawKeyPathComponent._projectReadOnly<A, B, C>(_:to:endingWith:) + 1012 (KeyPath.swift:1701) 10 libswiftCore.dylib 0x00000001a1ce3ddc KeyPath._projectReadOnly(from:) + 1036 (KeyPath.swift:331) 11 libswiftCore.dylib 0x00000001a1ce8348 swift_getAtKeyPath + 24 (KeyPath.swift:2029) 12 SwiftUI 0x00000001a7af4814 EnvironmentBox.update(property:phase:) + 872 (Environment.swift:273) 13 SwiftUI 0x00000001a782a074 static BoxVTable.update(ptr:property:phase:) + 396 (DynamicPropertyBuffer.swift:294) 14 SwiftUI 0x00000001a78297b0 _DynamicPropertyBuffer.update(container:phase:) + 104 (DynamicPropertyBuffer.swift:215) 15 SwiftUI 0x00000001a887fb78 closure #1 in closure #1 in DynamicBody.updateValue() + 104 (DynamicProperty.swift:447) 16 SwiftUI 0x00000001a887fbb8 partial apply for closure #1 in closure #1 in DynamicBody.updateValue() + 28 (<compiler-generated>:0) 17 libswiftCore.dylib 0x00000001a1bcc068 withUnsafeMutablePointer<A, B>(to:_:) + 28 (LifetimeManager.swift:82) 18 SwiftUI 0x00000001a887f9dc closure #1 in DynamicBody.updateValue() + 408 (DynamicProperty.swift:446) 19 SwiftUI 0x00000001a887f5c0 DynamicBody.updateValue() + 712 (DynamicProperty.swift:445) 20 SwiftUI 0x00000001a71e8bf8 partial apply for implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 32 (<compiler-generated>:0) 21 AttributeGraph 0x00000001cbd4c240 AG::Graph::UpdateStack::update() + 512 (ag-graph-update.cc:578) 22 AttributeGraph 0x00000001cbd42f38 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 424 (ag-graph-update.cc:719) 23 AttributeGraph 0x00000001cbd42810 AG::Graph::input_value_ref_slow(AG::data::ptr<AG::Node>, AG::AttributeID, unsigned int, unsigned int, AGSwiftMetadata const*, unsigned char&, long) + 720 (ag-graph.cc:1429) 24 AttributeGraph 0x00000001cbd423a4 AGGraphGetValue + 228 (AGGraph.mm:701) 25 SwiftUI 0x00000001a887f548 DynamicBody.updateValue() + 592 (DynamicProperty.swift:444) 26 SwiftUI 0x00000001a71e8bf8 partial apply for implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 32 (<compiler-generated>:0) 27 AttributeGraph 0x00000001cbd4c240 AG::Graph::UpdateStack::update() + 512 (ag-graph-update.cc:578) 28 AttributeGraph 0x00000001cbd42f38 AG::Graph::update_attribute(AG::data::ptr<AG::Node>, unsigned int) + 424 (ag-graph-update.cc:719) [...] 107 SwiftUI 0x00000001a7cf79fc static App.main() + 132 (App.swift:114) 108 MyAppName 0x0000000100e6d120 static MyAppNameApp.$main() + 52 (MyAppNameApp.swift:0) 109 MyAppName 0x0000000100e6d120 main + 64 110 dyld 0x00000001c67c2d84 start + 2240 (dyldMain.cpp:1298) The report also says key path getter for EnvironmentValues.modelContext, which seems odd. Any idea where I could start to look for the issue? I'm currently just trying things out, pushing them to TestFlight and waiting for crashes to happen. As soon as I can narrow it down further I'll update this.
Posted
by fer0n.
Last updated
.
Post not yet marked as solved
5 Replies
557 Views
My background audio app stops updating its Live Activity after the iPhone locks, and doesn't resume updating the activity after tapping the screen or even after FaceID unlocks the device (without opening the lock screen). My live activity requests a ContentState update & iOS updates the content for the activity as below: Task{ log.debug("LiveActivityManager.updateLiveActivity() with new ContentState") await liveActivity.update( ActivityContent(state:contentState, staleDate:nil) ) } Below what my log looks like: <<<<SWIPE LOCK SCREEN DOWN>>>> DEBUG: LiveActivityManager.updateLiveActivity() with new ContentState iOS: Updating content for activity 0A519263-1E46-4BB6-BA4F-F3DDBC081AB4 DEBUG: LiveActivityManager.updateLiveActivity() with new ContentState iOS: Updating content for activity 0A519263-1E46-4BB6-BA4F-F3DDBC081AB4 <<<<PRESS LOCK BUTTON->Lock iPhone>>>> INFO: --------protectedDataWillBecomeUnavailableNotification-------- DEBUG: LiveActivityManager.updateLiveActivity() with new ContentState iOS: Updating content for activity 0A519263-1E46-4BB6-BA4F-F3DDBC081AB4 DEBUG: LiveActivityManager.updateLiveActivity() with new ContentState DEBUG: LiveActivityManager.updateLiveActivity() with new ContentState DEBUG: LiveActivityManager.updateLiveActivity() with new ContentState <<<<LOOK AT & TAP LOCK SCREEN->Unlock iPhone without swiping up>>>> INFO: --------protectedDataDidBecomeAvailableNotification----------- DEBUG: LiveActivityManager.updateLiveActivity() with new ContentState DEBUG: LiveActivityManager.updateLiveActivity() with new ContentState DEBUG: LiveActivityManager.updateLiveActivity() with new ContentState As shown in the log, normally iOS updates the content for my activity after my liveActivity.update request. This works fine in the Dynamic Island and when after switching apps and swiping down to see the lock screen without locking the phone. However, once I lock the phone, iOS stops updating the Live Activity content, and doesn't resume updates until after the app regains the foreground at least once. Has anyone else encountered this behavior? Is this a setting that I'm missing, or a bug?
Posted
by zabelc.
Last updated
.
Post not yet marked as solved
4 Replies
473 Views
XCode 15.3, watchOS 10.4 SDK Our health-related app is exploring adding an additional feature that would make use of extended runtime sessions to guide users through an activity. A user starts a session by tapping a button on the watchOS app's interface. If a session is already running, pressing that button should cause the current session to invalidate, and a new session should be created so we can start again from the beginning. TLDR: Running new sessions works as expected on the simulator but not on a real device. Why? We currently have a barebones implementation that includes logging in the extended runtime session delegate functions, on the button push, and when the new session is about to start. Here's what our logging output for the simulator looks like when we try to invalidate the current session and run another one: Invalidating extended session Optional("<WKExtendedRuntimeSession: 0x60000262d7a0> state=2, sessionID=4894EB1D-96F7-4921-8263-378E304E719F, expirationDate=2024-03-20 13:01:10 +0000") at 12:01:21 PM Extended runtime session <WKExtendedRuntimeSession: 0x60000262d7a0> state=3, sessionID=4894EB1D-96F7-4921-8263-378E304E719F, expirationDate=2024-03-20 13:01:10 +0000 invalidated for reason WKExtendedRuntimeSessionInvalidationReason(rawValue: 0) with error nil at 12:01:21 PM Requesting new extended session in application state 0 at 12:01:22 PM Starting new extended session Optional("<WKExtendedRuntimeSession: 0x600002644540> state=0, sessionID=B34ECCFF-A0DA-45C1-9FD1-FD0F335FBE02, expirationDate=(null)") in application state 0 at 12:01:23 PM Did start extended session <WKExtendedRuntimeSession: 0x600002644540> state=2, sessionID=B34ECCFF-A0DA-45C1-9FD1-FD0F335FBE02, expirationDate=2024-03-20 13:01:23 +0000 at 12:01:23 PM As you can see, we successfully invalidate a running session, a button press requests a new one, and then we create and start a new runtime session instance which ends in the running (2) state. We can repeat this over and over without issue. The exact same code running on an actual device produces this: Invalidating extended session Optional(\"<WKExtendedRuntimeSession: 0x15db5750> state=2, sessionID=889FE2E8-0FDA-4826-9094-4D48094FEBED, expirationDate=2024-03-20 12:53:55 +0000\") at 11:56:04AM Extended runtime session <WKExtendedRuntimeSession: 0x15db5750> state=3, sessionID=889FE2E8-0FDA-4826-9094-4D48094FEBED, expirationDate=2024-03-20 12:53:55 +0000 invalidated for reason WKExtendedRuntimeSessionInvalidationReason(rawValue: 0) with error nil at 11:56:04AM Requesting new extended session in application state 0 at 11:56:05AM Starting new extended session Optional(\"<WKExtendedRuntimeSession: 0x15e0aba0> state=0, sessionID=D5020337-D20B-48BE-B2EE-EE44BE580AEC, expirationDate=(null)\") in application state 0 at 11:56:06AM Extended runtime session <WKExtendedRuntimeSession: 0x15e0aba0> state=3, sessionID=D5020337-D20B-48BE-B2EE-EE44BE580AEC, expirationDate=(null) invalidated for reason WKExtendedRuntimeSessionInvalidationReason(rawValue: 1) with error nil at 11:56:06AM The difference is in the last line: starting the session was unsuccessful and it was immediately invalidated, with the reason WKExtendedRuntimeSessionInvalidationReason(rawValue: 1) which maps to the enum sessionInProgress. This is surprising, since we just invalidated and dereferenced the old runtime session. What else can we do to tear down this session? In fact, no other extended runtime sessions can be created and started successfully until the device is rebooted. One note is that on the simulator we do get the following warning right after invalidating the running session: -[WKExtendedRuntimeSession _invalidateWithError:]_block_invoke_2:527: Got error Error Domain=com.apple.CarouselServices.SessionErrorDomain Code=3 "Session not running <CSLSession: 0x600003b4eca0; pid: 8833; dismissed: NO; ended: YES; duration: 3600.0; autoEnd: NO; launchable: NO; mutuallyExclusive: YES; managed: YES; persisted: NO; requiresFGActiveInitiation: YES; lastForeground: 2024-03-20 12:01:21 +0000> |CSLSSession = { | sessionID: 4894EB1D-96F7-4921-8263-378E304E719F; bundleID: com.bundle; type: "physical therapy"; running: NO; paused: NO; expirationDate: 2024-03-20 13:01:10 +0000; supportsAOT: NO; lastStartWasScheduled: NO; remote: NO; |}" UserInfo={NSLocalizedDescription=Session not running <CSLSession: 0x600003b4eca0; pid: 8833; dismissed: NO; ended: YES; duration: 3600.0; autoEnd: NO; launchable: NO; mutuallyExclusive: YES; managed: YES; persisted: NO; requiresFGActiveInitiation: YES; lastForeground: 2024-03-20 12:01:21 +0000> |CSLSSession = { | sessionID: 4894EB1D-96F7-4921-8263-378E304E719F; bundleID: com.bundle; type: "physical therapy"; running: NO; paused: NO; expirationDate: 2024-03-20 13:01:10 +0000; supportsAOT: NO; lastStartWasScheduled: NO; remote: NO; |}} This appears to be thrown by some part of Carousel, for which no public documentation exists, and it clearly doesn't disrupt the expected behavior on the simulator. I don't know if this is being thrown on the device, since our logging wouldn't be able to pick it up. Please let me know if we are approaching this incorrectly or if there are any known solutions to this issue.
Posted
by bcappdev.
Last updated
.
Post not yet marked as solved
0 Replies
256 Views
Hello, I'm developing a voice communication App using Livekit SDK. Everything works fine in the foreground, AudioSession is activated and audio transmitted. However, I would like to add a feature, I would like my app to receive audio even when it's in background or terminated. I know I can run code when the App is in that state by sending a background push notification, but the only thing that is not working in that case is the AudioSession activation. It fails with error "Session activation failed", no more clues. I tried every combination of category and mode, but no success. Bacground modes in XCode have been activated: -Audio, AirPlay, and Picture in Picture -Background Processing Is this a limit of Livekit? I would be grateful if someone can point me into the right direction.
Posted
by enrico-g.
Last updated
.
Post not yet marked as solved
4 Replies
277 Views
Can't we set up a network server that constantly runs in the background, even in the applications we will develop for corporate companies? @eskimo
Posted Last updated
.
Post not yet marked as solved
0 Replies
275 Views
hi I recently developed an iOS APP which will advertise in background, as I checked the developer document, device name and service uuid will be ignored when iOS APP goes to background. But I found an APP named Berkanan which can broadcast in backgound with device name and service uuid, and its device name length exceeds 8 bytes, does anyone know how it implements? thanks!
Posted
by Pandak.
Last updated
.
Post not yet marked as solved
0 Replies
343 Views
We have been using the BGTask (specifically a BGProcessingTask) reliably for the last couple of years for our app. Up until now they wake up automatically while the screen is off, the iPad is plugged in, and the app is running (that is, in the background), but never while the screen is on (that is, never when the scenePhase == .active). For the last month or so, I've noticed that they are triggering now while the screen is displayed. How is this possible??? Did something change with a recent version of iOS? It's violating Apple's own documentation, which describes the BGProcessingTask as: "A time-consuming processing task that runs while the app is in the background."
Posted Last updated
.
Post marked as solved
1 Replies
373 Views
I'm working on a app that can communicate, send and receive data from our own MFi scanner. Ideally, this app can receives data and remains communication even when it's in background, but I can only runs a background task for maximum 30 sec. Along with this main app, we also have a keyboard extension as an interface that can publish collected data to other app that user prefers with string format. However, It seems like Apple doesn't allow to implement UIApplication.shared.beginBackgroundTask method in extension class, is there any alternative that worth to try? Also, can I extend app background task time elapsed to at least 30 minutes? If I can get an official response would be great!
Posted
by Rimbaud.
Last updated
.
Post not yet marked as solved
0 Replies
11k Views
I regularly see questions, both here on DevForums and in my Day Job™ at DTS, that are caused by a fundamental misunderstanding of how background execution works on iOS. These come in many different variants, for example: How do I keep my app running continuously in the background? If I schedule a timer, how do I get it to fire when the screen is locked? How do I run code in the background every 15 minutes? How do I set up a network server that runs in the background? How can my app provide an IPC service to another one of my apps while it’s in the background? How can I resume my app in the background if it’s been ‘force quit’ by the user? The short answer to all of these is You can’t. iOS puts strict limits on background execution. Its default behaviour is to suspend your app shortly after the user has moved it to the background; this suspension prevents the process from running any code. There’s no general-purpose mechanism for: Running code continuously in the background Running code at some specific time in the background Running code periodically at a guaranteed interval Resuming in the background in response to a network or IPC request However, iOS does provide a wide range of special-purpose mechanisms for accomplishing specific user goals. For example: If you’re building a music player, use the audio background mode to continue playing after the user has moved your app to the background. If you’re building a timer app, use a local notification to notify the user when your timer has expired. If you’re building a video player app, use AVFoundation’s download support. Keep in mind that the above is just a short list of examples. There are many other special-purpose background execution mechanisms, so you should search the documentation for something appropriate to your needs. IMPORTANT Each of these mechanisms fulfils a specific purpose. Do not attempt to use them for some other purpose. Before using a background API, read clause 2.5.4 of the App Review Guidelines. Additionally, iOS provides some general-purpose mechanisms for background execution: To resume your app in the background in response to an event on your server, use a background notification (aka a ‘silent’ push). For more information, see Pushing background updates to your App. To request a small amount of background execution time to refresh your UI, use BGAppRefreshTaskRequest. To request extended background execution time, typically delivered overnight when the user is asleep, use BGProcessingTaskRequest. To prevent your app from being suspended for a short period of time so that you can complete some user task, use a UIApplication background task. For more information on this, see UIApplication Background Task Notes. To download or upload a large HTTP resource, use an NSURLSession background session. All of these mechanisms prevent you from abusing them to run arbitrary code in the background. As an example, consider the NSURLSession resume rate limiter. For more information about these limitations, and background execution in general, I strongly recommend that you watch WWDC 2020 Session 10063 Background execution demystified. It’s an excellent resource. Specifically, this talk addresses a common misconception about the app refresh mechanism (BGAppRefreshTaskRequest and the older background fetch API). Folks assume that app refresh will provide regular background execution time. That’s not the case. The system applies a range of heuristics to decide which apps get app refresh time and when. This is a complex issue, one that I’m not going to try to summarise here, but the take-home message is that, if you expect that the app refresh mechanism will grant you background execution time, say, every 15 minutes, you’ll be disappointed. In fact, there are common scenarios where it won’t grant you any background execution time at all! Watch the talk for the details. When the user ‘force quits’ an app by swiping up in the multitasking UI, iOS interprets that to mean that the user doesn’t want the app running at all. So: If the app is running, iOS terminates it. iOS also sets a flag that prevents the app from being launched in the background. That flag gets cleared when the user next launches the app manually. This gesture is a clear statement of user intent; there’s no documented way for your app to override the user’s choice. Note In some circumstances iOS will not honour this flag. The exact cases where this happens are not documented and have changed over time. Finally, if you have questions about background execution that aren’t covered by the resources listed here, please open a new thread on DevForums with the details. Tag it appropriately for the technology you’re using; if nothing specific springs to mind, use Background Tasks. Also, make sure to include details about the specific problem you’re trying to solve because, when it comes to background execution, the devil really is in the details. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Change history: 2024-03-21 Added a discussion of ‘force quit’. 2023-05-11 Added a paragraph that explains a common misconception about the app refresh mechanism. Made other minor editorial changes. 2021-08-12 Added more entries to the common questions list, this time related to networking and IPC. Made minor editorial changes. 2021-07-26 Extended the statement about what’s not possible to include “running code periodically at a guaranteed interval”. 2021-07-22 First posted.
Posted
by eskimo.
Last updated
.