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
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
.
Post not yet marked as solved
1 Replies
815 Views
I’m working on an independent watchOS app which is primarily designed to to collect and periodically send location updates to a server. The UI features a toggle that allows the user to turn this capability on or off at their discretion. The typical use case scenario would be for the user to turn the toggle on in the morning, put the app in the background and then go about their day. Given the limitations and restrictions regarding background execution on watchOS, in an ideal situation, I would be able to upload the stored location updates about every 15-20 minutes. With an active complication on the watch face, it’s my understanding that this should be possible. I’ve implemented background app refresh and indeed, I do see this reliably being triggered every 15-20 minutes or so. In my handle(_:) method, I process the WKApplicationRefreshBackgroundTask like this: func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { backgroundTasks.forEach { task in switch task { case let appRefreshBackgroundTask as WKApplicationRefreshBackgroundTask: // start background URL session to upload data; watchOS will perform the request in a separate process so that it will continue to run even if our app gets // terminated; when the system is done transferring data, it will call this method again and backgroundTasks will contain an instance of // WKURLSessionRefreshBackgroundTask which will be processed below startBackgroundURLSessionUploadTask() scheduleNextBackgroundAppRefresh() appRefreshBackgroundTask.setTaskCompletedWithSnapshot(false) case let urlSessionTask as WKURLSessionRefreshBackgroundTask: // add urlSessionTask to the pendingURLSessionRefreshBackgroundTasks array so we keep a reference to it; when the system completes the upload and // informs us via a URL session delegate method callback, then we will retrieve urlSessionTask from the pendingURLSessionRefreshBackgroundTasks array // and call .setTaskCompletedWithSnapshot(_:) on it pendingURLSessionRefreshBackgroundTasks.append(urlSessionTask) // create another background URL session using the background task’s sessionIdentifier and specify our extension as the session’s delegate; using the same // identifier to create a second URL session allows the system to connect the session to the upload that it performed for us in another process let configuration = URLSessionConfiguration.background(withIdentifier: urlSessionTask.sessionIdentifier) let _ = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) default: task.setTaskCompletedWithSnapshot(false) } } } And here is how I'm creating and starting the background URL session upload task: func startBackgroundURLSessionUploadTask() { // 1. check to see that we have locations to report; otherwise, just return // 2. serialize the locations into a temporary file // 3. create the background upload task let configuration = URLSessionConfiguration.background(withIdentifier: Constants.backgroundUploadIdentifier) configuration.isDiscretionary = false configuration.sessionSendsLaunchEvents = true let backgroundUrlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) let request: URLRequest = createURLRequest() // this is a POST request let backgroundUrlSessionUploadTask = backgroundUrlSession.uploadTask(with: request, fromFile: tempFileUrl) backgroundUrlSessionUploadTask.countOfBytesClientExpectsToSend = Int64(serializedData.count) // on average, this is ~1.5 KB backgroundUrlSessionUploadTask.countOfBytesClientExpectsToReceive = Int64(50) // approximate size of server response backgroundUrlSessionUploadTask.resume() } Note that I'm not setting the .earliestBeginDate property on the backgroundUrlSessionUploadTask because I'd like the upload to start as soon as possible without any delay. Also, this same class (my WatchKit application delegate) conforms to URLSessionTaskDelegate and I have implemented urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:) and urlSession(_:task:didCompleteWithError:). In my testing (on an actual Apple Watch Ultra running watchOS 9.3.1), I've observed that when the system performs the background app refresh, I always receive a callback to myhandle(_:) method. But when I start the background URL session upload task (in startBackgroundURLSessionUploadTask()), I was expecting that when the upload completes, I'd receive another call to myhandle(_:) method with an instance of WKURLSessionRefreshBackgroundTask but this doesn't seem to happen consistently. Sometimes I do see it but other times, I don't and when I don't, the data doesn't seem to be getting uploaded. On a side note, most of the time, startBackgroundURLSessionUploadTask() gets called as a result of my code handling a background app refresh task. But when the user turns off the toggle in the UI and I stop the location updates, I need to report any stored locations at that time and so I call startBackgroundURLSessionUploadTask() to do that. In that specific case, the upload seems to work 100% of the time but I definitely don't see a callback to my handle(_:) method when this occurs. Am I wrong in expecting that I should always be getting a callback to handle(_:) when a background URL session upload task completes? If so, under what circumstances should this occur? Thanks very much!
Posted
by bmt22033.
Last updated
.
Post not yet marked as solved
1 Replies
834 Views
Hello, Our team is working on a mobile app that uses Nearby Interaction framework (UWB technology) to get real-time high-accuracy ranging information with our third-party UWB-enabled device. So far everything works fine, background sessions included as explained in wwdc2022/10008 video. We are using Bluetooth LE to exchange the UWB parameters as recommended by Apple. Our next goal is to go for a full hands-free configuration of the UWB session. Let's think of an access control use case where UWB is used to measure the distance between the user and the door (credentials exchanged via Bluetooth). What we want to achieve is to start the UWB session without requiring the user to take the phone out of his wallet and open the access control app. What it works for us today is if the user starts the app, then switches off the screen and puts the phone into his pocket. The app is still running in background, so the Bluetooth Scan keeps working, the Bluetooth session starts, the UWB parameters exchanged and the UWB session started in the background, all good. But what if the user killed the app or never started it after reboot? How can we force the app to start from killed state when the BLE / UWB third-party accessory comes into proximity? iBeacon seems like a promising approach, but according to the forums, in iOS 16 the app will not be restarted from killed state. Is this correct? Any idea / suggestion about how to let the OS start our app when the user approaches the BLE / UWB accessory and the app is in killed state? Thanks in advance for your time. Regards.
Posted
by gorka-mk.
Last updated
.
Post not yet marked as solved
1 Replies
382 Views
I'm working on a screen where the goal is for the user to walk for 6 minutes while the app times them and measures the distance walked. I'm using CMPedometer to track the walking distance and a repeating 1-second Timer to count down the time. This works fine as long as the app is in the foreground, but I'd like my user to be able to lock their phone and put it away while they walk. I used UIApplication.shared.beginBackgroundTask, but it doesn't provide enough time. It usually only gives me around 30 seconds. I also tried calling UIApplication.shared.beginBackgroundTask again or calling it once every time the timer ticks, with no better result. How can I accomplish my goal here?
Posted
by flarosa.
Last updated
.
Post not yet marked as solved
2 Replies
371 Views
We are developing a SwiftUI iOS app which behaves as a client to a MJPEG server on a local network. This means that our app should read images sent from a special hardware we are developing using HTTP protocol. The testing is working fine, but our concern is that when the app goes to the background or the phone is locked, the HTTP connection gets closed after one minute. However, we need to have this HTTP connection alive all the time because we are developing a safety monitoring app that should continue its monitoring state even when the phone is locked. We are constantly running object detection AI algorithm on the transferred images from the hardware. Is there a solution to our concern. Could we have example code to a solution?
Posted
by FaridHage.
Last updated
.
Post not yet marked as solved
1 Replies
363 Views
Is there a possibility to develop an iOS app that is connected to an external camera connected through lightning or USB-C port and receives video stream. We need to be able to get this video stream even while the app is in the background or if the phone is locked. We could have the camera connected wirelessly through the lightning port. Is there an available library or a sample app featuring such functionalities. Thanks.
Posted
by FaridHage.
Last updated
.
Post not yet marked as solved
7 Replies
426 Views
I have an app which uses Cocoa Pods to use MQTTClient in connecting to io.adafruit. I use the app to get the various data point stored at io.adafruit and to even send data to adafruit to control a connected unit. I am using .xcworkspace to upload the app on my phone and everything works fine. I am hoping to wake my app every so ofter to get some data points from io.adafruit and if certain conditions exist, I want to send a notification to the user. I have added Background Modes to my app's Signing & Capabilities (Background fetch) and in my INFO I have Permitted background task scheduler identifiers with the String identifier LEVELIT.Refresh. The following is my code I am using in my AppDelegate.h #import <UIKit/UIKit.h> #import <CoreData/CoreData.h> #import <MQTTClient/MQTTClient.h> #import <UserNotifications/UserNotifications.h> @interface AppDelegate: UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate,UIAlertViewDelegate,MQTTSessionDelegate>{ MQTTSession *session3; } @property (nonatomic, retain) MQTTSession *session3; @property (nonatomic, strong) NSPersistentContainer *persistentContainer; @end And this is the code I use in my AppDelegate.m #import "AppDelegate.h" #import <BackgroundTasks/BackgroundTasks.h> #import <CloudKit/CloudKit.h> #import <UserNotifications/UserNotifications.h> static NSString* TaskID = @"LEVELIT.refresh"; @interface AppDelegate() @property (nonatomic, retain) NSString *myUserName; @property (nonatomic, retain) NSString *myUserKey; @property (nonatomic, retain) NSString *myTrips; @property (nonatomic, retain) NSString *atrip; @property (nonatomic, retain) NSString *trip; @property (nonatomic, retain) NSString *gettrip; @property(strong) void (^expirationHandler)(void); @end @implementation AppDelegate @synthesize session3,window; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if (@available(iOS 13.0, *)) { [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:TaskID usingQueue:nil launchHandler:^(BGAppRefreshTask *task) { [self handleAppRefreshTask:task]; }]; } else { // Fallback on earlier versions } UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { }]; UNNotificationCategory* generalCategory = [UNNotificationCategory categoryWithIdentifier:@"GENERAL" actions:@[] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]; NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults]; if([[[defaults2 dictionaryRepresentation] allKeys] containsObject:@"myUserNameFile"]){ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; self.myUserName = [defaults objectForKey:@"myUserNameFile"]; NSLog(@"myUserName1:%@",self.myUserName); self.myUserKey = [defaults objectForKey:@"myUserKeyFile"]; NSLog(@"myUserKey1:%@",self.myUserKey); } return YES; } } -(void)schedualLocalNotifications{ } - (void)setTaskCompletedWithSuccess:(BOOL)success;{ NSLog(@"Completed"); } - (void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"Entering background"); if (@available(iOS 13.0, *)) { BGAppRefreshTaskRequest *request = [[BGAppRefreshTaskRequest alloc] initWithIdentifier:TaskID]; request.earliestBeginDate = [NSDate dateWithTimeIntervalSinceNow:15*60]; NSError *error; BOOL success = [[BGTaskScheduler sharedScheduler] submitTaskRequest:request error:&error]; if (success == TRUE) { } } //BREAKPOINT } -(void)handleAppRefreshTask:(BGAppRefreshTask *)task API_AVAILABLE(ios(13.0)){ //do things with task NSLog(@"Process started!"); task.expirationHandler = ^{ NSLog(@"WARNING: expired before finish was executed."); }; MQTTCFSocketTransport *transport = [[MQTTCFSocketTransport alloc] init]; transport.host = @"io.adafruit.com"; transport.port = 1883; self.session3 = [[MQTTSession alloc] init]; self.session3.userName = self.myUserName; self.session3.password = self.myUserKey; self.session3.transport = transport; self.session3.delegate = self; self.session3.keepAliveInterval = 30; // new stuff NSString *feeds = [self.myUserName stringByAppendingString:@"/feeds/"]; self.atrip = [feeds stringByAppendingString:@"trip"]; self.gettrip = [self.atrip stringByAppendingString:@"/get"]; [session3 connectWithConnectHandler:^(NSError *error) { if(!error){ [self.session3 subscribeToTopic:self.atrip atLevel:1 subscribeHandler:^(NSError *error, NSArray *gQoss){ if (error) { NSLog(@"Subscription failed %@", error.localizedDescription); } else { NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss); NSData* data = [@"0" dataUsingEncoding:NSUTF8StringEncoding]; [self.session3 publishData:data onTopic:self.gettrip retain:NO qos:0 publishHandler:nil]; } }]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(45* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [task setTaskCompletedWithSuccess:YES]; }); self.session3.keepAliveInterval =30; } else {NSLog(@"[connectWithConnectHandler]Error Connect %@", error.localizedDescription);} }]; task.expirationHandler = ^{ NSLog(@"WARNING: expired before finish was executed."); }; } } } //More code here but too much. @end I am not sure about the local notification because the BGAppRefreshTask is not working. I have placed a breakpoint just after the app enters background and the TASK is submitted. Then I type in e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"LEVELIT.refresh"] The app launches in the background but I get an error error: Header search couldn't locate module MQTTClient error: couldn't install checkers, unknown error Message from debugger: Terminated due to signal 9 When I tried running the app without .xcworkspace the project said it couldn't find MQTTClient. But with the workspace everything works fine. Why would launching the app in the background cause the app not to locate the MQTTClient libraries? And how do I work around this problem? Any and all help would be appreciated.
Posted
by gbenna.
Last updated
.
Post not yet marked as solved
2 Replies
573 Views
Currently working on an emergency app paired with a BLE device, and the desired use case is: When the device is triggered, it sends your location to your emergency contacts an API we've built. This flow works while the app is open, but we need things to obviously work while in background (while the phone is sleeping as well, of course, for emergency contexts) From what I've researched and understood, background fetches don't really work, because the intervals are a maximum of about 15 minutes, and iOS will make them less frequent based on app usage, and that window in an emergency situation isn't good enough. Having read around, I've bumped into a couple resources that suggest background bluetooth processing is possible, if I listen for a particular service being advertised, but I haven't been able to make things work so far. I wanted some help on this.
Posted
by JoaoNM.
Last updated
.
Post not yet marked as solved
1 Replies
441 Views
I have an app to communicate with a peripheral via L2CAP channel. Even I already enabled "Uses Bluetooth LE accessories" in "Background Mode", it still stop working when I lock the screen. Did some search and found these two posts: CBL2CAPChannel not responsive while app is backgrounded iOS Swift CoreBluetooth CBL2CAPChannel L2CAP Channel Oriented Connection Cannot Reconnect After Close From Central I am wondering if there are any solutions or work around about this. Based on the use case, I prefer to use L2CAP to transfer large data between two devices, so won't consider GATT.
Posted
by stonezhl.
Last updated
.
Post not yet marked as solved
0 Replies
507 Views
Hi, I'm relatively new to iOS development and kindly ask for some feedback on a strategy to achieve this desired behavior in my app. My Question: What would be the best strategy for sound effect playback when an app is in the background with precise timing? Is this even possible? Context: I created a basic countdown timer app (targeting iOS 17 with Swift/SwiftUI.). Countdown sessions can last up to 30-60 mins. When the timer is started it progresses through a series of sub-intervals and plays a short sound for each one. I used AVAudioPlayer and everything works fine when the app is in the foreground. I'm considering switching to AVAudioEngine b/c precise timing is very important and the AIs tell me this would have better precision. I'm already setting "App plays audio or streams audio/video using AirPlay" in my Plist, and have configured: AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers) Curiously, when testing on my iPhone 13 mini, sounds sometimes still play when the app is in the background, but not always. What I've considered: Background Tasks: Would they make any sense for this use-case? Seems like not if the allowed time is short &amp; limited by the system. Pre-scheduling all Sounds: Not sure this would even work and seems like a lot of memory would be needed (could be hundreds of intervals). ActivityKit Alerts: works but with a ~50ms delay which is too long for my purposes. Pre-Render all SFX to 1 large audio file: Seems like a lot of work and processing time and probably not worth it. I hope there's a better solution. I'd really appreciate any feedback.
Posted
by hekuli.
Last updated
.
Post not yet marked as solved
0 Replies
340 Views
I'm trying to execute a background task following the Developer Documentation. This is my code import SwiftUI @main struct MyAppTest_Watch_AppApp: App { @Environment(\.scenePhase) var scenePhase let bs = BackgroundSession() @SceneBuilder var body: some Scene { WindowGroup { ContentView() }.backgroundTask(.appRefresh("prova")) { context in print("bg task") await scheduleTask() } .onChange(of: scenePhase) { phase in switch phase { case .active: print("\(#function) REPORTS - App change of scenePhase to ACTIVE") case .inactive: print("\(#function) REPORTS - App change of scenePhase Inactive") case .background: print("\(#function) REPORTS - App change of scenePhase Background") WKApplication.shared() .scheduleBackgroundRefresh( withPreferredDate: Date.init(timeIntervalSinceNow: 5 * 60.0), userInfo: "prova" as NSSecureCoding & NSObjectProtocol, scheduledCompletion: schedule) default: print("\(#function) REPORTS - App change of scenePhase Default") } } } func scheduleTask() async { bs.testSession() await WKApplication.shared() .scheduleBackgroundRefresh( withPreferredDate: Date.init(timeIntervalSinceNow: 5 * 60.0), userInfo: "prova" as NSSecureCoding & NSObjectProtocol, scheduledCompletion: schedule) } func schedule(error: Error?) { if error != nil { // Handle the scheduling error. fatalError("*** An error occurred while scheduling the background refresh task. ***") } print("Scheduled!") } } On the simulator the background refresh occurs correctly according to the preferred date and executes the background task, on the real watch it does not. I also set the app as complication in my watch face. The device I'm testing the app on is an Apple Watch Serie 7 with watchOS 10.3. Any idea?
Posted Last updated
.
Post not yet marked as solved
1 Replies
468 Views
Detecting New WiFi Connection + WiFi Details What I want to accomplish: The app, including when backgrounded or suspended, creates a local notification (assuming the app has permission for notifications) when there is a new WiFi network being used and ideally being able to execute some small code to customize the notification. This code would also have access to SSID info, security type, etc., so the sort of info in NEHotspotNetwork. A number of apps seem able to do this but I am having trouble replicating what they are doing. What I’ve looked at or tried: Looking at “TN3111: iOS Wi-Fi API overview” https://developer.apple.com/documentation/technotes/tn3111-ios-wifi-api-overview Navigate an internet hotspot (NEHotspotHelper) Doesn’t look like NEHotspotHelper would provide the above functionality for detecting changes while backgrounded and it seems to indicate that the special entitlement com.apple.developer.networking.HotspotHelper would not be granted for this use case anyway. Add an accessory to the user’s network (Wireless Accessory Configuration (WAC) or HomeKit) Doesn’t seem relevant to my use case Peer-to-peer networking Doesn’t seem relevant to my use case Location tracking I don’t want to know my user’s location and Lookout and Norton 360 (just two of many examples) don’t request or have location permissions (or request any permissions for that matter except notifications) and are still able to obtain the WiFi network info without it as well as detect changes in the background. Current Wi-Fi network NEHotspotNetwork .fetchCurrent(completionHandler:) So this is the most obvious since it returns the info I want but it requires the following permissions or configurations that neither Lookout or Norton 360 are requesting and also I don’t see how this API would trigger a backgrounded app to run, more for when your app is in the foreground and able to run already. From Apple docs: “This method produces a non-nil NEHotspotNetwork object only when the current network environment meets all four of the following critieria: The app is using the Core Location API and has user’s authorization to access precise location. The app used the NEHotspotConfiguration API to configure the current Wi-Fi network. The app has active VPN configurations installed. The app has an active NEDNSSettingsManager configuration installed. This method also requires the app to have the Access Wi-Fi Information Entitlement, and produces nil if the app lacks this entitlement.” Once again, apps that are able to do what I want don't seem to have location permissions, no VPN profile, no DNS config, no hotspot config.... Additional things I’ve considered that are not mentioned in the above: Using NWPathMonitor works for identifying a change, doesn’t trigger when app backgrounded and no access to SSID or other WiFi info. What am I missing? Is there some API that I totally missed? Thank you! Colin
Posted Last updated
.
Post not yet marked as solved
1 Replies
385 Views
What is the safest method for verify/register background tasks in an appliction? Apple docs state that trying to register a background task that’s already scheduled will crash the app. That is confirmed. Im looking to understand the best method for checking to see if a process is already registered to prevent the crash. Any help is appreciated.
Posted Last updated
.
Post marked as solved
1 Replies
352 Views
How do you wake up an app without using push notification? I am developing a medical app which is isolated from the internet for cybersecurity/HIPAA reasons. When the iPhone is locked, I would like the app to launch, or return to the foreground, when the server notifies it that an event occurred. Is there a way implement this using Swift?
Posted
by NkMA.
Last updated
.
Post not yet marked as solved
1 Replies
365 Views
I want to start a shell script during the boot of a MacOS (14.2.1) machine. But the scripts is executed only when I log in, not directly after the system has started. I wrote a plist definition like this: > ls -l /Library/LaunchDaemons/com.foobar.justLog.plist -rw-r--r--@ 1 root wheel 397 Jan 25 21:06 /Library/LaunchDaemons/com.foobar.justLog.plist > cat /Library/LaunchDaemons/com.foobar.justLog.plist <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.foobar.justLog</string> <key>RunAtLoad</key> <true/> <key>Program</key> <string>/usr/local/bin/justLog.sh</string> </dict> </plist> > The referenced shell script looks like this: > ls -l /usr/local/bin/justLog.sh -rwxr-xr-x@ 1 root wheel 105 Jan 25 14:46 /usr/local/bin/justLog.sh > cat /usr/local/bin/justLog.sh #!/bin/bash while true ;do echo "Started script $0 as user $(whoami) in $PWD ($(date))" sleep 120 done > Then I shutdown the mac and restarted it at 21:46:40. I waited until 21:48:00 before I logged on with my default user. I was expecting my script to be run after the machine startet. But when I check the files in /var/log/com.apple.xpc.launchd I see that there are no entries from launchd during the initial boot. It looks like launchd does nothing before the first user logs in. That's not the behaviour I would expect from a script to be run when the system boots. > for i in 5 6 7 8 ;do echo "inspecting minute: 21:4$i"; grep "2024-01-25 21:4${i}:" /var/log/com.apple.xpc.launchd/launchd.log{.2,.1,} /var/log/* 2>/dev/null | wc -l ;done inspecting minute: 21:45 11747 inspecting minute: 21:46 0 inspecting minute: 21:47 0 inspecting minute: 21:48 21150 > Can anyone explain why my script is not executed before I log in?
Posted Last updated
.
Post not yet marked as solved
1 Replies
306 Views
Hello, I am currently working on an iOS application that relies on WebSocket connections for real-time data updates. As part of our application's functionality, we need to ensure that WebSocket connections continue to operate seamlessly when the iOS app is in the background or when the device is locked by the user. I am seeking clarification on the following points: WebSocket Connection in Background: Will WebSocket connections remain active and functional when the iOS app is in the background? If not, what are the recommended best practices or guidelines for maintaining WebSocket connections during background execution? WebSocket Connection when Device is Locked: How does WebSocket behave when the iOS device is locked by the user? Are there any specific considerations or configurations that need to be addressed to ensure the WebSocket connection persists when the device is locked? Alternate Solutions for Background Data Collection: If WebSocket connections are not intended to work in the background, are there alternative approaches or APIs that can be employed to collect real-time data while the app is in the background? Specifically, is there a recommended method to collect data from a WebSocket connection and store it locally in an SQLite database while the application is running in the background? Any insights or guidance you can provide on these matters?
Posted
by mayur c.
Last updated
.
Post not yet marked as solved
0 Replies
278 Views
I activate the conditions as follows Unexpected operation found. Details are below Conditions and configurations used in the testing "Background Modes" Capability with "Location updates" checked on added the info.plist keys: NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationWhenInUseUsageDescription with description invoking startMonitoringSignificantLocationChanges using core location API invoking didUpdateLocations using core location API Using Background fetch (15 minutes) I just press the Home button without any gesture. A few hours after the app was stopped, didfinishlaunch, didenterBackground, background fetch, and didUpdateLocation code did not run, but the app started running again in the background from the point it was stopped. The wake-up time is random, and the app will freeze again within a few seconds of running again.(I took logs in all delegate functions related to the app life cycle in the AppDelegate file, but nothing was executed when the app was relaunched.) Is the above behavior normal? If it's normal, who wakes up the app? How do I prevent my app from restarting unexpectedly?
Posted
by h_susan.
Last updated
.
Post not yet marked as solved
1 Replies
471 Views
I asked a similar question a while back: https://developer.apple.com/forums/thread/730946 Since then I have a new Mac and new iPhone and so I now have the hardware to actually play with WeatherKit. I've worked my way past all the entitlements stuff and have been able to use and expand on online examples. Cool. Trouble is, nearly every example you can find uses code designed to update the UI as fresh weather data is fetched. My app currently uses background URL fetches to obtain weather data, make some calculations and take appropriate actions, all in the background. Updating the UI was a separate challenge. So which asynchronous tool is the right one for this? How can I quickly update my existing code to call WeatherKit instead of going to a weather site for a download? I currently use something like a download task session: let weatherTask = session.downloadTask (with: URL(string: urlString)!) weatherTask.taskDescription = "weather" weatherTask.resume() or a dataTask session: var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("text/html", forHTTPHeaderField: "Content-Type") let taskWeatherPOP = URLSession.shared.dataTask(with: request) { (data, response, error) in if error != nil { print("Error is \(String(describing: error))") } if let POPData = data, let report = String(data: POPData, encoding: String.Encoding.utf8) { if weatherReportPOP.contains("ServiceUnavailable") { print("A Weather POP report error") } else { weatherReportPOP = report } // Close the IF service unavailable } // Closes the IF weather data is not nil } // Close Task Weather taskWeatherPOP.resume()
Posted
by waynehend.
Last updated
.
Post not yet marked as solved
1 Replies
706 Views
i have an issue when handling silent push in my app when the user close the app, here is my native code which works like charm when the app in the foreground, background or terminated status from a short time from closing the app, and after long time from closing it (+30min) it will not work anymore, it make me confuse why it does not work and other messaging app like viber, whatsapp and messanger you can still receive messages and calls even you swipe the app and close it !! is there any thing must i add !! override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -&gt; Void) { Messaging.messaging().appDidReceiveMessage(userInfo) if Auth.auth().canHandleNotification(userInfo) { completionHandler(.noData) return } // sample notification for testing let content = UNMutableNotificationContent() content.title = "Hi there" content.body = "Just test" content.sound = UNNotificationSound.default let request = UNNotificationRequest(identifier: "helloNotification", content: content, trigger: nil) UNUserNotificationCenter.current().add(request) { (error) in if let error = error { print("Error adding notification request: \(error.localizedDescription)") } } // resent to dart side let controller: FlutterViewController = window?.rootViewController as! FlutterViewController let notificationChannel = FlutterMethodChannel(name: "notificationHandler", binaryMessenger: controller.binaryMessenger) var dataToSend: [String: Any] = [:] if let text = userInfo["text"] as? String { dataToSend["text"] = text } // Convert the dictionary to NSDictionary let nsDataToSend = NSDictionary(dictionary: dataToSend) // Pass the NSDictionary to Dart notificationChannel.invokeMethod("handleRemoteMessage", arguments: nsDataToSend) } i checked : background capabilities : remote notifs, background fetching, voip, background processing
Posted
by devops07.
Last updated
.