25

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?

xezo
  • 293
  • 3
  • 6

3 Answers3

34

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
Mats
  • 8,528
  • 1
  • 29
  • 35
  • Thanks, that is a solution. By default swift is using iOS framework but I need it osx, – xezo Jun 24 '15 at 07:45
  • @Mats Seems like swift defaults to iOS also if I'm not using xcrun but just /usr/bin/swift. It even tries iOS with "env -i". How does it know? I'd like my script to rely just on swift, not on Xcode. – Jaka Jančar Jun 05 '16 at 06:03
7

+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

Community
  • 1
  • 1
Puttin
  • 1,596
  • 23
  • 27
3

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

Ben Lings
  • 28,823
  • 13
  • 72
  • 81
  • How does one go about doing that ? Also, I guess that if I'm running this script before the 'Compile Sources', I will need to set it back to using the iOS sdk? – Skwiggs Apr 27 '19 at 12:31
  • Checked with XCode11.4 and it is no need to set it back to iOS SDK. – Bill Chan Apr 17 '20 at 10:44