如何在 iOS 中使用 Swift 运行命令行命令或任务?



我正在为在 Swift 中运行 iOS 12 或更高版本的越狱设备编写一个 iOS 应用程序。 它是一个包管理器,为了安装包,我需要运行一个dpkg -i [PACKAGE_ID] control命令。

为了实现这一点,我做了以下功能:

func task(launchPath: String, arguments: String) {
let task = CommandLine()
task.launchPath = launchPath
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: String.Encoding.utf8)
return output
}

当我想运行命令时,我像这样调用我的函数:

task(launchPath: "/usr/libexec/Thunderbolt/supersling", arguments: "/usr/bin/dpkg -i" + packageID + "control")

但它一直给我以下错误:

'CommandLine' cannot be constructed because it has no accessible initializers

我一直在互联网上搜索此错误,并且我读到您无法在iOS中运行CommandLine(),但我知道可以运行命令。

我一直在互联网上搜索如何做到这一点,并为Objective-C找到了一些东西:

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/libexec/Thunderbolt/supersling"];
[task setArguments:@[@"/usr/bin/dpkg", @"-I", packageID, @"control"]];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
[task launch];
[task waitUntilExit];
NSFileHandle *read = [pipe fileHandleForReading];
NSData *dataRead = [read readDataToEndOfFile];
NSString *stringRead = [[NSString alloc] initWithData:dataRead encoding:NSUTF8StringEncoding];

这与我在Objective-C中所做的完全相同。

为什么 Xcode 允许运行这个 Objective-C 代码,而 Swift 代码不允许? 还有其他方法可以为 Swift 运行命令吗?

提前谢谢。

编辑:我发现Objective-C代码导入了它自己的NSTask.h头文件:

//#import <Foundation/Foundation-Structs.h>
@class NSURL, NSArray, NSDictionary;
@interface NSTask : NSObject
@property (copy) NSURL * executableURL;
@property (copy) NSArray * arguments;
@property (copy) NSDictionary * environment;
@property (copy) NSURL * currentDirectoryURL;
@property (retain) id standardInput;
@property (retain) id standardOutput;
@property (retain) id standardError;
@property (readonly) int processIdentifier;
@property (getter=isRunning,readonly) BOOL running;
@property (readonly) int terminationStatus;
@property (readonly) long long terminationReason;
@property (copy) id terminationHandler;
@property (assign) long long qualityOfService;
+(id)currentTaskDictionary;
+(id)launchedTaskWithDictionary:(id)arg1 ;
+(id)launchedTaskWithLaunchPath:(id)arg1 arguments:(id)arg2 ;
+(id)launchedTaskWithExecutableURL:(id)arg1 arguments:(id)arg2 error:(out id*)arg3 terminationHandler:(/*^block*/id)arg4 ;
+(id)allocWithZone:(NSZone*)arg1 ;
-(void)waitUntilExit;
-(NSURL *)executableURL;
-(id)currentDirectoryPath;
-(void)setArguments:(NSArray *)arg1 ;
-(void)setCurrentDirectoryPath:(id)arg1 ;
-(id)launchPath;
-(void)setLaunchPath:(id)arg1 ;
-(int)terminationStatus;
-(long long)terminationReason;
-(void)launch;
-(BOOL)launchAndReturnError:(id*)arg1 ;
-(void)setCurrentDirectoryURL:(NSURL *)arg1 ;
-(NSURL *)currentDirectoryURL;
-(void)setExecutableURL:(NSURL *)arg1 ;
-(void)interrupt;
-(long long)suspendCount;
-(void)setStandardInput:(id)arg1 ;
-(void)setStandardOutput:(id)arg1 ;
-(void)setStandardError:(id)arg1 ;
-(id)standardInput;
-(id)standardOutput;
-(id)standardError;
-(id)init;
-(NSDictionary *)environment;
-(BOOL)isRunning;
-(BOOL)suspend;
-(BOOL)resume;
-(void)setEnvironment:(NSDictionary *)arg1 ;
-(void)setQualityOfService:(long long)arg1 ;
-(void)setTerminationHandler:(id)arg1 ;
-(int)processIdentifier;
-(id)terminationHandler;
-(long long)qualityOfService;
-(void)terminate;
-(NSArray *)arguments;
@end

我可以在 Swift 中使用吗?如果可能的话,我该怎么做?

请阅读编辑编号 3

好的,所以基本上我自己想出了如何做到这一点,所以我将发布这个答案,以帮助可能遇到相同问题的人。

请注意,这仅适用于越狱设备

这适用于非越狱和越狱iOS设备

我能够找到的实现此目的的最佳方法是使用自定义的Objective-C头文件,该文件创建了对象NSTask及其所需的一切。

然后,为了在 Swift 中使用此代码,您需要创建一个桥接标头,在其中您需要导入NSTask.hSwift 以将其公开给 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/dpkg", arguments: "-i", packageID, "control")

这也将返回该值,因此您甚至可以通过以下方式显示它:

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

这将打印:

~> Hello, World!

希望这能解决问题。

编辑1:我发现当您使用自定义NSTask对象时,即使在非越狱设备上,您也可以运行该任务。在iPad Mini 2(iOS 12.1 ~>越狱)和iPhone Xr(iOS 12.2 ~>未越狱)上进行测试。

注意:即使这也适用于非越狱设备,您的应用程序也将在AppStore上被拒绝,正如@ClausJ ørgensen所说:

您使用的是私有 API,因此它将在 App Store 上被拒绝。此外,Xcode 11 还有一些新功能,在使用某些私有 API 时会触发构建失败。

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

编辑 2:为此工作并避免抛出NSInternalInconsistencyException,您需要将 launchPath 设置为可执行文件的完整路径,而不仅仅是包含它的目录。

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

工作方法(2020年3月24日)(仅适用于越狱设备)

有一种更简单的方法,粗略推荐而不是上面的方法,用于在越狱的iOS设备上运行CLI命令。

您无法在iOS设备上使用NSTask的原因是您的应用程序已沙盒化,并且在库存iOS上无法避免这种情况。这就是越狱发生的地方:使用theos的新实例创建器(NIC)并创建一个类型为application的新实例,您可以轻松创建非沙盒应用程序。

请注意,此过程用于制作与 Debian 打包程序 (dpkg一起安装的越狱软件包。如果你使用过 Debian,你可能会熟悉这一点)。包被编译为.deb文件。

完成此操作后,您可以在应用程序上轻松使用NSTask,没有任何问题,如下所示:

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/dpkg", arguments: "-i", packageID, "control")

完成应用后,只需使用以下make编译它:

make do #just compile the package
make package #compile the package and save it on the 'packages' folder
make package install #if theos and ssh are configured properly, compile the package and automatically install it on your iPhone.

帮助! 当我在我的iPhone7(iOS13.1 ~>未越狱)中进行测试时,我将命令文件拖到Xcode项目中,并得到这样的文件路径:

let commandPath = Bundle.main.path(forResource: "command", ofType: nil)! 

当我像这样在iPhone中运行时:

task(launchPath: commandPath, arguments:"")

我得到了:

'NSInvalidArgumentException', reason: 'launch path not accessible'

如何为我的命令文件获取正确的路径?

最新更新