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

144 Posts
Sort by:
Post marked as solved
4 Replies
515 Views
On receive of silent push I was able to connect to server and post some data. However I want to know whether safari browser can be opened too? I tried adding code but nothing happened. Logically Apple introduced this feature so that users wont get disturbed and silently app can do what it needs, however I have a requirement to open a browser for specific silent push.Any suggestion would help me to take decision.Thanks,
Posted
by
Post not yet marked as solved
4 Replies
2.9k Views
Greetings.I have an app today that uses multipeer connectivity extensively. Currently, when the user switches away from the app, MPC disconnects the session(s) - this is by design apparently (per other feedback). I'd like to hear if anyone has experimented with iOS9 multitasking / multipeer and whether MPC sessions can stay alive?Thanks
Posted
by
Post not yet marked as solved
0 Replies
5.2k Views
Note Much of this content has been rolled into URL Loading System documentation, but I’m leaving this doc here for my own reference. URLSession background sessions are optimised for transferring a small number of large resources. Moreover, it’s best if the transfer is resumable. This design makes the best use of client device resources and the available network bandwidth. If your app runs a lot of tasks in a background session, you should rethink its design. Below you’ll find a number of options you might consider. Most of these options require server-side support. If your server does not have this support, and you can’t add it — perhaps you’re writing a client app for a server you don’t control — you won’t be able to implement these options directly. In that case consider creating your own server that sits between your app and the final server and implements the necessary smarts required to optimise your app’s network usage. If that’s not possible, a final option is to not use a background session but instead take advantage of the BackgroundTasks framework. See BackgroundTasks Framework, below. Basics The basic strategy here is to have the sender (the server for a download, your app for an upload) pack the data into some sort of archive, transfer that archive over the network, and then have the receiver unpack it. There are, however, a number of complications, as described in the subsequent sections. Archive Format The obvious choices for the archive format are zip and tar. macOS has lots of options for handling these formats but none of that support is present on iOS (r. 22151959). OTOH, it’s easy to find third-party libraries to fill in this gap. Incremental Transfers It’s common to have a corpus of data at one end of the connection that you need to replicate at the other. If the data is large, you don’t want to transfer the whole thing every time there’s an update. Consider using the following strategies to deal with this: Catalogue diff — In this approach the receiver first downloads a catalogue from the sender, then diffs its current state against that catalogue, then requests all the things that are missing. Alternatively, the receiver passes a catalogue of what it has to the sender, at which point the sender does the diff and returns the things that are missing. The critical part is that, once the diff has been done, all of the missing resources are transferred in a single archive. The biggest drawback here is resume. If the sender is working with lots of different receivers, each of which has their own unique needs, the sender must keep a lot of unique archives around so it can resume a failed transfer. This can be a serious headache. Versions — In this approach you manage changes to the data as separate versions. The receiver passes the version number it has to the sender, at which point the sender knows exactly what data the receiver needs. This approach requires a bit more structure but it does avoid the above-mentioned problem with resume. The sender only needs to maintain a limited number of version diffs. In fact, you can balance the number of diffs against your desire to reduce network usage: Maintaining a lot of diffs means that you only have to transfer exactly what the receiver needs, while maintaining fewer diffs makes for a simpler server at the cost of a less efficient use of the network. Download versus Upload The discussion so far has applied equally to both downloads and uploads. Historically, however, there was one key difference: URLSession did not support resumable uploads. IMPORTANT Starting with iOS 17, URLSession supports resumable uploads. See WWDC 2023 Session 10006 Build robust and resumable file transfers for the details. The rest of this section assumes that you don’t have access to that support, either because you’re working on an older system or because the server you’re uploading to doesn’t support this feature. When doing a non-resumable upload you have to balance the number of tasks you submit to the session against the negative effects of a transfer failing. For example, if you do a single large upload then it’s annoying if the transfer fails when it’s 99% complete. On the other hand, if you do lots of tiny uploads, you’re working against the URLSession background session design. It is possible to support resumable uploads with sufficient server-side support. For example, you could implement an algorithm like this: Run an initial request to allocate an upload ID. Start the upload with that upload ID. If it completes successfully, you’re done. If it fails, make a request with the upload ID to find out how much the server received. Start a new upload for the remaining data. Indeed, this is kinda how the built-in resumable upload support works. If you’re going to implement something like this, it’s best to implement that protocol. (r. 22323347) BackgroundTasks Framework If you’re unable to use an URLSession background session effectively, you do have an alternative, namely, combining a standard session with the BackgroundTasks framework, and specifically the BGProcessingTaskRequest. This allows you to request extended processing time from the system. Once you’ve been granted that time, use it to run your many small network requests in a standard session. The main drawback to this approach is latency: The system may not grant your request for many hours. Indeed, it’s common for these requests to run overnight, once the user has connected their device to a power source. Background Assets Framework If you’re using URLSession to download assets for your app or game, check out the Background Assets framework. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Revision History 2023-09-27 Added information about the new resumable upload support. Added the Background Assets Framework section. Made significant editorial changes. 2022-01-31 Fixed the formatting and tags. Added a link to the official docs. 2018-03-24 Added the BackgroundTasks Framework section. Other editorial changes. 2015-08-18 First written.
Posted
by
Post not yet marked as solved
8 Replies
8.7k Views
Hi guys, I got one issue about sending data with interval 1000 seconds to the server, while the app has been killed by user. I found the relevant document about app in background mode. https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html but I checked the document, it seems there is no way to use NSTimer inside the block of beginBackgroundTaskWithName... function. NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(AppDelegate.handleTimer), userInfo: nil, repeats: true) Question: How to consistently send data to server with interval time while app has been terminated? Thank you, e
Posted
by
Post not yet marked as solved
0 Replies
30k 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. One way to avoid this is to wrap the background task in an object; see the QRunInBackgroundAssertion post on this thread for an example. 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 2023-06-16 Added a link to my QRunInBackgroundAssertion post. 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
Post not yet marked as solved
4 Replies
3.9k Views
I am trying to implement silent push notification in my application where I need to update some data in the server when silent notification comes. I am using Pushkit and it uses VoIP certificate for silent push notification but the app has been rejectd by Apple saying that "I can't use VoIP" certificate. It seems that apple has rejected it as I don't have any VoIP call functionality in my app. In that case how can I implement silent push notification so that my app gets activated even if it is not runnning(not even in the background) and I can update the server?
Posted
by
Post not yet marked as solved
1 Replies
2.5k Views
When the screen is unlocked the AVSpeechSynthesizer.speak is working fine and in locked not working do { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, mode: .default, options: .defaultToSpeaker) try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation) } catch { print("audioSession properties weren't set because of an error.") } let utterance = AVSpeechUtterance(string: voiceOutdata) utterance.voice = AVSpeechSynthesisVoice(language: "en-US") let synth = AVSpeechSynthesizer() synth.speak(utterance) defer { disableAVSession() } Error Log in the locked state [AXTTSCommon] Failure starting audio queue alp![AXTTSCommon] _BeginSpeaking: couldn't begin playback
Posted
by
Post not yet marked as solved
7 Replies
2k Views
I setup a BGProcessingTask that do some work with the db and at the end sends an email. I've notice that, even if I set requiresExternalPower to false the task runs only when the device is connected to the power cable. I've tested setting the repeating time every 10 minutes. If the power cable is disconnected the task isn't launhed anuymore. After I attach the cable, waiting some minutes it restarts.
Posted
by
Post not yet marked as solved
2 Replies
1.2k Views
Hello everyone,I've been developing an Interval Training App for iOS using SWIFT using a Timer Object. Everything is working perfectly with the App except when it goes on the background. For example, if a user exist the app to go to another app (for example a music app) the Timer stops and everything stops on the App. Does anyone know how to deal with this situation? I've seen many apps similar to mine working perfectly when they go on the background (for example "IntervalTimer" ou "HIIT & Tabata").Thanks in advance.
Posted
by
Post not yet marked as solved
5 Replies
2.4k Views
We are seeing a strange behavior regarding BGProcessingTasks on recent iOS releases (tested on iOS 13.5.1, iOS 13.6, iOS 14 Beta 2). The background task starts executing, but after a short period of time (sometimes just 5 seconds) the app goes into suspended date. The completion task or expiration task of the BackgroundProcessingTask is never called. We are seeing this behavior in production as well as in simulation( using: _simulateLaunchForTaskWithIdentifier) On previous iOS 13 releases (can't exactly pinpoint the last version) it worked fine and the task got usually 5-10 minutes of background time and then ran either into the completion or expiration handler. The issue is also reproducible using the Apple Sample App "Refreshing and Maintaining Your App Using Background Tasks" available at https://developer.apple.com/documentation/backgroundtasks/refreshing_and_maintaining_your_app_using_background_tasks Simplest way to reproduce the issue: 1) Launch the sample app 2) Bring the app to the background 3) Pause the debugger and simulate with e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.example.apple-samplecode.ColorFeed.db_cleaning"] 4) Then continue the program execution. 5) The background task will start, but after some seconds the execution/log messages will stop and the app goes into suspended state. 6) To prove that its in suspended state: Switching the app into the foreground resumes execution and eventually completes the background task.
Posted
by
Post not yet marked as solved
12 Replies
4.6k Views
Hello! Can someone please confirm whether or not an app will trigger background fetch after it has been force-quit by the user? Currently my app works performs background fetches correctly when it has been backgrounded, but after force-quitting the app it stops fetching. Specifically I am referring to scheduled background fetches, not fetches initiated by notifications - although I am interested to know if that would be an alternative. I've tried searching online and there's a lot of confusing and contradictory information about this - including old Apple documentation that explicitly says it will not launch, however that documentation has since been removed. The new documentation does not explicitly mention the force-quit scenario. Can anyone please confirm? Thanks!
Post not yet marked as solved
1 Replies
638 Views
Hi. Didn't find the answer in the documentation. Are CloudKit procedures executables in background tasks ? I'm trying to do : "[privateDatabase fetchRecordWithID:myMasterRecordID completionHandler:^(CKRecord *myMasterRecord, NSError *error) { ... }]" but it returns a record only when the app is active. In background task, it does nothing and waits until app is active. Thanks for you answer. Best Claude
Posted
by
Post not yet marked as solved
2 Replies
3.2k Views
Team, is there anyway, if we can wakeup the app while it is in suspended mode. I am using BLE scanning to share/receive the TCN token and generate notifications, but while app in sleep/suspended mode it stops. is there anyway to trigger this scanning or wake up the app without any manual intervention. we are trying to achieve this with help of silent notifications. can you help to figure out how many silent notification we can trigger in an hour ?
Posted
by
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
Post marked as solved
5 Replies
1.8k 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 not yet marked as solved
26 Replies
24k 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
by
Post not yet marked as solved
20 Replies
6.2k Views
Hi, before installing iOS 15 our app received HKObserverQuery calls in background, which worked like a charm - the calls have reliably woken up our app in background, enabling it to process new HK data. In iOS 15 the new entitlement com.apple.developer.healthkit.background-delivery was added, being mandatory if HKObserverQuery calls should be delivered in background. Indeed, we added the entitlement to the Entitlements file and the Provisioning Profile of the app. After doing so, registering with enableBackgroundDelivery(for:frequency:withCompletion:) worked again without an error. While testing we observed that the app is not called at all. To debug, we captured system logs of an iPhone with iOS 15 - you can find them attached. syslog It can be seen that HK background delivery tries to fire, but dasd decides to not proceed because of the ApplicationPolicy. After some research we found this might be related to background modes capabilities. Thus we added "Background fetch" and "Background processing". Anyhow, this did not change the behavior. Again, this background delivery perfectly worked on iOS 14 - we did not change anything except adding the new background delivery entitlement (and the background processing entitlements in a second try). Are we missing any (new?) entitlements? Any other news in iOS 15 making further changes necessary? Is HKObserverQuery working for others in background mode? Thanks in advance for considering and best regards, Nils Notes on the logs: App was suspended at all times iPhone was unlocked from the beginning on iPhone was locked at 13:16
Posted
by
Post not yet marked as solved
3 Replies
2.2k Views
Our application allows people to back up their content (Photos / Videos) into the cloud. To have our backup working more efficiently while the application is in background, we have implemented background tasks. We schedule refresh and processing task (BGProcessingTask). Processing task is used for uploading content. We are looking into improving the number of triggers for processing tasks. There are one or two triggers in 24 hours but not as frequently as we expected. We did an exercise to compare google photo v/s our application: the time google gets to execute in background is 6 times more than personal cloud. What are the possible reason for this difference.  See some sample code below. We were lucky to have an appointment for a tech talk with @George V. from Apple and he suggested to use BGProcessingTask and set a flag to defer those tasks to run at a time where the device was less used. We do work with BGProcessingTask and are using the flags request.requiresNetworkConnectivity and request.requiresExternalPower. Where it's not clear for me is: would setting requiresExternalPower to true prevent our app to run in background while the device is not plugged? Any guidance would be appreciated :) Maybe @George, if you're available. Thanks import UIKit import BackgroundTasks @main class AppDelegate: UIResponder, UIApplicationDelegate {     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {         registerBgTasks()         //registerBatteryBgTasks()         return true     }     func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {     }     func registerBgTasks() {         BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.photos-upload",                                            using: nil) { (task) in             self.handleProcessingTask(task: task as! BGProcessingTask)         }     }     func registerBatteryBgTasks() {         BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.photos-upload-power",                                            using: nil) { (task) in             self.handlePowerProcessingTask(task: task as! BGProcessingTask)         }     }     func handlePowerProcessingTask(task: BGProcessingTask) {         let startTime = Date()         let taskId = task.identifier         if let url = URL(string: "https://imaging.nikon.com/lineup/dslr/df/sample.htm") {             let session = URLSession.shared             let networkTask = session.dataTask(with: url) { data, _, _ in             }             networkTask.resume()         }         task.expirationHandler = {             let endTime = Date()             let diffComponents = Calendar.current.dateComponents([.second], from: startTime, to: endTime)             let taskEntry = TaskEntry(taskId: taskId, taskLaunchedTime: DateUtility.readableDate(date: startTime),                                       taskExpirationTime: DateUtility.readableDate(date: endTime),                                       taskTotalTime: "\(diffComponents.second ?? 0)")             let fileName = "\(Date().timeIntervalSince1970)power.plist"             APIPreferencesLoaderPower.write(preferences: TaskArray(tasks: [taskEntry]), fileName: fileName)             task.setTaskCompleted(success: true)         }     }     func handleProcessingTask(task: BGProcessingTask) {         let startTime = Date()         let taskId = task.identifier         if let url = URL(string: "https://imaging.nikon.com/lineup/dslr/df/sample.htm") {             let session = URLSession.shared             let networkTask = session.dataTask(with: url) { data, _, _ in             }             networkTask.resume()         }         task.expirationHandler = {             let endTime = Date()             let diffComponents = Calendar.current.dateComponents([.second], from: startTime, to: endTime)             let taskEntry = TaskEntry(taskId: taskId, taskLaunchedTime: DateUtility.readableDate(date: startTime),                                       taskExpirationTime: DateUtility.readableDate(date: endTime),                                       taskTotalTime: "\(diffComponents.second ?? 0)")             let fileName = "\(Date().timeIntervalSince1970)normal.plist"             APIPreferencesLoader.write(preferences: TaskArray(tasks: [taskEntry]), fileName: fileName)             task.setTaskCompleted(success: true)         }     } } other class: func scheduleBgTask() {         let request = BGProcessingTaskRequest(identifier: "com.synchronoss.cloud.photos-upload")         request.requiresNetworkConnectivity = true         request.requiresExternalPower = false         do {             try BGTaskScheduler.shared.submit(request)         } catch {             print("error")         }     }     func schedulePowerBgTask() {         let request = BGProcessingTaskRequest(identifier: "com.synchronoss.cloud.photos-upload-power")         request.requiresNetworkConnectivity = true         request.requiresExternalPower = true         do {             try BGTaskScheduler.shared.submit(request)         } catch {             print("error")         }     }
Posted
by
Post not yet marked as solved
2 Replies
4.2k Views
I have this error: [AXRuntimeCommon] AX Lookup problem - errorCode:1100 error:Permission denied portName:'com.apple.iphone.axserver' PID:963 It is preceded by lots of this message, if it matters: [Assert] +[UIInputViewSetPlacementInvisible placementWithPlacement:]: Should not be called with an invisible placement I thought it was because I didn't include a key in Info.plist, but I put keys in there that I thought might be needed. I am using CloudKit sharing and silent push notifications for CloudKit subscriptions, and the Apple documentation says when I set the capabilities for background fetch and remote notifications, the keys would be put in Info.plist by Xcode. Does this have anything to do with the fact that when my app is run for the first time it asks the user for permission to send notifications. If it's a silent notification that I'm using, I thought the documentation meant the user is not notified at all? I have searched on the internet and on stack overflow and in Apple developer forums for a solution. Any help will be appreciated.
Posted
by