23
votes

Here is a simple swift script:

#!/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)

I added this script as build phase(before 'compile sources phase) in iOS project but XCode failed to build project with error 'undefined NSTask()...' When I added same script in OSX project, XCode build project without any errors.

Question is why XCode is looking for NSTask inside iOS framework(where doesn't exists) instead to run swift script as platform script(like bash)?

Just to add: swift script isn't included into project with other files to compile. It's just added into build phase, even before compilation, of other source files(which are objective-c files) to run it.

Any ideas how to run custom swift script from iOS XCode project when script contains classes which aren't part of iOS framework?

3
can you explain how add this script to build phase?john07

3 Answers

30
votes

When building for iOS the implicit SDK for xcrun is the iOS SDK, so you have the change it to the Mac OS X SDK with a command line parameter. Change the first line in your script to:

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

+1 for @Mats's answer.

For anyone who get an error like *** is only available on OS X 10.11 or newer.

You can:

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

UPDATE 1:

If you don't get ready for Swift 3, but you are using Xcode 8, you can also control toolchain version:

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

So:

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

also checkout answers here: https://stackoverflow.com/a/36254848/1298043

2
votes

If you unset the SDKROOT environment variable before calling the swift script, it will then use the OS X sdk.