After logging in to the main App, turn on screen recording, then switch to the interface of another App to perform operations. After about ten-odd minutes, when returning to the main App, it was found that the app was forcefully quit by the system, and subsequent operations could not be carried out.
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 am considering to use the BGAppRefreshTask mechanism, and while I think I have read and understood all documentation and hints in this forum about it (especially the limitations), the one thing I do not understand is: how can I debug it? I cannot find a way to trigger the BGAppRefreshTask execution reliably and immediately. I would have expected the Xcode Debug->Simulate Background Fetch menu to do this for me, but it only sends the app into the background.
I am working with the unmodified (except for a few added print()) ColorFeed sample code project from Apple, which schedules a task 15min into the future when it goes to the background. Using a real device, I have not managed to trigger execution of the BGAppRefreshTask more often than once a day so far.
Surely, there must be a way to trigger it much more often solely for debugging and development purposes (I am totally happy with all restrictions for the final app).
So what detail am I missing here?
Hello, I'm developing a Mac application that uses a network extension. I'm trying to implement XPC to pass data between my main app and system extension and I'm using the SimpleFirewall demo app as a guide to do this. One thing I can't understand is how the ViewController in the SimpleFirewall main app has access to the class IPCConnection in the SimpleFirewallExtension without it being public and without SimpleFirewallExtension being imported in ViewController.
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
XPC
System Extensions
Network Extension
An XPC service’s process has a system-managed lifecycle: the process is launched on-demand when another process tries to connect to it, and the system can decide to kill it when system resources are low. XPC services can tell the system when they shouldn’t be killed using xpc_transaction_begin/end.
Do extensions created with ExtensionFoundation and/or ExtensionKit have the same behavior?
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 am developing the application in Mac. My requirement is to start the application automatically when user login.
I have tried adding the plist file in launch agents, But it doesn't achieve my requirement.
Please find the code added in the launch agents
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.sftk.secure</string>
<key>ProgramArguments</key>
<array>
<string>/Applications/Testing.app/Contents/MacOS/Testing</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<false/>
</dict>
</plist>
I have tried by adding manually in the setting, but it was opened sometimes and closed suddenly. On open manually it works.
Please provide a solution to start the application automatically on system starts
I would like to implement an expression that pops out from the window to Immersive based on the following WWDC video.
This video introduces the new features of visionOS 2.0 in the form of refurbishing Apple's sample app BOT-anist.
https://developer.apple.com/jp/videos/play/wwdc2024/10153/?time=1252
In the video, it looks like ImmersiveSpaceAppModel is newly implemented.
However, the key code is not mentioned anywhere.
You pass appModel.robot as the from argument to the transform method of RealityViewContent.
It seems that BOT-anist has been updated once and can be downloaded from the following URL, but there is no class such as ImmersiveSpaceAppModel implemented in this app either.
https://developer.apple.com/documentation/visionos/bot-anist
Has it been further updated again?
Frankly, I'm not sure if it is possible to proceed as per the WWDC video.
Translated with DeepL.com (free version)
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Swift
RealityKit
Reality Composer Pro
visionOS
Hi everyone,
We’re developing a macOS SwiftUI app that uses a local Swift Package (CasSherpaCore) to invoke an external compiled binary (sherpa-onnx-offline-tts) for text-to-speech synthesis using system calls. The package works flawlessly when tested from terminal or via a lightweight test C program.
However, when we invoke it from a SwiftUI app (even with Full Disk Access granted to Xcode and Terminal), we consistently get the error:
sh: /Users/xxxxxxxxxxx/SherpaONNX/sherpa-onnx/build/bin/sherpa-onnx-offline-tts: Operation not permitted
We’ve tried:
Granting Full Disk Access to Xcode and Terminal.
Removing the quarantine flag with xattr -d com.apple.quarantine.
Setting executable permission via chmod +x.
Using both system() and Process in C and Swift contexts.
Testing within a Swift Package that’s integrated into the app as a local dependency.
Running the command manually from terminal (works perfectly).
It appears that macOS (or Xcode’s runtime sandbox) is restricting execution of binaries from certain locations or contexts when launched via system() inside the app.
Questions:
Is there a specific entitlement or configuration that allows execution of local binaries from a SwiftUI macOS app?
Is this related to System Integrity Protection (SIP) or a hardened runtime limitation?
Are there best practices or alternative approaches to safely execute local TTS binaries from within a Swift app?
Any help would be deeply appreciated. This is a core feature in our project and we’re stuck at this point. Thank you so much in advance!
My app is for personal use currently, so distribution won't be a problem. It registers a privileged helper using SMAppService, and I was wondering whether there is a way to customize the authorization dialog that the system presents to the user.
How to execute code on main app when interacted with a live activity, given that they are already interactable.
is there a way without opening the app?
what are the best ways?
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Extensions
WidgetKit
ActivityKit
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();
}
My app uses SMAppService to register a privileged helper, the helper registers without errors, and can be seen in System Settings. I can get a connection to the service and a remote object proxy, but the helper process cannot be found in Activity Monitor and the calls to the proxy functions seem to always fail without showing any specific errors. What could be causing this situation?
Basically the title. I am trying to implement a local notification to trigger, regardless of internet connection, around 3-5pm if a certain array in the app is not empty to get the user to sync unsaved work with the cloud. I wanted to used the BGAppRefreshTask as I saw it was lightweight and quick for just posting a banner notification but after inspecting it in the console, it looks like it needs internet connection to trigger. Is this the case or am I doing something wrong? Should I be using the BGProcessingTask instead?
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Background Tasks
User Notifications
Hello 👋
Our team added com.apple.security.temporary-exception.apple-events: com.apple.Terminal recently to our Mac app to be able to tell the terminal to execute a specific command line automatically for the user when clicking a button but we've been rejected during review because of this entitlement so for now we've deleted it and deleted the associated feature.
It concerns the following feature (see attachment).
Context:
Among other things the application enable to review pull request changes (remote) and we would like a button to automatically clone the pull request on disk when user click a button. We would like to use terminal for security reason as when cloning using git command we need ssh keys or other credential and there's no reason (rather than technical ones) that the user provide us such private information that is stored in the ~/.ssh. We prefer think the other way around and tell the user what to execute instead (no credentials involved or shared).
We referred to: https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/AppSandboxTemporaryExceptionEntitlements.html
I admit it's unclear for me if this will imply a 100% rejection or if these entitlements are deprecated.
Is "com.apple.security.temporary-exception.apple-events: com.apple.Terminal" an entitlement that is reserved for special Apple partners ?
Is it an entitlement that we should demonstrate usage first ? Or should we completely remove the feature if we distribute through the App Store ?
Is Apple advice for other APIs to develop such features (execute command line for the user) when distributing through the App Store ?
As said we've disabled the feature for now.
Thank you in advance for those who will take time to answer this,
https://idmsa.apple.com/IDMSWebAuth/signin?path=%2F%2Fforums%2Fpost%2Fquestion%3Flogin%3Dtrue&language=US-EN&instanceId=EN&appIdKey=25138a77e3499638936f018102a53961c923f72b517d4a4d6aee9f09529baca9&rv=4
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Hello,
I am trying to implement a subscriber which specifies its own demand for how many elements it wants to receive from a publisher.
My code is below:
import Combine
var array = [1, 2, 3, 4, 5, 6, 7]
struct ArraySubscriber<T>: Subscriber {
typealias Input = T
typealias Failure = Never
let combineIdentifier = CombineIdentifier()
func receive(subscription: any Subscription) {
subscription.request(.max(4))
}
func receive(_ input: T) -> Subscribers.Demand {
print("input,", input)
return .max(4)
}
func receive(completion: Subscribers.Completion<Never>) {
switch completion {
case .finished:
print("publisher finished normally")
case .failure(let failure):
print("publisher failed due to, ", failure)
}
}
}
let subscriber = ArraySubscriber<Int>()
array.publisher.subscribe(subscriber)
According to Apple's documentation, I specify the demand inside the receive(subscription: any Subscription) method, see link.
But when I run this code I get the following output:
input, 1
input, 2
input, 3
input, 4
input, 5
input, 6
input, 7
publisher finished normally
Instead, I expect the subscriber to only "receive" elements 1, 2, 3, 4 from the array.
How can I accomplish this?
XPC is the preferred inter-process communication (IPC) mechanism on Apple platforms. XPC has three APIs:
The high-level NSXPCConnection API, for Objective-C and Swift
The low-level Swift API, introduced with macOS 14
The low-level C API, which, while callable from all languages, works best with C-based languages
General:
Forums subtopic: App & System Services > Processes & Concurrency
Forums tag: XPC
Creating XPC services documentation
NSXPCConnection class documentation
Low-level API documentation
XPC has extensive man pages — For the low-level API, start with the xpc man page; this is the original source for the XPC C API documentation and still contains titbits that you can’t find elsewhere. Also read the xpcservice.plist man page, which documents the property list format used by XPC services.
Daemons and Services Programming Guide archived documentation
WWDC 2012 Session 241 Cocoa Interprocess Communication with XPC — This is no longer available from the Apple Developer website )-:
Technote 2083 Daemons and Agents — It hasn’t been updated in… well… decades, but it’s still remarkably relevant.
TN3113 Testing and Debugging XPC Code With an Anonymous Listener
XPC and App-to-App Communication forums post
Validating Signature Of XPC Process forums post
This forums post summarises the options for bidirectional communication
This forums post explains the meaning of privileged flag
Related tags include:
Inter-process communication, for other IPC mechanisms
Service Management, for installing and uninstalling Service Management login items, launchd agents, and launchd daemons
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
I have a video, after recording there is no sound, after a few seconds there is only audio sound that I recorded.
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Hello,
I recently implemented a conditional debounce publisher using Swift's Combine.
If a string with a length less than 2 is passed, the event is sent downstream immediately without delay. If a string with a length of 2 or more is passed, the event is emitted downstream with a 0.2-second delay.
While writing test logic related to this, I noticed a strange phenomenon: sometimes the publisher, which should emit events with a 0.2-second delay, does not emit an event.
The test code below should have all indices from 1 to 100 in the array, but sometimes some indices are missing, causing the assertion to fail. Even after observing completion, cancel, and output events through handleEvents, I couldn't find any cause. Am I using Combine incorrectly, or is there a bug in Combine?
I would appreciate it if you could let me know.
import Foundation
import Combine
var cancellables: Set<AnyCancellable> = []
@MainActor func text(index: Int, completion: @escaping () -> Void) {
let subject = PassthroughSubject<String, Never>()
let textToSent = "textToSent"
subject
.map { text in
if text.count >= 2 {
return Just<String>(text)
.delay(for: .seconds(0.2), scheduler: RunLoop.main)
.eraseToAnyPublisher()
} else {
return Just<String>(text)
.eraseToAnyPublisher()
}
}
.switchToLatest()
.sink {
if $0.count >= 2 {
completion()
}
}.store(in: &cancellables)
for i in 0..<textToSent.count {
let stringIndex = textToSent.index(textToSent.startIndex, offsetBy: i)
let stringToSent = String(textToSent[textToSent.startIndex...stringIndex])
subject.send(stringToSent)
}
}
var array = [Int]()
for i in 1...100 {
text(index: i) {
array.append(i)
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
for i in 1...100 {
assert(array.contains(i))
}
}
RunLoop.main.run(until: .now + 10)
I was stuck on a long train journey this weekend, so I thought I’d use that time to write up the process for installing a launchd daemon using SMAppService. This involves a number of deliberate steps and, while the overall process isn’t too hard — it’s certainly a lot better than with the older SMJobBless — it’s easy to accidentally stray from the path and get very confused.
If you have questions or comments, start a new thread in the App & System Services > Processes & Concurrency subtopic and tag it with Service Management.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Getting Started with SMAppService
This post explains how to use SMAppService to install a launchd daemon. I tested these instructions using Xcode 26.0 on macOS 15.6.1. Things are likely to be slightly different with different Xcode and macOS versions.
Create the container app target
To start, I created a new project:
I choose File > New > Project.
In the template picker, I chose macOS > App.
In options page, I set the Product Name field to SMAppServiceTest [1].
And I selected my team in the Team popup.
And I verified that the Organization Identifier was set to com.example.apple-samplecode, the standard for Apple sample code [1].
I selected SwiftUI in the Interface popup. There’s no requirement to use SwiftUI here; I chose it because that’s what I generally use these days.
And None in the Testing System popup.
And None in the Storage popup.
I then completed the new project workflow.
I configured basic settings on the project:
In the Project navigator, I selected the SMAppServiceTest project.
In the Project editor, I selected the SMAppServiceTest target.
At the top I selected Signing & Capabilities.
In the Signing section, I made sure that “Automatically manage signing” was checked.
And that my team was selected in the Team popup.
And that the bundle ID of the app ended up as com.example.apple-samplecode.SMAppServiceTest.
Still in the Signing & Capabilities tab, I removed the App Sandbox section.
Note It’s possible to use SMAppService to install a daemon from a sandboxed app, but in that case the daemon also has to be sandboxed. That complicates things, so I’m disabling the sandbox for the moment. See Enable App Sandbox, below, for more on this.
Next I tweaked some settings to make it easier to keep track of which target is which:
At the top, I selected the Build Settings tab.
I changed the Product Name build setting from $(TARGET_NAME) to SMAppServiceTest.
On the left, I renamed the target to App.
I chose Product > Scheme > Manage Schemes.
In the resulting sheet, I renamed the scheme from SMAppServiceTest to App, just to keep things in sync.
[1] You are free to choose your own value, of course. However, those values affect other values later in the process, so I’m giving the specific values I used so that you can see how everything lines up.
Create the daemon target
I then created a daemon target:
I chose File > New > Target.
In the template picker, I chose macOS > Command Line Tool.
In the options page, I set the Product Name field to Daemon.
And I selected my team in the Team popup.
And I verified that the Organization Identifier was set to com.example.apple-samplecode, the standard for Apple sample code.
I selected Swift in the Language popup.
And verified that SMAppServiceTest was set in the Project popup.
I clicked Finish.
I configured basic settings on the target:
In the Project navigator, I selected the SMAppServiceTest project.
In the Project editor, I selected the Daemon target.
At the top I selected Signing & Capabilities.
In the Signing section, I made sure that “Automatically manage signing” was checked.
And that my team was selected in the Team popup.
Note The Bundle Identifier field is blank, and that’s fine. There are cases where you want to give a daemon a bundle identifier, but it’s not necessary in this case.
Next I tweaked some settings to make it easier to keep track of which target is which:
At the top, I selected the Build Settings tab.
I changed the Product Name build setting from $(TARGET_NAME) to SMAppServiceTest-Daemon.
I forced the Enable Debug Dylib Support to No.
IMPORTANT To set it to No, you first have to set it to Yes and then set it back to No.
I edited Daemon/swift.swift to look like this:
import Foundation
import os.log
let log = Logger(subsystem: "com.example.apple-samplecode.SMAppServiceTest", category: "daemon")
func main() {
log.log("Hello Cruel World!")
dispatchMain()
}
main()
This just logs a ‘first light’ log message and parks [1] the main thread in dispatchMain().
Note For more about first light log points, see Debugging a Network Extension Provider.
[1] Technically the main thread terminates in this case, but I say “parks” because that’s easier to understand (-:
Test the daemon executable
I selected the Daemon scheme and chose Product > Run. The program ran, logging its first light log entry, and then started waiting indefinitely.
Note Weirdly, in some cases the first time I ran the program I couldn’t see its log output. I had to stop and re-run it. I’m not sure what that’s about.
I chose Product > Stop to stop it. I then switched back the App scheme.
Embed the daemon in the app
I added a build phase to embed the daemon executable into app:
In the Project navigator, I selected the SMAppServiceTest project.
In the Project editor, I selected the App target.
At the top I selected Build Phases.
I added a new copy files build phase.
I renamed it to Embed Helper Tools.
I set its Destination popup to Executables.
I clicked the add (+) button under the list and selected SMAppServiceTest-Daemon.
I made sure that Code Sign on Copy was checked for that.
I then created a launchd property list file for the daemon:
In the Project navigator, I selected SMAppServiceTestApp.swift.
I chose Product > New > File from Template.
I selected the Property List template.
In the save sheet, I named the file com.example.apple-samplecode.SMAppServiceTest-Daemon.plist.
And made sure that the Group popup was set to SMAppServiceTest.
And that only the App target was checked in the Targets list.
I clicked Create to create the file.
In the property list editor, I added two properties:
Label, with a string value of com.example.apple-samplecode.SMAppServiceTest-Daemon
BundleProgram, with a string value of Contents/MacOS/SMAppServiceTest-Daemon
I added a build phase to copy that property list into app:
In the Project navigator, I selected the SMAppServiceTest project.
In the Project editor, I selected the App target.
At the top I selected Build Phases.
I added a new copy files build phase.
I renamed it to Copy LaunchDaemons Property Lists.
I set its Destination popup to Wrapper.
And set the Subpath field to Contents/Library/LaunchDaemons.
I disclosed the contents of the Copy Bundle Resources build phase.
I dragged com.example.apple-samplecode.SMAppServiceTest-Daemon.plist from the Copy Bundle Resources build phase to the new Copy LaunchDaemons Property Lists build phase.
I made sure that Code Sign on Copy was unchecked.
Register and unregister the daemon
In the Project navigator, I selected ContentView.swift and added the following to the imports section:
import os.log
import ServiceManagement
I then added this global variable:
let log = Logger(subsystem: "com.example.apple-samplecode.SMAppServiceTest", category: "app")
Finally, I added this code to the VStack:
Button("Register") {
do {
log.log("will register")
let service = SMAppService.daemon(plistName: "com.example.apple-samplecode.SMAppServiceTest-Daemon.plist")
try service.register()
log.log("did register")
} catch let error as NSError {
log.log("did not register, \(error.domain, privacy: .public) / \(error.code)")
}
}
Button("Unregister") {
do {
log.log("will unregister")
let service = SMAppService.daemon(plistName: "com.example.apple-samplecode.SMAppServiceTest-Daemon.plist")
try service.unregister()
log.log("did unregister")
} catch let error as NSError {
log.log("did not unregister, \(error.domain, privacy: .public) / \(error.code)")
}
}
IMPORTANT None of this is code is structured as I would structure a real app. Rather, this is the absolutely minimal code needed to demonstrate this API.
Check the app structure
I chose Product > Build and verified that everything built OK. I then verified that the app’s was structured correctly:
I then choose Product > Show Build Folder in Finder.
I opened a Terminal window for that folder.
In Terminal, I changed into the Products/Debug directory and dumped the structure of the app:
% cd "Products/Debug"
% find "SMAppServiceTest.app"
SMAppServiceTest.app
SMAppServiceTest.app/Contents
SMAppServiceTest.app/Contents/_CodeSignature
SMAppServiceTest.app/Contents/_CodeSignature/CodeResources
SMAppServiceTest.app/Contents/MacOS
SMAppServiceTest.app/Contents/MacOS/SMAppServiceTest.debug.dylib
SMAppServiceTest.app/Contents/MacOS/SMAppServiceTest
SMAppServiceTest.app/Contents/MacOS/__preview.dylib
SMAppServiceTest.app/Contents/MacOS/SMAppServiceTest-Daemon
SMAppServiceTest.app/Contents/Resources
SMAppServiceTest.app/Contents/Library
SMAppServiceTest.app/Contents/Library/LaunchDaemons
SMAppServiceTest.app/Contents/Library/LaunchDaemons/com.example.apple-samplecode.SMAppServiceTest-Daemon.plist
SMAppServiceTest.app/Contents/Info.plist
SMAppServiceTest.app/Contents/PkgInfo
There are a few things to note here:
The com.example.apple-samplecode.SMAppServiceTest-Daemon.plist property list is in Contents/Library/LaunchDaemons.
The daemon executable is at Contents/MacOS/SMAppServiceTest-Daemon.
The app is still built as debug dynamic library (SMAppServiceTest.debug.dylib) but the daemon is not.
Test registration
I chose Product > Run. In the app I clicked the Register button. The program logged:
will register
did not register, SMAppServiceErrorDomain / 1
Error 1 indicates that installing a daemon hasn’t been approved by the user. The system also presented a notification:
Background Items Added
“SMAppServiceTest” added items that can
run in the background for all users. Do you
want to allow this?
Options > Allow
> Don’t Allow
I chose Allow and authenticated the configuration change.
In Terminal, I verified that the launchd daemon was loaded:
% sudo launchctl list com.example.apple-samplecode.SMAppServiceTest-Daemon
{
"LimitLoadToSessionType" = "System";
"Label" = "com.example.apple-samplecode.SMAppServiceTest-Daemon";
"OnDemand" = true;
"LastExitStatus" = 0;
"Program" = "Contents/MacOS/SMAppServiceTest-Daemon";
};
IMPORTANT Use sudo to target the global launchd context. If you omit this you end up targeting the launchd context in which Terminal is running, a GUI login context, and you won't find any launchd daemons there.
I started monitoring the system log:
I launched the Console app.
I pasted subsystem:com.example.apple-samplecode.SMAppServiceTest into the search box.
I clicked “Start streaming”.
Back in Terminal, I started the daemon:
% sudo launchctl start com.example.apple-samplecode.SMAppServiceTest-Daemon
In Console, I saw it log its first light log point:
type: default
time: 17:42:20.626447+0100
process: SMAppServiceTest-Daemon
subsystem: com.example.apple-samplecode.SMAppServiceTest
category: daemon
message: Hello Cruel World!
Note I’m starting the daemon manually because my goal here is to show how to use SMAppService, not how to use XPC to talk to a daemon. For general advice about XPC, see XPC Resources.
Clean up
Back in the app, I clicked Unregister. The program logged:
will unregister
did unregister
In Terminal, I confirmed that the launchd daemon was unloaded:
% sudo launchctl list com.example.apple-samplecode.SMAppServiceTest-Daemon
Could not find service "com.example.apple-samplecode.SMAppServiceTest-Daemon" in domain for system
Note This doesn’t clean up completely. The system remembers your response to the Background Items Added notification, so the next time you run the app and register your daemon it will be immediately available. To reset that state, run the sfltool with the resetbtm subcommand.
Install an Agent Rather Than a Daemon
The above process shows how to install a launchd daemon. Tweaking this to install a launchd agent is easy. There are only two required changes:
In the Copy Launch Daemon Plists copy files build phase, set the Subpath field to Contents/Library/LaunchAgents.
In ContentView.swift, change the two SMAppService.daemon(plistName:) calls to SMAppService.agent(plistName:).
There are a bunch of other changes you should make, like renaming everything from daemon to agent, but those aren’t required to get your agent working.
Enable App Sandbox
In some cases you might want to sandbox the launchd job (the term job to refer to either a daemon or an agent.) This most commonly crops up with App Store apps, where the app itself must be sandboxed. If the app wants to install a launchd agent, that agent must also be sandboxed. However, there are actually four combinations, of which three are supported:
App Sandboxed | Job Sandboxed | Supported
------------- | ------------- | ---------
no | no | yes
no | yes | yes
yes | no | no [1]
yes | yes | yes
There are also two ways to sandbox the job:
Continue to use a macOS > Command Line Tool target for the launchd job.
Use an macOS > App target for the launchd job.
In the first approach you have to use some low-level build settings to enable the App Sandbox. Specifically, you must assign the program a bundle ID and then embed an Info.plist into the executable via the Create Info.plist Section in Binary build setting.
In the second approach you can use the standard Signing & Capabilities editor to give the job a bundle ID and enable the App Sandbox, but you have to adjust the BundleProgram property to account for the app-like wrapper.
IMPORTANT The second approach is required if your launchd job uses restricted entitlements, that is, entitlements that must be authorised by a provisioning profile. In that case you need an app-like wrapper to give you a place to store the provisioning profile. For more on this idea, see Signing a daemon with a restricted entitlement.
For more background on how provisioning profiles authorise the use of entitlements, see TN3125 Inside Code Signing: Provisioning Profiles.
On balance, the second approach is the probably the best option for most developers.
[1] When SMAppService was introduced it was possible to install a non-sandboxed daemon from a sandboxed app. That option is blocked by macOS 14.2 and later.