osx - How to programmatically delete a file with elevated privileges?

大憨熊 提交于 2019-12-01 05:27:37

问题


I'm trying to remove a file form the ~/Library/PreferencePanes folder, and this cannot be done with normal privileges. Usually, if you need to delete any file from the ~/Library folder the system will ask for your username and password.

The current way I do this is with

[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]

but this keeps on returning an error ([error localizedDescription]):

theAppName.prefPane couldn’t be removed because you don’t have permission to access it.

What logic and code would I need to use in order to gain these elevated privileges needed for deleting files?

Thanks!


回答1:


You should go through the Authorization Services Programming Guide. You will need to use AuthorizationExecuteWithPrivileges.




回答2:


The only method I could find and which worked for me was to create a command line tool in Xcode. Install the tool as a Launchd Job using SMJOBBLESS and then use XPC connection to talk to it. Follow the below EvenBetterAuthorization sample to understand how all of the above works.

https://developer.apple.com/library/mac/samplecode/EvenBetterAuthorizationSample/Listings/Read_Me_About_EvenBetterAuthorizationSample_txt.html#//apple_ref/doc/uid/DTS40013768-Read_Me_About_EvenBetterAuthorizationSample_txt-DontLinkElementID_17



来源:https://stackoverflow.com/questions/6267197/osx-how-to-programmatically-delete-a-file-with-elevated-privileges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!