How to prevent a Command Line Tool from exiting before asynchronous operation completes
Asked Answered
R

9

56

In a swift 2 command line tool (main.swift), I have the following:

import Foundation
print("yay")

var request = HTTPTask()
request.GET("http://www.stackoverflow.com", parameters: nil, completionHandler: {(response: HTTPResponse) in
    if let err = response.error {
        print("error: \(err.localizedDescription)")
        return //also notify app of failure as needed
    }
    if let data = response.responseObject as? NSData {
        let str = NSString(data: data, encoding: NSUTF8StringEncoding)
        print("response: \(str)") //prints the HTML of the page
    }
})

The console shows 'yay' and then exits (Program ended with exit code: 0), seemingly without ever waiting for the request to complete. How would I prevent this from happening?

The code is using swiftHTTP

I think I might need an NSRunLoop but there is no swift example

Renfrow answered 11/8, 2015 at 14:4 Comment(4)
Does it have to be async?Lope
@Lope not necessarily but am interested in either case, async or not. I decided to try and use github.com/daltoniam/SwiftHTTP as an experimentRenfrow
Possible duplicate of CFRunLoop in Swift Command Line Program (which has a Swift example for NSRunLoop).Dunker
You can use readline() if you are just debugging, it will keep the runloop running waiting for an input. Or you can use it to actually make user quit on their choice checking input against "y" or somethingNecessitous
I
35

I realize this is an old question, but here is the solution I ended on. Using DispatchGroup.

let dispatchGroup = DispatchGroup()

for someItem in items {
    dispatchGroup.enter()
    doSomeAsyncWork(item: someItem) {
        dispatchGroup.leave()
    }
}

dispatchGroup.notify(queue: DispatchQueue.main) {
    exit(EXIT_SUCCESS)
}
dispatchMain()
Incondensable answered 23/6, 2018 at 4:42 Comment(0)
R
44

Adding RunLoop.main.run() to the end of the file is one option. More info on another approach using a semaphore here

Renfrow answered 11/8, 2015 at 14:23 Comment(2)
Swift 4: RunLoop.main.run()Pyotr
Swift 5: RunLoop.current.run(mode: .default, before: .distantFuture) or a simple dead loop while true { }Clos
I
35

I realize this is an old question, but here is the solution I ended on. Using DispatchGroup.

let dispatchGroup = DispatchGroup()

for someItem in items {
    dispatchGroup.enter()
    doSomeAsyncWork(item: someItem) {
        dispatchGroup.leave()
    }
}

dispatchGroup.notify(queue: DispatchQueue.main) {
    exit(EXIT_SUCCESS)
}
dispatchMain()
Incondensable answered 23/6, 2018 at 4:42 Comment(0)
H
19

You can call dispatchMain() at the end of main. That runs the GCD main queue dispatcher and never returns so it will prevent the main thread from exiting. Then you just need to explicitly call exit() to exit the application when you are ready (otherwise the command line app will hang).

import Foundation

let url = URL(string:"http://www.stackoverflow.com")!
let dataTask = URLSession.shared.dataTask(with:url) { (data, response, error) in
    // handle the network response
    print("data=\(data)")
    print("response=\(response)")
    print("error=\(error)")

    // explicitly exit the program after response is handled
    exit(EXIT_SUCCESS)
}
dataTask.resume()

// Run GCD main dispatcher, this function never returns, call exit() elsewhere to quit the program or it will hang
dispatchMain()
Homes answered 8/1, 2017 at 20:44 Comment(5)
This is an elegant solution imo. It has the least cognitive load.Capricorn
Maybe it got down voted because the down voter could not find dispatchMain(). I think that Mike meant dispatch_main().Montherlant
dispatch_main() is for obj-c. In Swift it is dispatchMain() developer.apple.com/documentation/dispatch/1452860-dispatchmainHomes
Xcode 10.1 seems to be bugged when using this and doesn't let you stop the process unless you quit Xcode (kill -9 stops it but Xcode doesn't figure that out). RunLoop.main.run() works howeverJaysonjaywalk
@Capricorn please explain why displatchMain() is a better solution then DispatchSemaphore( value: 0)Finstad
D
13

Don't depend on timing.. You should try this

let sema = DispatchSemaphore(value: 0)

let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_November_2010-1a.jpg")!

let task = URLSession.shared.dataTask(with: url) { data, response, error in
  print("after image is downloaded")

  // signals the process to continue
  sema.signal()
}

task.resume()

// sets the process to wait
sema.wait()
Deerskin answered 18/1, 2017 at 18:20 Comment(1)
Article here was also useful to meDibri
C
7

Swift 4: RunLoop.main.run()

At the end of your file

Castled answered 16/12, 2018 at 0:58 Comment(1)
then it will never exitRandi
N
6

If your need isn't something that requires "production level" code but some quick experiment or a tryout of a piece of code, you can do it like this :

SWIFT 3

//put at the end of your main file
RunLoop.main.run(until: Date(timeIntervalSinceNow: 15))  //will run your app for 15 seconds only

More info : https://mcmap.net/q/425639/-using-nsurlsession-from-a-swift-command-line-program


Please note that you shouldn't rely on fixed execution time in your architecture.

Nurmi answered 29/11, 2016 at 16:0 Comment(4)
Hard-coded time intervals for asynchronous tasks are never a good idea. The command line interface should run the loop (without timeout) and stop it explicitly after returning from the completion block. Any timeout is supposed to be controlled by the HTTPTask or URLSession class.Skeie
As described in NOTES section of my original answer ;)Hirsch
can sleep(15) do the same trick? I am doing this way in CodeRunnerOxidize
Just to add onto this: To keep it running indefinitely you can use Date.distantFuture.Zaidazailer
S
1

Nowadays, we would use Swift concurrency and simply await the async task. E.g.,

do {
    guard let url = URL(string: "https://stackoverflow.com") else {
        throw URLError(.badURL)
    }

    let (data, _) = try await URLSession.shared.data(from: url)
    if let string = String(data: data, encoding: .utf8) {
        print(string)
    } else {
        print("Unable to generate string representation")
    }
} catch {
    print(error)
}

Unlike traditional completion handler patterns, if you await an async task, the command line app will not terminate before the asynchronous task is done.

For more information, see WWDC 2021 video Meet async/await or any of the “Related videos” listed on that page.

Scotopia answered 16/7, 2023 at 15:59 Comment(0)
C
0
// Step 1: Add isDone global flag

var isDone = false
// Step 2: Set isDone to true in callback

request.GET(...) {
    ...
    isDone = true
}

// Step 3: Add waiting block at the end of code

while(!isDone) {
    // run your code for 0.1 second
    RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.1))
}
Collimate answered 23/9, 2020 at 7:11 Comment(0)
S
0

In addition to Rob's answer nowadays (Swift 5.5+) there is a convenient way to create an asynchronous command line interface

@main
struct AsyncCLI { // the name is arbitrary 
    static func main() async throws {
        // your code goes here
    }
}

Important:

  • The enclosing file must not be named main.swift
Skeie answered 3/9, 2023 at 8:38 Comment(2)
If you find yourself posting the same answer to multiple questions then it seems it would be better to close the other questions as duplicates.Humbertohumble
@Humbertohumble I'm sorry, I didn't remember that.Skeie

© 2022 - 2025 — McMap. All rights reserved.