I was wondering which of the hkquantitytypeidentifiers I can collect while a workout is running.
Essentially which of these types are actually being collected by the sensors on the apple watch rather than being read from manual input.
Thanks
Background Tasks
RSS for tagRequest the system to launch your app in the background to run tasks using Background Tasks.
Posts under Background Tasks tag
123 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hi!
I've been working on app with Silent Background notifications using FCM and I'm facing some issue where system decides to block the receiving notification.
In Console logs I get:
com.apple.pushLaunch.<bundleId>:[{name: ApplicationPolicy, policyWeight: 50.000, response: {Decision: Absolutely Must Not Proceed, Score: 0.00, Rationale: [{[pushDisallowed]: Required:0.00, Observed:1.00},]}} ], FinalDecision: Absolutely Must Not Proceed}]
It never proceeds in case of app being killed and another app in use.
Is there a way to tell the system to proceed or to fix this somehow so we get the notification in such case and make didReceiveRemoteNotification to be called?
Thanks!
whenever the background task stat running one of the UI got triggered i.e published the UI rendering part, so the crash occurred on that publisher subscribed and change the UI, so i don't think the ui doesn't load on the background task runs, so i don't use main thread operation for that UI change, this may be the reason for crash, i dont know, could you please help
When my app enter to background, I start a background task, and when Expiration happens, I end my background task. The code likes below:
backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
[self cancel];
}
});
}];
When the breakpoint is triggered at the endBackgroundTask line, I also get the following log:
[BackgroundTask] Background task still not ended after expiration handlers were called: <UIBackgroundTaskInfo: 0x282d7ab40>: taskID = 36, taskName = Called by MyApp, from MyMethod, creationTime = 892832 (elapsed = 26). This app will likely be terminated by the system. Call UIApplication.endBackgroundTask(:) to avoid this.
The log don't appear every time, so why is that? Is there something wrong with my code?
Hi. I have medical app that communicates with bluetooth device all the time. I set it up to run in background mode ("Background processing"). It works fine if most cases but i noticed that when I start facetime my app suspends. Why is this happening and whats best practice at handling this?
Thank you.
So from what I'm understanding, iOS doesn't do periodic callbacks ?
If that's true, does registering a new background fetch every time a background fetch is triggered work in the same way in practice ?
If none of this is possible, then how do apps like RSS feeds readers regularly fetch data ?
Thanks.
Hello,
I am building an enterprise application, where I will be syncing user location to the backend server every 5 min for a period of 12 hr every day.
I have enabled location updates and background processing for the app in Xcode, and also will be getting location permission as always from user.
We are able to get the location update from the user for the whole time, but the part where we make the service call to sync with backend is delayed.
It works fine for the first couple of minutes, but later we see the delay.
I have also used NWConnection to directly make the service call without using URLSession, this approach is slight better comparatively, but not perfect.
I have made sure "Low power mode" and "Low data mode" is disabled, also "Background App Refresh" is enabled for the application.
I believe it should be possible since may app eg. WhatsApp, Telegram have a feature of sharing live location for up to 8 hrs.
Is there any way where we can achieve this without delay?
Thanks in advance.
I wanted to understand if it is safe to call beginBackgroundTaskWithExpirationHandler in applicationWillEnterForeground or if it should only be called when the app is going to enter the background?
My requirement is that I have a thread running which sends data to the server, and I want to ensure that when the app enters the background, it sends some extra information (like the app has been backgrounded and some other events that occurred while the app was in the foreground). This may take some time to complete. So, I'm trying to understand the best practice for calling beginBackgroundTaskWithExpirationHandler.
Hello, I have a tasks to make an app such that once receive FCM notification, get current SSID and current location, then send it to our server, even if this app is in background (not active) or being killed from app switcher(not sure if it's the correct name, user swipe up to remove apps). Now it works for a couple of hours after putting the app to background, but with a time limit I don't know it stops working.
I personally think it cannot be done, but could somebody please confirm it?
I wrote this simple app to try to fetch and add data to my airport Database in the background.
I'm trying to add some data to the airport table in the background using swift-data, I create a loop that should add and save 100 test airports in a table but when I run the code I only get add 1 airport at the time and the number get add is random, any idea why?
How to use swiftData in the background? So far not so many examples.
actor JsonImporter: ModelActor {
let executor: any ModelExecutor
let context: ModelContext
init(modelContainer: ModelContainer) {
context = ModelContext(modelContainer)
executor = DefaultModelExecutor(context: context)
}
func parseJsonDBAirport() async {
for i in 1...100{
print("loop \(i)")
let airport = Airport(lastPicked: Date(), icao: "test \(i)")
context.insert(airport)
do{
try context.save()
}catch {
print("Error")
}
}
}
}
Using on the view:
struct SettingsView: View {
@Environment (\.modelContext) var mc
var body: some View {
Button {
Task(priority: .background){
let importer = JsonImporter(modelContainer: mc.container)
await importer.parseJsonDBAirport()
}
} label: {
Text("Parse Json airport")
}
NavigationLink {
Airports(dm: dm)
} label: {
HStack{
Image(systemName: "person.2.badge.gearshape.fill")
Text("Airports")
}
}
}
}
my main actor is following:
@main
struct Pilot_VisionApp: App {
var dm = DataManager.shared
var body: some Scene {
WindowGroup {
SettingsView(dm: dm)
}
.modelContainer(for: [UserModel.self, Flight.self, Aircraft.self, CrewModel.self, Airport.self])
}
}
and the airport list as following:
import SwiftUI
import SwiftData
struct Airports: View {
let dm: DataManager
@Query(filter: nil, sort: [SortDescriptor(\Airport.lastPicked)], animation: .default) var airports: [Airport]
var body: some View {
List{
Text("Airport Contains : \(airports.count)")
ForEach(airports) { apt in
Text("icao: \(apt.icao ?? "")")
}
}
}
}
not sure why when I press the button the loop runs correctly I get the printout 100 times but when I open the list of my airport I only see 1 airport saved, every time I press the button one more airport is added to the table but should be 100 airports every time I press the button.
How shuld be use swiftdata in background?
thanks
Hi,
I tried to figure out how I can get my iOS-App to refresh regularly if it is in the background. I thought about WhatsApp. Even if it is closed it updates itself in the background and checks for new messages. But how does it do this?
I would like to observe the battery charging level. But my app should also observe it when I switched the screen off (locked my iPhone). I don't know how to do this. A Timer will not work, it is not available if the app is in the background. To clarify: I know how to read the battery level but I don't know how to observing the battery level when the app is in the background.
I tried to learn something about the Background App Refresh function but I had no success.
I support Live Activities in my app, and am unable to dismiss Live Activities when the app gets closed from the background.
Currently, I subscribe to the willTerminateNotification notification in order to perform actions when the app gets terminated. This guys triggered when the app gets terminated in the foreground. However, if it gets terminated from the background, it does not get triggered and my Live Activity stays after the app gets closed. How can I prevent this from happening?
I'm a beginner in swift.
Ways I tried:
Tried adding a command line tool DNC observer to call a function when any screen sharing notification triggers, but later came to know that screen sharing doesn’t give any notifications.
import OSLog
import Foundation
os_log("TecMFA:: Starting screen sharing finder.")
let dnc = DistributedNotificationCenter.default()
dnc.addObserver(
forName: .init("com.apple.screensharing.server"), // tried many notification names like com.apple.screensharing.curtain etc.
object: nil,
queue: .main
) { notification in
os_log("TecMFA:: Started screen sharing deamon.")
}
dispatchMain()
Created a server using vapor as following
//configure.swift
import Vapor
func routes(_ app: Application) throws {
// Define a route to handle POST requests to "/login"
app.post("login") { req -> HTTPStatus in
// Read the username and password from the request body
guard let loginData = try? req.content.decode(LoginData.self) else {
// Failed to parse request body or invalid data
return .badRequest
}
let username = loginData.username
let password = loginData.password
print(username)
print(password)
// Do something with the username and password
print("Received login request with username: \(username) and password: \(password)")
// Return a success response
return .ok
}
}
// Define a struct to represent the request body data
struct LoginData: Content {
let username: String
let password: String
}
// routes.swift
import Vapor
import Foundation
func getLocalIPAddress() -> String? {
let task = Process()
task.launchPath = "/usr/sbin/ipconfig"
task.arguments = ["getifaddr", "en0"] // Use "en0" for Wi-Fi, "en1" for Ethernet
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
return output
}
// Called before your application initializes.
public func configure(_ app: Application) throws {
// Register routes
try routes(app)
// Get the local IP address
guard let localIPAddress = getLocalIPAddress() else {
fatalError("Unable to get the local IP address.")
}
// Update the server configuration to bind to the local IP address and desired port
app.http.server.configuration.hostname = localIPAddress
app.http.server.configuration.port = 8080
}
It didn't work when same port numbers. I tried using different port numbers but the request comes through port 5900, so 8080 cannot access it, so it didn't work either.
Any corrections and suggestions are welcome.
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?
We are developing an app that is going to be used with hardware that is connected through bluethooth to the iOS device, where we use a device with an MFI external accessory, and we are using the external accessory framework, and this will require some background tasks, we understand that there is a limitation on the use on background capabilities, but we were wondering what is the best approach to gather information from the hardware while the app is running on the background? think of the Oura ring, the app is gathering some information while you are sleeping, not processing, not fully running, only gathering information. Should we doit with the BGProcesingTask? or there is an additional background strategy to this kind of use case?
Thanks.
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
Trying to to convert my old URL functionality to SwiftUI with async/await. While the skeleton below works, am puzzled as to why I must place my call to the method within a Task? When I don't use Task I get the error:
Cannot pass function of type '() async -> Void' to parameter expecting synchronous function type
From the examples I've seen, this wasn't necessary.
So I either I've misunderstood something, or I am doing this incorrectly, and am looking for little but of guidance.
Thank you
Within my SwiftUI view:
Button {
Task {
let request = xFile.makePostRequest(xUser: xUser, script: "requestTicket.pl")
var result = await myNewURL.asyncCall(request: request)
print("\(result)")
}
}
From a separate class:
class MyNewURL: NSObject, ObservableObject {
func asyncCall(request: URLRequest) async -> Int {
do {
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse
else {
print("error")
return -1
}
if httpResponse.statusCode == 200 {
...
}
} catch {
return -2
}
return 0
}
}
I am sorry for my poor English.
I know that a callback of timer is not called in background mode. I know that I should add capabilities, permissions and keys into the Info file for doing something in background mode.
But I do not need any complicated task in background mode, just need to terminate my app automatically after 30 minutes in background mode.
Is there a simple way for that purpose?
Can I keep my app running continuously in the background?
Is it possible to run code in background every 15 minutes?
Sorry if this is a stupid question but I haven't been able to find any information on whether an app can request and receive weatherKit data - the weather - while in the background.
My app (AirCompare) makes extensive use of background URL sessions to fetch and process weather data. If certain conditions are met, a notification alert is sent to the user so the user can decide whether to activate the app. For instance if rain is in the forecast, the app alerts the user that they might want to close their windows. Making the app active will execute HomeKit control and accomplish that.
Will I be able to replace the background URL session with the appropriate code and be able to fetch weather data in the background?