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
2 Replies
775 Views
Is it possible for an app using NSPersistentCloudKitContainer to enable sync in the background, if so, how? Install app on your iPhone and iPad, create some data, it automatically syncs to both and life is good Close the iPad app Modify the data on iPhone Desired behavior: The backgrounded iPad app should sync (even if it takes a while) and be informed that its local database has finished syncing or similarly that changes were made. The use case is I want to reload my widget when data changes so it's up-to-date, so I need my app to sync it in the background, then notify when it's complete to be able to trigger the widget reload. I am concerned it will be a poor widget experience if it's always showing stale data until they manually open the app to initiate sync - kind of defeats the purpose of widgets. ha According to this post, they found sync is never run in the background. Is this not the case, or has it changed in iOS 15? Thanks!
Posted
by
Post not yet marked as solved
1 Replies
874 Views
I'm creating a pure SwiftUI app. I wish to use a background task to keep my data up-to-date while in the background. I've found the BGTaskScheduler documentation (https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler). In the section titled Register, Schedule, and Run Tasks, the document states: During app startup, you register a launch handler, a small block of code that runs the task, and an associated unique identifier for each task. Register all of the tasks before the end of the app launch sequence. For more information, see About the App Launch Sequence. I know you can do this in application(_ :, didFinishLaunchingWithOptions:) method of the AppDelegate. However, in a pure SwiftUI app there is no AppDelegate. So, how do I register my background task in SwiftUI? If I can't, then how do a retrofit an AppDelegate into an already existing SwiftUI app? Thanks, Alan
Posted
by
Post not yet marked as solved
0 Replies
2.0k 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 app while it’s in the background? 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 Store 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 periodic background execution time to refresh your UI, use BGAppRefreshTaskRequest. To request extended background execution time, 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. 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 BackgroundTasks. 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: 22 Jul 2021 — First posted. 26 Jul 2021 — Extended the statement about what’s not possible to include “running code periodically at a guaranteed interval”. 12 Aug 2021 — Added more entries to the common questions list, this time related to networking and IPC. Made minor editorial changes.
Posted
by
Post not yet marked as solved
0 Replies
464 Views
I am working on an iOS app that uses push notifications to wake up the app so I can receive SIP calls when app is not in foreground. When all is working, app gets a VOIP push notification while in background which wakes up the app and within 5 seconds I get a SIP invite to process the call. We are using a timer for 5 seconds to wait for SIP after getting VOIP push. The issue I am having is after a certain period of running sip calls test, app stopped receiving SIP invites if it is in background. This happened on our multiple test devices. Restarting the app and rebooting the device didn’t help but uninstalling & installing the same version of app did the trick. What could be the reasons behind this and how can we fix this? Have anyone else experienced the similar thing? Any suggestions . TIA.
Posted
by
Post marked as solved
1 Replies
316 Views
Hello, tldr; relaunch for background uploads isn't working as expected. I'm testing my code on iPad OS 14.6 and XCode 12.5.1. Background app refresh is ON on my device for my app. A background file upload is being setup with URLSession. The URL session is created as soon as the app starts up and not lazily created. See URL session configuration below. I have followed the test instructions as outlined here: https://developer.apple.com/forums/thread/14855, specifically launching my app not via Xcode but from the home screen and adding an exit() call after the app enters the background in the AppDelegate callback method applicationDidEnterBackground. The file transfer is initiated before the app enters the background. Here's the configuration code I'm using: let configuration = URLSessionConfiguration.background(withIdentifier: <unique_identifier>)     configuration.sessionSendsLaunchEvents = true     configuration.sharedContainerIdentifier = <container group identifier>     configuration.isDiscretionary = false     configuration.timeoutIntervalForResource = 3600 * 24 * 2 // wait for 2 days before timing out connections                urlSession = URLSession(configuration: configuration, delegate:self, delegateQueue: nil) The file in fact finishes uploading but the app isn't relaunched as one would expect. As soon as I re-open the app from the home screen, I get the requisite callbacks about the upload having completed properly. In the past when I have tested my code, the method AppDelegate:handleEventsForBackgroundURLSession used to be called after the upload finishes. That appears to no longer be the case. Any guidance/help will be hugely appreciated! Thanks Krishna
Posted
by
Post marked as solved
1 Replies
563 Views
I'm trying to upload an existing zip file to a server, but the file itself doesn't seem to be present in the request when I check what the server actually receives. Here's my current implementation: func uploadZip(filePath: URL, authorization: String, callback: @escaping ((Bool) -> Void)) { BGUploadManager.callback = callback let url = URL(string: "\(APINetwork.BASE_URL)")! var request = URLRequest(url: url) request.headers = ["Authorization": "Bearer " + authorization] request.method = HTTPMethod(rawValue: "POST") request.setValue("application/zip", forHTTPHeaderField: "Content-Type") let config = URLSessionConfiguration.background(withIdentifier: "identifier") config.isDiscretionary = false let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main) let task = session.uploadTask(with: request, fromFile: filePath) task.resume() } There are implemented handlers for completion and progress and they work properly. The problem is really just the actual file not being sent (or if it is I don't know how to get it). Here's parts of what the server receives: headers: { host: 'localhost:1337', 'content-type': 'application/zip', 'accept-encoding': 'gzip, deflate', connection: 'keep-alive', accept: '*/*', 'user-agent': 'App/37 CFNetwork/1237 Darwin/20.4.0', authorization: 'Bearer sometokenhere', 'content-length': '89634' } body: {} Checking for request.files also shows that it's empty. The Content-Length value is correct. The filePath is the full path and does actually point to the zip file.
Posted
by
Post not yet marked as solved
4 Replies
418 Views
I have some business requirements to send data to a particular cloud location while the app is not running (not even in the background). I am looking for Apple support on whether there are any services in iOS SDK which allow me to do the same. This service should continue to upload data until it detects that there is no more data left to be uploaded.
Posted
by
Post marked as solved
4 Replies
661 Views
I have a working background URLSession. I know that upon creating an URLSession with the same session identifier I get a "background URLSession with identifier x already exists" message. I know that I can store the session and call .finishTasksAndInvalidate() on it if needed. My use case is that if the application terminates, and the user relaunches the application before the background task completes, I need to be able to check if a background URLSession with the same identifier exists, and if it does, restitute the application state with the same handlers (so that I can update a UIProgressView for example). I have two questions: How do I check that a background URLSession with a given identifier already exists? Does the AppDelegate completion handler still get called if the application was terminated and relaunched?
Posted
by
Post marked as solved
1 Replies
427 Views
I've just finished making a meditation app for iphone using swiftui which includes a timer. The only problem is the timer stops when the app is in the background or the phone is locked. The user can select between 2 and 60 minutes on the timer and play, pause, reset the timer. When seconds remaining equals zero the timer ends and a meditation bell sound plays to signal the end of the meditation. Currently I use the default timer on the iphone when I meditate in the Clock app. If I set this timer for 20 minutes and lock the phone, at the end of the 20 minutes the timer will go off and notify me with whatever sound I selected in "When Timer Ends". If the default Clock app on the iphone has this basic functionality, why is it so hard to have the same functionality in the meditation app I'm making? Wouldn't the safest/easiest way to have the timer run in the background or when the phone is locked be the same method the default Clock app uses? While meditating, we don't want to have our phone giving off light by having to be unlocked so the timer can continue running. We want to be able to lock the phone so it's not giving off light and be reminded when the time ends or if we unlock the phone to check how much time is remaining. Any thoughts would be appreciated. Have checked stackoverflow and other places but the fixes and work around methods don't directly apply to the use case.
Posted
by
Post not yet marked as solved
11 Replies
1.1k Views
Hi All, I have coded a TCP Server packaged inside C++ static library. I am using this static library within the iOS Swift UI application. I have coded a simple UI which has a button, on click of which I want to start the TCP server (which is written in C++ and inside the linked static library). After the TCP server is started, I want to push the application to background and then run the client application which is going to interact with this TCP server from the backgrounded SwiftUI application. I want the TCP server to be running even the application goes to the background mode as I have another user interface application which is going to interact with the TCP server on the same device. I tried using background task, but I don't know whether I am doing something wrong there, or I cannot achieve what I want using the BackgroundTask functionality available in iOS. The main thing here is, the TCP server code is in C++ inside static library and I want to start the TCP server from SwiftUI application layer. I have managed to call C++ function from Swift that part is available. Can anyone show me the right path here ? How do I keep the BSD Socket based TCP Server active while the application is in Background mode ?
Posted
by
Post not yet marked as solved
0 Replies
357 Views
I have implemented local database and based on some logics I need to scheduled background task and app refresh on every 4 hours. And on app refresh need to generate local notification to show some reminder information. I created POC and tested with apple xcode command and it generating notification e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"MyTaskIdentifier"] but on actual testing I am not getting local notification. Please let me know if any thing missed or is there any limitation with background schedule job?. (I read the background task scheduler has some complex algorithm to schedule it and system OS decide it to generate, but for me its was not generate single time) https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler Any help on this ? Thanks
Posted
by
Post not yet marked as solved
0 Replies
363 Views
Before asking, I referenced this thread (https://developer.apple.com/forums/thread/652592) While the Android devices can function fully as both Central and Peripheral while an app is in both foreground and background execution modes, iOS apps are bound by restrictions that iOS has on background Bluetooth functionality. When in the background, iOS apps advertise in a proprietary advertisement format that is not part of the Bluetooth standard and thus not readable by non-iOS devices, hence it is unable to scan for other devices in any meaningful way. Any work around to this problem?
Posted
by
Post marked as solved
1 Replies
328 Views
Hello! I have an beacon (this. device doesn't support pair) that should work as SOS button, but required option is that the device should work for a long time in background. Sequence algorithm: BLE device send trigger to nearest device iPhone should receive this trigger (in background) then do network request I can't find right solution cz the BGTask has 30 sec limit
Posted
by
Post marked as solved
2 Replies
336 Views
I’m having trouble wrapping my head around the how I might build a fantasy sports app that I have in mind.  I can get real-time sports data from an API, so users’ teams can have scores, based on the players they pick and how those players perform. That's easy. I’m having trouble in the following 2 areas… How would I display a leaderboard? I want all users’ scores to be displayed on a leaderboard. It seems like CloudKit can do this. Is that the best solution or is there a better option? (I really don’t want to use Game Center). Here’s the second thing I’m struggling with. I’ve worked with background tasks, but I don’t think those would work because I want the real-time sports updates to be pushed to each user. If I use background tasks, the users’ scores and the leaderboard won’t be updated if the device is in low battery mode or off. With this in mind, should I be pulling data from the API to a server, and then pushing notifications to users? If so, this project gets suuuper complicated, and I need to learn something like Vapor and working with a database. I might be in over my head here. Hopefully, I can get some tips/guidance!
Posted
by
Post not yet marked as solved
0 Replies
263 Views
Like WhatsApp, i want to insert my incoming message in local database when notification arrives in all states like terminated state also without click on notification. My FCM payload is { "message": { "token": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "apns": { "headers": { "apns-priority": "10" }, "payload": { "aps": { "alert": { "title": "From Name", "subtitle": "Group Name", "body": "Message Text" }, "sound" : "default", "mutable-content" : 1 } } } } } i am able to receive notification in terminated state also, but i want to invoke my app's code when notification receives like whatsapp. i am using flutter, fcm.
Posted
by
Post not yet marked as solved
1 Replies
368 Views
I want to call api to update user location everytime(after every 1 min) when app is in background. I have enabled everything that is required for this but after 10-15 mins system kills my app. Is any solution to achieve this?
Posted
by
Post not yet marked as solved
0 Replies
897 Views
Application process being killed by iOS internal, when the application was background for more than 30 secs and application is consuming Bluetooth External Asseceries frameworks (data transmission or just Bluetooth connected, no data transmission) or periodic network upload is progress in background Not observed this issue in till iOS 15 beta 6. Observed in iOS 15 Beta 7 and 8 am I missing any new configuration to run the application in background other than External BLE Accessaries and Uses Bluetooth LE Accessories in Background ?
Posted
by