2

I try to start a command file from my app, so I need to use "posix_spawn". But usage of this requires strange use of pointers. I didn't find any example of Swift (3.0), only C++ or Objective C which I couldn't translate.

I simply need something like that (in old system call):

let err = system("ls -param >file.txt")

Any ideas?

Edit: The linked solution didn't match. First it does not use posix_spawn function, which was mentioned by the complier. It uses NSTask, which seems also be abandoned. But I tried this example and ended up in:

func shell(launchPath: String, arguments: [String]) -> String
{
    let task = Process()
    task.launchPath = launchPath
    task.arguments = arguments

    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String

    return output
}

Here all changes needed for XCode 8 were made. But when calling, it will never return from ".launch()".

Somewhere in Output debug window I found this line:

2016-09-15 15:06:36.793 DSRenamer[96562:2569582] launch path not accessible

Same command works fine in terminal window:

/usr/local/bin/ExifTool -ext .CR2
Peter71
  • 2,180
  • 4
  • 20
  • 33
  • 1
    Possible duplicate of [How do I run an terminal command in a swift script? (e.g. xcodebuild)](http://stackoverflow.com/questions/26971240/how-do-i-run-an-terminal-command-in-a-swift-script-e-g-xcodebuild) – Craig Otis Sep 15 '16 at 12:31
  • I added a comment above. – Peter71 Sep 15 '16 at 13:05
  • 1
    NSTask is not abandoned, it just has been renamed to Process in Swift 3. You are probably not calling it correctly. `"/usr/local/bin/ExifTool"` should be the launch path, and `["-ext", ".CR2"]` the argument array. – Martin R Sep 15 '16 at 13:38
  • `task.waitUntilExit()` will block until the `Process` task is finished. The resulting status can be checked with `if task.terminationStatus == 0 { print("Task succeeded.") }` – marc-medley Dec 11 '16 at 06:08

1 Answers1

0

I use swift to call the objective-c menthod(though not the best way)

  1. define an objective-c util menthod

    #import "SystemTaskHelper.h"
    @implementation SystemTaskHelper
    +(void)performSystemTask:(NSString *)task
    {
        system([task UTF8String]);
    }
    @end
    
  2. import objective-c util.h into Bridging-Header.h , and in swift use SystemTaskHelper.performSystemTask("ls -param >file.txt")