I'm a developer using Lazarus Pascal, so converting ObjC and Swift comes with its challenges.
I'm trying to figure how to properly use SMAppService to add my application as a login item for the App Store.
I have learned that the old method (< macOS 13) uses a helper tool, included in the app bundle, which calls the now deprecated SMLoginItemSetEnabled. Now this is already quite a pain to deal with if you're not using XCode, not to mention converting the headers being rather complicated when you're not experienced with doing this.
The "new" method (as of macOS 13) is using SMAppService.
Can anyone explain how to use this? The documentation (for me anyway) is a not very clear about that and neither are examples that can be found all over the Internet.
My main question is:
Can I now use the SMAppService functions to add/remove a login item straight in my application, or is a helper tool still required?
Processes & Concurrency
RSS for tagDiscover how the operating system manages multiple applications and processes simultaneously, ensuring smooth multitasking performance.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I'm developing a macOS application that tracks the duration of a user's session using a timer, which is displayed both in the main window and in an menu bar extra view. I have a couple of questions regarding the timer's behavior:
What happens to the timer if the user closes the application's window (causing the app to become inactive) but does not fully quit it? Does the timer continue to run, pause, or behave in some other way?
Will the app nap feature stop the timer when app is in-active state?
I'm developing a macOS application that tracks the duration of a user's session using a timer, which is displayed both in the main window and in an menu bar extra view. I have a couple of questions regarding the timer's behavior:
What happens to the timer if the user closes the application's window (causing the app to become inactive) but does not fully quit it? Does the timer continue to run, pause, or behave in some other way?
Will the app nap feature stop the timer when app is in-active state?
When the application is inactive and the system is either in sleep mode or locked, does the timer’s tolerance get affected? In other words, will the timer fire with any additional delay compared to its scheduled time under these conditions?
I am encountering an issue with my application, BloxOneEndpoint.pkg, which includes two services:
rc_service_infoblox – Runs as the root user.
Controller Application – Runs as a normal user.
Although a thread within rc_service_infoblox is running fine and performing its expected tasks, I notice that the service appears as "Not Responding" in Activity Monitor. Despite normal functionality, this status is concerning, as it may indicate some issue to customer.
I would appreciate any insights into why this might be happening and how to resolve it. Is there a specific API or mechanism I should use to ensure the service remains in a "Running" state in Activity Monitor?
Thank you for your guidance.
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Endpoint Security
Service Management
I have BGProcessingTask & BGAppRefreshTask working fine. The main purpose of my use of BGProcessingTask is to upload a file to AWS S3 using multipart/form-data. I have found that any file above about 2.5MB times out after running almost four minutes. If I run the same RESTful api using curl or Postman, I can upload a 25MB file in 3 seconds or less.
I have tried to deliberately set .earliestBeginDate to 01:00 or 02:00 local time on the iPhone, but that does not seem to help.
I use the delegate (yes, I am writing in Objective C) - URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: and find that the iOS system uploads about 140kB every 15 seconds or so.
I am looking for recommendations or insight into how I might enable uploads of 25MB files. I would be happy it I could do just one a day for my use case.
I provide code on how I set up the NSURLSession and NSURLSessionDownloadTask, as it is my guess that if there is something that needs to be modified it is there.
I have to believe there is a solution for this since I read in many posts here and in StackOverflow how developers are using this functionality for uploading many, many files.
NSURLSessionConfiguration *sConf = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:bkto.taskIdentifier];
sConf.URLCache = [NSURLCache sharedURLCache];
sConf.waitsForConnectivity = YES;
sConf.allowsCellularAccess = NO;
sConf.networkServiceType = NSURLNetworkServiceTypeVideot;
sConf.multipathServiceType = NSURLSessionMultipathServiceTypeNone;
sConf.discretionary = YES;
sConf.timeoutIntervalForResource = kONEHOURINTERVAL;
sConf.timeoutIntervalForRequest = kONEMINUTEINTERVAL;
sConf.allowsExpensiveNetworkAccess = NO ;
sConf.allowsConstrainedNetworkAccess = NO;
sConf.sessionSendsLaunchEvents = YES;
myURLSession = [NSURLSession sessionWithConfiguration:sConf delegate:self delegateQueue:nil];
And then later in the code...
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:pth]];
request.HTTPMethod = kHTTPPOST;
request.HTTPBody = [NSData my body data];
request.timeoutInterval = 60;
[request setValue:@"*/*" forHTTPHeaderField:@"Accept"];
[request setValue:@"en-us,en" forHTTPHeaderField:@"Accept-Language"];
[request setValue:@"gzip, deflate, br" forHTTPHeaderField:@"Accept-Encoding"];
[request setValue:@"ISO-8859-1,utf-8" forHTTPHeaderField:@"Accept-Charset"];
[request setValue:@"600" forHTTPHeaderField:@"Keep-Alive"];
[request setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
NSString *contType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",bnd];
[request setValue:contType forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"%lu",(unsigned long)myData.length] forHTTPHeaderField:@"Content-Length"];
and here are a few lines from my logs to show the infrequent multi-part uploads of only small chunks of data by the iOS system:
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: bytesSent = 393,216
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: totalBytesSent = 393,216
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: task = BackgroundDownloadTask <76A81A80-4703-4686-8742-A0048EB65108>.<2>, time Fri Mar 7 16:25:27 2025
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: bytesSent = 131,072
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: totalBytesSent = 524,288
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: task = BackgroundDownloadTask <76A81A80-4703-4686-8742-A0048EB65108>.<2>, time Fri Mar 7 16:25:42 2025
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: bytesSent = 131,072
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: totalBytesSent = 655,360
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: task = BackgroundDownloadTask <76A81A80-4703-4686-8742-A0048EB65108>.<2>, time Fri Mar 7 16:25:56 2025
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: bytesSent = 131,072
-[BKSessionManager URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:]: totalBytesSent = 786,432
I have an app that uses background audio recording. From what others say, I have enabled the audio background mode to keep the audio session active, and this worked. But when submitting the app to the app store, the app was rejected because the audio background mode is only supposed to be used for audio playback.
How do I create this background mode while following Apple's guidelines?
Im using the low-level C xpc api <xpc/xpc.h> and i get this error when I run it: Underlying connection interrupted. I know this error stems from the call to xpc_session_send_message_with_reply_sync(session, message, &reply_err);. I have no previous experience with xpc or dispatch and I find the xpc docs very limited and I also found next to no code examples online. Can somebody take a look at my code and tell me what I did wrong and how to fix it? Thank you in advance.
Main code:
#include <stdio.h>
#include <xpc/xpc.h>
#include <dispatch/dispatch.h>
// the context passed to mainf()
struct context {
char* text;
xpc_session_t sess;
};
// This is for later implementation and the name is also rudimentary
void mainf(void* c) {
//char * text = ((struct context*)c)->text;
xpc_session_t session = ((struct context*)c)->sess;
dispatch_queue_t messageq = dispatch_queue_create("y.ddd.main",
DISPATCH_QUEUE_SERIAL);
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_string(message, "test", "eeeee");
if (session == NULL) {
printf("Session is NULL\n");
exit(1);
}
__block xpc_rich_error_t reply_err = NULL;
__block xpc_object_t reply;
dispatch_sync(messageq, ^{
reply = xpc_session_send_message_with_reply_sync(session,
message,
&reply_err);
if (reply_err != NULL) printf("Reply Error: %s\n",
xpc_rich_error_copy_description(reply_err));
});
if (reply != NULL)
printf("Reply: %s\n", xpc_dictionary_get_string(reply, "test"));
else printf("Reply is NULL\n");
}
int main(int argc, char* argv[]) {
// Create seperate queue for mainf()
dispatch_queue_t mainq = dispatch_queue_create("y.ddd.main",
DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t xpcq = dispatch_queue_create("y.ddd.xpc",
NULL);
// Create the context being sent to mainf
struct context* c = malloc(sizeof(struct context));
c->text = malloc(sizeof("Hello"));
strcpy(c->text, "Hello");
xpc_rich_error_t sess_err = NULL;
xpc_session_t session = xpc_session_create_xpc_service("y.getFilec",
xpcq,
XPC_SESSION_CREATE_INACTIVE,
&sess_err);
if (sess_err != NULL) {
printf("Session Create Error: %s\n",
xpc_rich_error_copy_description(sess_err));
xpc_release(sess_err);
exit(1);
}
xpc_release(sess_err);
xpc_session_set_incoming_message_handler(session, ^(xpc_object_t message) {
printf("message recieved\n");
});
c->sess = session;
xpc_rich_error_t sess_ac_err = NULL;
xpc_session_activate(session, &sess_ac_err);
if (sess_err != NULL) {
printf("Session Activate Error: %s\n",
xpc_rich_error_copy_description(sess_ac_err));
xpc_release(sess_ac_err);
exit(1);
}
xpc_release(sess_ac_err);
xpc_retain(session);
dispatch_async_f(mainq, (void*)c, mainf);
xpc_release(session);
dispatch_main();
}
XPC Service code:
#include <stdio.h>
#include <xpc/xpc.h>
#include <dispatch/dispatch.h>
int main(void) {
xpc_rich_error_t lis_err = NULL;
xpc_listener_t listener = xpc_listener_create("y.getFilec",
NULL,
XPC_LISTENER_CREATE_INACTIVE,
^(xpc_session_t sess){
printf("Incoming Session: %s\n", xpc_session_copy_description(sess));
xpc_session_set_incoming_message_handler(sess,
^(xpc_object_t mess) {
xpc_object_t repl = xpc_dictionary_create_empty();
xpc_dictionary_set_string(repl, "test", "test");
xpc_rich_error_t send_repl_err = xpc_session_send_message(sess, repl);
if (send_repl_err != NULL) printf("Send Reply Error: %s\n",
xpc_rich_error_copy_description(send_repl_err));
});
xpc_rich_error_t sess_ac_err = NULL;
xpc_session_activate(sess, &sess_ac_err);
if (sess_ac_err != NULL) printf("Session Activate: %s\n",
xpc_rich_error_copy_description(sess_ac_err));
},
&lis_err);
if (lis_err != NULL) {
printf("Listener Error: %s\n", xpc_rich_error_copy_description(lis_err));
xpc_release(lis_err);
}
xpc_rich_error_t lis_ac_err = NULL;
xpc_listener_activate(listener, &lis_ac_err);
if (lis_ac_err != NULL) {
printf("Listener Activate Error: %s\n", xpc_rich_error_copy_description(lis_ac_err));
xpc_release(lis_ac_err);
}
dispatch_main();
}
Hi. I'm trying to learn macOS app development. i'm trying to run unix commands:
func execute(_ command: String) throws -> String {
let process = Process()
let pipe = Pipe()
process.executableURL = URL(fileURLWithPath: "/bin/bash")
process.arguments = ["-c", command]
process.standardOutput = pipe
// process.standardError
try process.run()
process.waitUntilExit()
guard let data = try pipe.fileHandleForReading.readToEnd() else {
throw CommandError.readError
}
guard let output = String(data: data, encoding: .utf8) else {
throw CommandError.invalidData
}
process.waitUntilExit()
guard process.terminationStatus == 0 else {
throw CommandError.commandFailed(output)
}
return output
}
when try to run "pgrep" in sandbox mode ON, i get:
sysmon request failed with error: sysmond service not found error. if i turn it off it works. i don't know what to do. anyone can help me out?
I'm working on an XPC server and need to determine the owner of the client process that connects to it. Specifically, I'd like to retrieve details such as the fully qualified user name or other identifying information from the XPC client connection.I'm considering using xpc_connection_get_pid() to get the client’s process ID, but I’m unsure of the best way to map this to the user who owns the process.
Is there a recommended API or approach to capture this information securely?
I'm using Swift 6 and tasks to concurrently process multiple PDF files for rendering, and it's working well.
But currently I'm manually limiting the number of simultaneous tasks to 2 out of fear that the system might run many tasks concurrently without having enough RAM to do the PDF processing.
Testing on a variety of devices, I've tried increasing the task limit and haven't seen any crashes, but I'm quite concerned about the possibility. Any given device might be using a lot of RAM at any moment, and any given PDF might strain resources more than the average PDF.
Is there a recommended technique for handling this kind of scenario?
Should I not worry about it and just go ahead and start a high number of tasks, trusting that the system won't run too many concurrently and therefore won't run out of RAM?
Topic:
App & System Services
SubTopic:
Processes & Concurrency
I have used C APIs to create a XPC server(mach service) as a launch daemon. I use dispatch_source_create () followed by dispatch_resume() to start the listener. I dont have any code for cleaning up memory.
I want to make sure that the XPC server is shutdown gracefully, without any memory leaks.
I know that launchd handles the cycle and the XPC framework takes care of XPC objects.
But do I need to do additional cleanup when the XPC listener is shutdown ?
When using the old withTaskCancellationHandler(operation:onCancel:isolation:) to run background tasks, you were notified that the background task gets cancelled via the handler being called. SwiftUI provides the backgroundTask(_:action:) modifier which looks quite handy. However how can I check if the background task will be cancelled to avoid being terminated by the system?
I have tried to check that via Task.isCancelled but this always returns false no matter what.
Is this not possible when using the modifier in which case I should file a bug report?
Thanks for your help
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
SwiftUI
Background Tasks
WidgetKit
Desired Behavior
I want the app to be able to handle multiple Push-to-Start notifications even when it is completely terminated. Each Live Activity should:
Be successfully displayed upon receiving a Push-to-Start notification.
Trigger background tasks to send its update token to the server, regardless of the time interval between notifications.
Problem
I am facing an issue with iOS Live Activities when using Push-to-Start notifications to trigger Live Activities in an app that has been completely terminated. Here’s the detailed scenario:
When the app is completely terminated and I send the first Push-to-Start notification:
The Live Activity is successfully displayed.
didFinishLaunchingWithOptions` is triggered, and background tasks execute correctly, including sending the update token to the server.
When I send consecutive Push-to-Start notifications in quick succession (e.g., within a few seconds or minutes):
Both notifications successfully display their respective Live Activities.
Background tasks are executed correctly for both notifications.
However, when there is a longer interval (e.g., 10 minutes) between two Push-to-Start notifications:
The first notification works perfectly—it displays the Live Activity, triggers didFinishLaunchingWithOptions, and executes background tasks.
The second notification successfully displays the Live Activity but fails to execute any background tasks, such as sending the update token to the server.
My HypothesisI
suspect that iOS might impose a restriction where background runtime for Push-to-Start notifications can only be granted once within a certain time frame after the app has been terminated.
Any insights into why this issue might be occurring or how to ensure consistent background task execution for multiple Push-to-Start notifications would be greatly appreciated!
Hello Apple Developer Community,
I am developing a medical app that is classified as Class B according to FDA regulations. The app connects to a medical device using Bluetooth Low Energy (BLE) to collect critical medical data such as ECG readings. To ensure accurate data collection and maintain the quality of the medical readings, the app needs to wake up every five minutes in the background and perform tasks for approximately 30 seconds.
I understand that iOS has strict limitations on background execution to preserve battery and system performance. However, due to the medical nature of the app and the need for periodic data collection, I am seeking guidance on the following:
If I can provide documentation that the app is associated with an FDA-approved Class B medical device, would Apple allow more lenient background task execution policies?
Are there specific APIs, such as BackgroundTasks, CoreBluetooth, or other recommended strategies, that could help me achieve this behavior reliably?
Is there a process to apply for an exception or special consideration for medical apps that require periodic background activity?
Any insights or recommendations would be greatly appreciated. Thank you!
We are building a 'server' application that can either run as a daemon or can run in background without showing any GUI. Basically, the end user can either configure this to run as a daemon so that it can be tied to the user's session or will launch the process which user will start and quit as needed.
I wanted to understand what is the recommended mechanism for such an application from Apple -
Should this application be built as a macOS Bundle ? Apple documentation also says that we should not daemonize the process by calling fork. Hence if we create a unix-style executable, will I not need to fork to make it run in a detached state when I launch the executable via double-click ? [Reference Link]
Is it fine to have an application on macOS which is a bundle but does not show any UI when launched by double click on the app-icon or via 'open'? While we have been able to achieve this by using NSApplicationMain and not showing the UI, was wondering if using CFRunLoop is best for this case as it is a non-gui application.
If we can get the right documentation link or recommendations on how we should build such an application which can run in a non-gui mode and also in a daemonized manner, it will help us.
Should the application be always built as a macos bundle or should it be a unix-style executable to support both the cases - by the same application/product and how should we look at the distribution of such applications.
I have implemented a XPC server using C APIs. I want to write unit tests for it.
I came across the following links that use Swift APIs-
Testing and Debugging XPC Code With an Anonymous Listener
TN3113
I have tried to write anonymous listener code and the client code in the same file, using C APIs-
#include <unistd.h>
#include <syslog.h>
#include <pthread.h>
#include <stdio.h>
#include <xpc/xpc.h>
#include <xpc/connection.h>
#include <CoreFoundation/CoreFoundation.h>
static void Anon_Client_Connection_Handler(xpc_connection_t connection, xpc_object_t clientMessage)
{
const char *description = xpc_copy_description(clientMessage);
printf("Event received - %s\n", description);
free((void *)description);
xpc_type_t type = xpc_get_type(clientMessage);
if (type == XPC_TYPE_ERROR)
{
if (clientMessage == XPC_ERROR_CONNECTION_INVALID)
printf("Client_Connection_Handler received invalid connection n");
else if (clientMessage == XPC_ERROR_TERMINATION_IMMINENT)
printf("Client_Connection_Handler received termination notice n");
}
else
{
const char *clientMsg = xpc_dictionary_get_string(clientMessage, "message");
printf("Received from client: %s ", clientMsg);
}
}
static void Anon_Listener_Connection_Handler(xpc_connection_t connection)
{
printf("Anon_Listener_Connection_Handler called, setting up event handler \n");
xpc_connection_set_event_handler(connection, ^(xpc_object_t clientMessage) {
printf("Processing the connection! \n");
Anon_Client_Connection_Handler(connection, clientMessage);
});
xpc_connection_resume(connection);
}
int main(int argc, const char *argv[])
{
xpc_connection_t anon_listener = xpc_connection_create(NULL, NULL);
xpc_connection_set_event_handler(anon_listener, ^(xpc_object_t clientConnection) {
printf("Client tried to connect \n");
Anon_Listener_Connection_Handler(clientConnection);
});
xpc_connection_resume(anon_listener);
printf("\nINFO Anonymous connection resumed");
xpc_object_t anon_endpoint = xpc_endpoint_create(anon_listener);
xpc_connection_t clientConnection = xpc_connection_create_from_endpoint(anon_endpoint);
xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0);
xpc_dictionary_set_string(message, "message", "client's message");
xpc_connection_send_message_with_reply(clientConnection, message, dispatch_get_main_queue(), ^(xpc_object_t event) {
printf("\nINFO inside reply");
const char *description = xpc_copy_description(event);
printf("\nINFO %s",description);
free((void *)description);
});
xpc_release(message);
xpc_release(anon_listener);
printf("\nINFO Releasing listener");
xpc_release(anon_endpoint);
printf("\nINFO Releasing endpoint");
// dispatch_main();
return 0;
}
and this is the output I get
INFO Anonymous connection resumed
INFO Releasing listener
INFO Releasing endpoint
I am not able to connect to the client and exchange messages. Where am I going wrong?
I am developing a macOS non-interactive macOS application which does not show any ui.
i want to block main thread and do all the work on worker thread . Once done with work in worker thread, want to unblock main thread by exiting event loop to terminate application.
Because i dont want to show any UI or use any Foundation/Cocoa functionality, i am thinking of using CFRunLoop to block main thread from exiting until i finish my work in worker thread.
When i tried this in a project, I am able to finish work in worker thread after block main thread using CFRunLoop.
I also want this application to be a bundled application, which can be launched by double clicking on application bundle . But when i tried it in my xcode project by launching it using double clicking on application bundle, application keeps on toggling/bouncing in the dock menu with a status "Not responding". Although i am able to complete my work in worker thread.
import Foundation
let runLoop = CFRunLoopGetCurrent()
func workerTask() {
DispatchQueue.global().async {
print("do its work")
sleep(5) // do some work
print("calling exit event loop")
CFRunLoopStop(runLoop)
print ("unblocking main thread")
}
}
workerTask ()
// blocking main thread
print ("blocked main thread")
CFRunLoopRun()
print ("exit")
Why i am getting this application bouncing in doc menu behavior ? I tried by using NSApplicationMain instead of CFRunLoop in my project, in that case i didnt get this behavior .
Does NSApplicationMain does some extra work before starting NSRunLoop which i am not doing while using CFRunLoop, which is showing this toggling/Bouncing application icon in Dock menu ?
or Is this bouncing app icon issue is related to run loop i am using which is CFRunLoop ?
Note : If i dont use a bundled application and use a commandline application then i am able to do all steps in worker thread and exit main thread as i wanted after finishing my work . But i need to do all this in application which can be launched using double clicking (bundled applcation).
If not by using CFRunLoop, then how can i achive this ? - Create a application which shows no UI and do all work in worker thread while main thread is blocked. Once work is done unblock main thread and exit. And user should be able to launch application using double click the application icon.
Are there any plans to add RBI support (the sending keyword) to the OSAllocatedLock interface? So it could be used with non-sendable objects without surrendering to the unchecked API
Is the title possible ? I tried [[thread valueForKey:@"_private"] valueForKey:@"tid"] but the tid was not kvc compliant. private apis are alright because this is just for testing remote process thread creation. I already have a working method but it has hardcoded assembly so you can't do anything else.
this question is mainly for Quinn (figured he may know something about this)
I've been seeing a high number of BGTaskScheduler related crashes, all of them coming from iOS 18.4. I've encountered this myself once on launch upon installing my app, but haven't been able to reproduce it since, even after doing multiple relaunches and reinstalls. Crash report attached at the bottom of this post.
I am not even able to symbolicate the reports despite having the archive on my MacBook:
Does anyone know if this is an iOS 18.4 bug or am I doing something wrong when scheduling the task? Below is my code for scheduling the background task on the view that appears when my app launches:
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
#if !os(macOS)
let request = BGAppRefreshTaskRequest(identifier: "notifications")
request.earliestBeginDate = Calendar.current.date(byAdding: .hour, value: 3, to: Date())
do {
try BGTaskScheduler.shared.submit(request)
Logger.notifications.log("Background task scheduled. Earliest begin date: \(request.earliestBeginDate?.description ?? "nil", privacy: .public)")
} catch let error {
// print("Scheduling Error \(error.localizedDescription)")
Logger.notifications.error("Error scheduling background task: \(error.localizedDescription, privacy: .public)")
}
#endif
...
}
2025-02-23_19-53-50.2294_+0000-876d2b8ec083447af883961da90398f00562f781.crash