Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active April 23, 2024 23:00
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mminer/be55bcdf7c4ff004ecafba6a664addc5 to your computer and use it in GitHub Desktop.
Save mminer/be55bcdf7c4ff004ecafba6a664addc5 to your computer and use it in GitHub Desktop.
Components of XPC service.
import Foundation
let delegate = MyServiceDelegate()
let listener = NSXPCListener.service()
listener.delegate = delegate
listener.resume()
import Foundation
class MyService: NSObject, MyServiceProtocol {
func upperCaseString(_ string: String, withReply reply: @escaping (String) -> Void) {
let response = string.uppercased()
reply(response)
}
}
import Foundation
class MyServiceDelegate: NSObject, NSXPCListenerDelegate {
func listener(_ listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
let exportedObject = MyService()
newConnection.exportedInterface = NSXPCInterface(with: MyServiceProtocol.self)
newConnection.exportedObject = exportedObject
newConnection.resume()
return true
}
}
import Foundation
@objc public protocol MyServiceProtocol {
func upperCaseString(_ string: String, withReply reply: @escaping (String) -> Void)
}
import MyService
...
let connection = NSXPCConnection(serviceName: "com.matthewminer.MyService")
connection.remoteObjectInterface = NSXPCInterface(with: MyServiceProtocol.self)
connection.resume()
let service = connection.remoteObjectProxyWithErrorHandler { error in
print("Received error:", error)
} as? MyServiceProtocol
service?.upperCaseString("Hello XPC") { response in
print("Response from XPC service:", response)
}
@ben-z
Copy link

ben-z commented Apr 14, 2020

I also just ran into this error:

Domain=NSCocoaErrorDomain Code=4099 "The connection to service on pid 0 named <service-name> was invalidated."

It turns out I just misspelled the service name when initializing the NSXPCConnection. Hope this saves someone a few hours of debugging lol.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment