swift - 我不能在函数中使用 Process

标签 swift process

我有一个问题我想使用函数 Process() 但是当我在一个函数中调用它时我得到了

Use of unresolved identifier 'Process'

但是当我在我的代码中直接调用它时它起作用了。 有人知道为什么吗?

最佳答案

由于您既没有提到您的目标平台也没有提供任何类型的代码,您需要注意以下事项:

  1. Process() 在 Swift 3.0 中被重命名为 CommandLine()
  2. 如果您的目标是 iOS,CommandLine() 不可用,因此您需要执行以下操作:

在 iOS 上使用 NSTask():

实现此目的的最佳方法,或者至少是我最喜欢的方法(我也没有找到任何其他方法来做到这一点),是使用 custom Objective-C header file它创建对象 NSTask() 和它需要的一切。

然后,为了在 Swift 中使用此代码,您需要创建一个 Bridging-Header ,您需要在其中导入 NSTask.h 以使其暴露给 Swift 并能够在您的 Swift 代码中使用它。

完成此操作后,只需在代码中使用以下函数即可运行任务:

func task(launchPath: String, arguments: String...) -> NSString {
    let task = NSTask.init()
    task?.setLaunchPath(launchPath)
    task?.arguments = arguments

    // Create a Pipe and make the task
    // put all the output there
    let pipe = Pipe()
    task?.standardOutput = pipe

    // Launch the task
    task?.launch()
    task?.waitUntilExit()

    // Get the data
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

    return output!
}

然后这样调用它:

task(launchPath: "/usr/bin/echo", arguments: "Hello World")

这也会返回值,因此您甚至可以通过执行以下操作来显示它:

print(task(launchPath: "/usr/bin/echo", arguments: "Hello, World!"))

将打印:

~> Hello, World!

为了让它工作而不抛出 NSInternalInconsistencyException,您需要将 launchPath 设置为可执行文件的完整路径,而不是仅包含它的目录。

您还需要设置所有由逗号 分隔的命令参数。

在 iPad Mini 2(iOS 12.1 ~> 越狱)和 iPhone Xr(iOS 12.2 ~> 未越狱)上测试。

注意:尽管这在非越狱和越狱设备上都有效,但您的应用程序将在 AppStore 上被拒绝,因为 @ClausJørgensen说:

You're using private APIs, so it'll be rejected on the App Store. Also, Xcode 11 has some new functionality that will trigger a build failure when using certain private APIs.

我只建议将此用于不会上传到 App Store 的应用程序,否则,尝试在不使用命令的情况下实现您想要的,肯定会有任何其他方法可以做到这一点。

如果您的应用针对越狱的 iOS 设备,并且将被上传到第三方商店,如 Cydia、Zebra、Thunderbolt 或 Sileo,那么这将正常工作。

关于swift - 我不能在函数中使用 Process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46194704/

相关文章:

ios - 使用数组数据更新 TableView

linux - 如何增加/proc/pid/cmdline 4096 字节限制?

ios - 根据三个变量对数组进行排序

swift - 使用 Swift 从 yaml block 中删除行

swift - 水平线 (NSBox) 删除背景阴影 - Swift

swift - 如何使用 SwiftUI View 代替 TableView 单元格

c - 如何创建进程间通信的全局窗口?

python - 运行我的 watch 应用程序之外的应用程序

c - 是否可以将密码传递给需要 root 权限的进程

linux - 两个管道程序,一个在另一个被杀死后继续运行