首页 > 解决方案 > 如何检查程序是否在 Swift 中以管理员权限运行

问题描述

我正在尝试在 Swift 中为我的程序制作安装脚本(这也是在 Swift 中制作的)。

它所做的只是在其中创建一个新文件夹,Library/然后在其中克隆 GitHub 存储库。

问题是,做任何事情都Library/需要管理员权限。这就是为什么我想检查程序是否以管理员权限运行,所以如果没有,抛出一个错误,告诉用户使用sudo.

我的代码:

import Foundation
import Darwin

@discardableResult
func shell(_ args: String...) -> Int32 {
    let task = Process()
    task.launchPath = "/usr/bin/env"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus
}

func Main() {
    if CommandLine.arguments[0] == "sudo" { //I tried by using this, but it seems that sudo doesn't appear in CommandLine.arguments
        print("Welcome to the MoonFish installation... This will install MoonFish on /Library/MoonFish/ using 59.37 MB")
        shell("mkdir", "/Library/MoonFish")
        shell("git", "clone https://github.com/iAlex11/MoonFish.git /Library/MoonFish/") //clones MoonFish repo
    } else {
        print("\u{001B}[1;31mError:\u{001B}[0;0m Please run this program using sudo. Example: sudo ./install")
        exit(0)
    }
}

Main()

标签: swiftcommand-line

解决方案


Apple 不允许通过Process.

我推荐使用 AppleScript。

  • 启动脚本编辑器。
  • 复制并粘贴此代码。

    try
        display dialog "Welcome to the MoonFish installation... This will install MoonFish on /Library/MoonFish/ using 59.37 MB" buttons {"Cancel", "Install"} default button 2
        do shell script "/bin/mkdir /Library/MoonFish" with administrator privileges
        do shell script "/usr/bin/git clone https://github.com/iAlex11/MoonFish.git /Library/MoonFish/" with administrator privileges
    on error
        quit
    end try
    
  • enter

  • 从菜单中File选择Export
  • 在对话框中检查Run OnlyApplicationFile Format弹出窗口中选择。
  • 指定文件名和位置,然后按Save

您甚至可以使用自定义图标。替换./Contents/Resources/applet.icns为另一个applet.icns文件。


推荐阅读