从Xcode iOS项目运行swift脚本作为构build阶段

这是一个简单的swift脚本:

#!/usr/bin/env xcrun swift import Foundation let task = NSTask() task.launchPath = "/bin/echo" task.arguments = ["farg1", "arg2"] let pipe = NSPipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) print(output) 

我在iOS项目中添加了这个脚本作为构build阶段(在编译源码阶段之前),但是XCode无法生成错误为'undefined NSTask()…'的项目当我在OSX项目中添加相同的脚本时,XCode生成项目没有任何错误。

问题是为什么XCode在iOS框架(不存在)中寻找NSTask而不是运行swift脚本作为平台脚本(如bash)?

只需添加:swift脚本不包含在项目中与其他文件编译。 它只是在编译之前添加到其他源文件(它们是objective-c文件)来运行它。

任何想法如何从iOS XCode项目运行自定义的快速脚本,当脚本包含的类不是iOS框架的一部分?

在为iOS构build时,隐式SDK for xcrun是iOS SDK,因此您可以使用命令行参数将其更改为Mac OS X SDK。 将脚本中的第一行更改为:

 #!/usr/bin/env xcrun --sdk macosx swift 

@Mats的答案+1。

对于像*** is only available on OS X 10.11 or newer这样的错误, *** is only available on OS X 10.11 or newer

您可以:

 #!/usr/bin/env xcrun --sdk macosx swift -target x86_64-macosx10.11 

更新1:

如果你没有准备好Swift 3,但是你正在使用Xcode 8,你还可以控制工具链版本:

 xcrun --toolchain com.apple.dt.toolchain.Swift_2_3 -f swift 

所以:

 #!/usr/bin/env xcrun --toolchain com.apple.dt.toolchain.Swift_2_3 --sdk macosx swift -target x86_64-macosx10.11 

还签出答案在这里: https : //stackoverflow.com/a/36254848/1298043

如果在调用swift脚本之前先取消设置SDKROOT环境variables,那么它将使用OS X sdk。