Using FileManager i want to delete some files under /Library/launchAgents from my Swift Application, how can i give authorised privileges to do it

I am using below piece of code to delete a file



if FileManager.default.fileExists(atPath: Path)
                {
                    do
                    {
                        try FileManager.default.removeItem(atPath: Path)
                    }
                    catch
                    {
                        print(error)
                    }
                }

Path is /Library/LaunchAgents/com.example.agent.plist


I am getting below error



Error Domain=NSCocoaErrorDomain Code=513 "“com.example.agent.plist” couldn’t be removed because you don’t have permission to access it." UserInfo={NSFilePath=/Library/LaunchAgents/com.example.agent.plist, NSUserStringVariant=(

Remove

), NSUnderlyingError=0x600000c76af0 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}}



How can i delete a file with admininistrative priveleges from swift.

Is there a way i can do without involving apple scripts and shell scripts using native swift?

Replies

macOS does not provide a built-in way for non-privileged code to perform privileged file system operations [1]. The standard approach here is to factor your privileged code out into a small helper tool and then install that helper tool as a daemon using

SMJobBless
. This is, alas, not for the faint of heart. If you want to tackle it, the best place to start is EvenBetterAuthorizationSample.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

[1] Other than the

NSWorkspaceAuthorization
thing, which doesn’t support a delete operation.