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

164 Posts
Sort by:
Post not yet marked as solved
0 Replies
114 Views
https://developer.apple.com/documentation/clockkit/creating_and_updating_a_complication_s_timeline I just run sample app to check background delivery on health kit. I added caffein on my health app on phone. but it dosen't triggered on obeserver processUpdate function. func processUpdate(query: HKObserverQuery,             completionHandler: @escaping () -> Void,             error: Error?) {     print("processUpdate come!!!!")     logger.debug("Received an update from the background observer query.")           // Check for any errors that occur while setting up the observer query.     guard error == nil else {       logger.error("Unable to set up a background observer query: \(error!.localizedDescription)")       fatalError()     }           logger.debug("Responding to a background query.")           Task {               // Load the updated data from the HealthKit Store.       let success = await loadNewDataFromHealthKit()               // Check for any errors.       guard success == true else {         logger.error("Unable to query for new or deleted caffeine samples.")         fatalError()       }               // Call the completion handler when done.       completionHandler()     }   }
Posted
by kotran.
Last updated
.
Post not yet marked as solved
0 Replies
224 Views
Hello, We are a company working on Ultra Wideband solutions and, hence, using Apple's NearbyInteraction framework to establish UWB Ranging sessions with our UWB-enabled third-party accessory. This week we were excited about the new background UWB Ranging session possibility, which opens new use cases. The wwdc2022 10008 video that provides the technical details for this feature indicates that the third-party accessory is responsible to expose the Nearby Interaction GATT Server. We don't manage to get full details about what needs to be implemented to by compliant with Apple's framework. The URL below indicates that full BLE details should be explained in the "Nearby Interaction Accessory Protocol Specification" but we don't see any info there. https://developer.apple.com/documentation/nearbyinteraction/ninearbyaccessoryconfiguration https://developer.apple.com/nearby-interaction/specification/ Can someone indicate us where the find full details for this background Nearby Interaction feature? Thanks in advance. Regards.
Posted
by gorka-mk.
Last updated
.
Post not yet marked as solved
1 Replies
226 Views
I am working on an iOS app where VOIP push notifications are working as expected in the app foreground and background scenario. When the app is terminated by the user and lets say after 1 min the iPhone receives the VOIP push for my app, but the app is not launched in the background and therefore didReceiveIncomingPushWithPayload is never getting called. Can anyone please help me why am i seeing this behavior ? Thanks in Advance.
Posted
by LBiOSDev.
Last updated
.
Post not yet marked as solved
0 Replies
26k Views
The UIApplication background task mechanism allows you to prevent your app from being suspended for short periods of time. While the API involved is quite small, there’s still a bunch of things to watch out for. The name background task is somewhat misappropriate. Specifically, beginBackgroundTask(expirationHandler:) doesn’t actually start any sort of background task, but rather it tells the system that you have started some ongoing work that you want to continue even if your app is in the background. You still have to write the code to create and manage that work. So it’s best to think of the background task API as raising a “don’t suspend me” assertion. You must end every background task that you begin. Failure to do so will result in your app being killed by the watchdog. For this reason I recommend that you attach a name to each background task you start (by calling beginBackgroundTask(withName:expirationHandler:) rather than beginBackgroundTask(expirationHandler:)). A good name is critical for tracking down problems when things go wrong. IMPORTANT Failing to end a background task is the number one cause of background task problems on iOS. This usually involves some easy-to-overlook error in bookkeeping that results in the app begining a background task and not ending it. For example, you might have a property that stores your current background task identifier (of type UIBackgroundTaskIdentifier). If you accidentally creates a second background task and store it in that property without calling endBackgroundTask on the identifier that’s currently stored there, the app will ‘leak’ a background task, something that will get it killed by the watchdog. Background tasks can end in one of two ways: When your app has finished doing whatever it set out to do. When the system calls the task’s expiry handler. Your code is responsible for calling endBackgroundTask(_:) in both cases. All background tasks must have an expiry handler that the system can use to ‘call in’ the task. The background task API allows the system to do that at any time. Your expiry handler is your opportunity to clean things up. It should not return until everything is actually cleaned up. It must run quickly, that is, in less than a second or so. If it takes too long, your app will be killed by the watchdog. Your expiry handler is called on the main thread. It is legal to begin and end background tasks on any thread, but doing this from a secondary thread can be tricky because you have to coordinate that work with the expiry handler, which is always called on the main thread. The system puts strict limits on the total amount of time that you can prevent suspension using background tasks. On current systems you can expect about 30 seconds. IMPORTANT I’m quoting these numbers just to give you a rough idea of what to expect. The target values have changed in the past and may well change in the future, and the amount of time you actually get depends on the state of the system. The thing to remember here is that the exact value doesn’t matter as long as your background tasks have a functional expiry handler. You can get a rough estimate of the amount of time available to you by looking at UIApplication’s backgroundTimeRemaining property. IMPORTANT The value returned by backgroundTimeRemaining is an estimate and can change at any time. You must design your app to function correctly regardless of the value returned. It’s reasonable to use this property for debugging but we strongly recommend that you avoid using as part of your app’s logic. IMPORTANT Basing app behaviour on the value returned by backgroundTimeRemaining is the number two cause of background task problems on iOS. The system does not guarantee any background task execution time. It’s possible (albeit unlikely, as covered in the next point) that you’ll be unable to create a background task. And even if you do manage to create one, its expiry handler can be called at any time. beginBackgroundTask(expirationHandler:) can fail, returning UIBackgroundTaskInvalid, to indicate that you the system is unable to create a background task. While this was a real possibility when background tasks were first introduced, where some devices did not support multitasking, you’re unlikely to see this on modern systems. The background time ‘clock’ only starts to tick when the background task becomes effective. For example, if you start a background task while the app is in the foreground and then stay in the foreground, the background task remains dormant until your app moves to the background. This can help simplify your background task tracking logic. The amount of background execution time you get is a property of your app, not a property of the background tasks themselves. For example, starting two background task in a row won’t give you 60 seconds of background execution time. Notwithstanding the previous point, it can still make sense to create multiple background tasks, just to help with your tracking logic. For example, it’s common to create a background task for each job being done by your app, ending the task when the job is done. Do not create too many background tasks. How many is too many? It’s absolutely fine to create tens of background tasks but creating thousands is not a good idea. IMPORTANT iOS 11 introduced a hard limit on the number of background task assertions a process can have (currently about 1000, but the specific value may change in the future). If you see a crash report with the exception code 0xbada5e47, you’ve hit that limit. Note The practical limit that you’re most likely to see here is the time taken to call your expiry handlers. The watchdog has a strict limit (a few seconds) on the total amount of time taken to run background task expiry handlers. If you have thousands of handlers, you may well run into this limit. If you’re working in a context where you don’t have access to UIApplication (an app extension or on watchOS) you can achieve a similar effect using the performExpiringActivity(withReason:using:) method on ProcessInfo. If your app ‘leaks’ a background task, it may end up being killed by the watchdog. This results in a crash report with the exception code 0x8badf00d (“ate bad food”). IMPORTANT A leaked background task is not the only reason for an 0x8badf00d crash. You should look at the backtrace of the main thread to see if the main thread is stuck in your code, for example, in a synchronous networking request. If, however, the main thread is happily blocked in the run loop, a leaked background task should be your primary suspect. Prior to iOS 11 information about any outstanding background tasks would appear in the resulting crash report (look for the text BKProcessAssertion). This information is not included by iOS 11 and later, but you can find equivalent information in the system log. The system log is very noisy so it’s important that you give each of your background tasks an easy-to-find name. For more system log hints and tips, see Your Friend the System Log. iOS 13 introduced the Background Tasks framework. This supports two type of requests: The BGAppRefreshTaskRequest class subsumes UIKit’s older background app refresh functionality. The BGProcessingTaskRequest class lets you request extended background execution time, typically overnight. WWDC 2020 Session 10063 Background execution demystified is an excellent summary of iOS’s background execution model. Watch it, learn it, love it! For more background execution hints and tips, see Background Tasks Resources. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Revision History 2022-06-08 Corrected a serious error in the discussion of BGProcessingTaskRequest. Replaced the basic system log info with a reference to Your Friend the System Log. Added a link to Background Tasks Resources. Made other minor editorial changes. 2021-02-27 Fixed the formatting. Added a reference to the Background Tasks framework and the Background execution demystified WWDC presentation. Minor editorial changes. 2019-01-20 Added a note about changes in the iOS 13 beta. Added a short discussion about beginning and ending background tasks on a secondary thread. 2018-02-28 Updated the task name discussion to account for iOS 11 changes. Added a section on how to debug ‘leaked’ background tasks. 2017-10-31 Added a note about iOS 11’s background task limit. 2017-09-12 Numerous updates to clarify various points. 2017-08-17 First posted.
Posted
by eskimo.
Last updated
.
Post not yet marked as solved
0 Replies
108 Views
General: DevForums tag: Background Tasks Background Tasks framework documentation UIApplication background tasks documentation ProcessInfo expiring activity documentation watchOS background execution documentation WWDC 2020 Session 10063 Background execution demystified — This is critical resource. Watch it! WWDC 2022 Session 10142 Efficiency awaits: Background tasks in SwiftUI iOS Background Execution Limits DevForums post UIApplication Background Task Notes DevForums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
Posted
by eskimo.
Last updated
.
Post not yet marked as solved
0 Replies
101 Views
Hello everybody, I know, that an app can request additionally time in background by calling beginBackgroundTask. But as documentation and many other posts says, it is only designed to finish a possible longer running task. (I tried to extend background execution beyond that by calling beginBackgroundTask with a timer, but that does not seem to reliably work and seems not the way it should be used.) As I am a developer of a fitness app, I am interested in keeping the app running in the background for a longer time (> 30min), if the user decides to turn off the device or to have another app in the front to watch a stream during the training. There should be a way to make this work, since running apps work in the background for multiple hours without being terminated. I even have a simple HitSet-timer-app, that works in the background, while a streaming app is in the foreground. Can anyone help me with that or point me in the right direction? Thank you in advance!
Posted
by bernik.
Last updated
.
Post marked as solved
3 Replies
323 Views
My program is shown in following. I want to get the dataTask session's error code working in background, but I haven't achieved it. let config:URLSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "abcd") self.session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) let task: URLSessionDataTask = session!.dataTask(with: myRequest as URLRequest) task.resume() In the program above, there isn't any parameter with error information, so I rewrite it as following. But when I run the following program, the exception error happens. By the way, about the following program, it can be run successfully when URLSession is configured as normal session, but when URLSession is configured as background session as following, the exception error happens when it's run. Anyone can give me some advice? Thanks a lot! let config:URLSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "abcd") self.session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) let task: URLSessionDataTask = session!.dataTask(with: myRequest as URLRequest) { (data, response, error) in             if let response = response as? HTTPURLResponse {                     NSLog("response.statusCode = \(response.statusCode)")             }        } task.resume()
Posted
by panawyf.
Last updated
.
Post not yet marked as solved
1 Replies
215 Views
Hi Apple Team, I have to do some such functionality in my applications that when application is in background, I have to upload the entire gallery assets of the iphone to a server (if the user has given permission to upload). I have come to a point where my background processing is not running for more than 28-30 seconds. And my process is such that I pick up the asset one by one from the gallery and process it and put it in a single task for uploading to the background thread. All this happens in a loop and photos are uploaded one after the other untill 28-30 seconds(in background). As I have also got my app registered for background processing and also coding is running from all standard process according to apple documentation. So I have to ask you something about background processing, my questions are as follows: 1: What is the maximum duration for background processing and background uploading? What if I want to increase the duration of background processing in my app? 2: Does Apple extend the background processing time for certain category of apps, if it does, then please mention those categories(Or share some links). 3: As my application is built for a particular organization(they upload their all photos), I need maximum background upload limit, is there any way Apple provides for that? if yes, could you please share sample code base or links. 4: Some applications like Google Photos etc. upload in the background for more than 30 seconds, is there a standard procedure that I can achieve as well? 5: If there is any framework provided by Apple to do this work then please mention it. Thanks, I am waiting for your kind reply.
Posted Last updated
.
Post marked as solved
9 Replies
753 Views
I am working on some study in sending the data from iphone to server, and I want to keep the communication even when my program is working on the background mode. For the details, when my program monitors the beacon' signal with special UUID by Corelocation( in other words, the iphone is taken into the beacon'region), then in Corelocation's handling function, the dataTask of URLSession will be excuted to forward the BLE signal's information to server. Because the beacon sends the BLE signal periodically and continuously, I think the data will be sent from iphone to sever with my program continuously. But now, my experiment result is, when I change the application into background: -sometimes, the dataTask can be kept for several hours or one or two days without any problem -sometimes, the dataTask will be stopped and after several minutes, it will be restarted automatically (really confusing). And in this case, I find the BLE monitoring program is kept to work, only the dataTask communication has been stopped I want to know the reason and the dataTask's action condition of the above phenomenon such as keeping or stoping or restarting the communication. Is there any method to keep the communication between the iphone and server without any interruption? Thanks a lot!
Posted
by panawyf.
Last updated
.
Post not yet marked as solved
2 Replies
278 Views
I want to create a hands-free application (e.g. smart lock)using the Nearby Interaction framework. Nearby Interaction sessions can only be active when the app is in the foreground, however, it can't be a complete hands-free application. Does anyone have any good ideas?
Posted
by GPSMRI.
Last updated
.
Post not yet marked as solved
1 Replies
167 Views
I want to send the data from iphone to server periodly in background. I use URLSession (dataTask) to try it , and when my program is changed into background: sometimes, the communication can be kept for several hours without any problem sometimes, the dataTask will be stopped and after several minutes, it will be restarted automatically Is there any method to keep the communication between the iphone and server continuously?
Posted
by panawyf.
Last updated
.
Post not yet marked as solved
1 Replies
172 Views
I was wondering that how to get pasteboard content when app was in background. It showed that: "retrieving pasteboard named com.apple.UIKit.pboard.general failed with error: Error Domain=PBErrorDomain Code=10 "Pasteboard com.apple.UIKit.pboard.general is not available at this time." And it returned null . how to deal with it ?
Posted
by MoscaPaul.
Last updated
.
Post marked as solved
1 Replies
205 Views
I have a downchannel half-connection to the Amazon Alexa cloud https://developer.amazon.com/en-US/docs/alexa/alexa-voice-service/manage-http2-connection.html#create Now, if the APP enters the background, my connection will be broken. Even if I put it in the backgroundTask, I cannot maintain the connection through ping, How do I maintain this HTTP persistent connection when the APP is in the background, plz。
Posted
by tongxingx.
Last updated
.
Post not yet marked as solved
1 Replies
186 Views
Hi dear , I am a beginner developer I have an application idea , and I think its great idea 😎 I think the application needs to use Device activity frame work , and UIScreen class , even if the app is in background or terminated , the problem is I don't know how to use these classes and frameworks 🤷🏻‍♂️ the questions are : can I detect UITouch event on UIScreen object even if the app is in background or terminated How to get the current activity name of the device
Posted Last updated
.
Post not yet marked as solved
4 Replies
1.9k Views
I've got some crash reports which aren't easy to understand. All the crashes happened when the application is in the background with multiple notifications received even without clicking on the notifications. Crashes are related to the autorelease pool but don’t know the exact root cause.  This is the stack: OS Version: iPhone OS 14.1 (18A8395) Release Type: User Baseband Version: 2.01.05 Report Version: 104 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000020 VM Region Info: 0x20 is not in any region. Bytes before following region: 4306190304 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START-- __TEXT 100ab4000-100bd8000 [ 1168K] r-x/r-x SM=COW ...rexendoMobile Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [1010] Triggered by Thread: 0 Thread 0 name: Thread 0 Crashed: 0 libobjc.A.dylib 0x00000001bac3e160 objc_release + 16 (objc-runtime-new.h:1585) 1 libobjc.A.dylib 0x00000001bac3f81c AutoreleasePoolPage::releaseUntil(objc_object**) + 204 (NSObject.mm:944) 2 libobjc.A.dylib 0x00000001bac3f6e8 objc_autoreleasePoolPop + 212 (NSObject.mm:1211) 3 CoreFoundation 0x00000001a6b3eae4 _CFAutoreleasePoolPop + 32 (NSObject.m:798) 4 CoreFoundation 0x00000001a6aae480 __CFRunLoopPerCalloutARPEnd + 48 (CFRunLoop.c:762) 5 CoreFoundation 0x00000001a6aa93f8 __CFRunLoopRun + 2576 (CFRunLoop.c:3120) 6 CoreFoundation 0x00000001a6aa84bc CFRunLoopRunSpecific + 600 (CFRunLoop.c:3242) 7 Foundation 0x00000001a7d29e30 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 232 (NSRunLoop.m:374) 8 CrexendoMobile 0x0000000100bca5e4 -[MobilePortBinding performSynchronousOperation:] + 268 (MobileService.m:17547) 9 CrexendoMobile 0x0000000100bcadf4 -[MobilePortBinding deviceExistsUsingParameters:] + 116 (MobileService.m:17638) 10 CrexendoMobile 0x0000000100d7175c -[MobileServiceHelper deviceExists:error:] + 596 (MobileServiceHelper.m:612) 11 CrexendoMobile 0x0000000100b43c34 -[CrexendoMobileAppDelegate applicationDidBecomeActiveBackgroundTasks:] + 1244 (CrexendoMobileAppDelegate.m:872) 12 Foundation 0x00000001a7e9424c __NSThreadPerformPerform + 188 (NSThread.m:807) 13 CoreFoundation 0x00000001a6aaf81c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 (CFRunLoop.c:1967) 14 CoreFoundation 0x00000001a6aaf718 __CFRunLoopDoSource0 + 208 (CFRunLoop.c:2011) 15 CoreFoundation 0x00000001a6aaea94 __CFRunLoopDoSources0 + 376 (CFRunLoop.c:2056) 16 CoreFoundation 0x00000001a6aa8d20 __CFRunLoopRun + 824 (CFRunLoop.c:2925) 17 CoreFoundation 0x00000001a6aa84bc CFRunLoopRunSpecific + 600 (CFRunLoop.c:3242) 18 GraphicsServices 0x00000001bd5ba820 GSEventRunModal + 164 (GSEvent.c:2259) 19 UIKitCore 0x00000001a9455164 -[UIApplication _run] + 1072 (UIApplication.m:3270) 20 UIKitCore 0x00000001a945a840 UIApplicationMain + 168 (UIApplication.m:4739) 21 CrexendoMobile 0x0000000100bdb60c main + 1209868 (main.m:21) 22 libdyld.dylib 0x00000001a676fe40 start + 4
Posted Last updated
.
Post not yet marked as solved
24 Replies
13k Views
After the iOS 15 update, the following process causes the app to die. Go to the home screen while running the app Completely quit by removing the background state of the app Start by pressing the icon on the home screen As soon as the app is opened in the state it was in when the previous home screen was moved, there is a symptom that the app dies. There was no such symptom until iOS 14. Is this symptom a bug in iOS 15 ? Or is there a new option for background state of apps in iOS 15?
Posted Last updated
.