0

Alamofire's callback block cannot run, i'm sure the server received the request send by Alamofire here‘s the code:

import Alamofire
import Foundation

@main
public struct SwiftClient {

    public static func main() {
        let url = "http://127.0.0.1:8080/hello"
        AF.request(url).response { response in
            debugPrint(response)
        }
        sleep(10)
    }
}

when i execute swift run, debugPrint doesn't run

Jack
  • 1
  • It's a "script", so the program will end before the callback is called. Either use `async` (see https://www.hackingwithswift.com/quick-start/concurrency/how-to-make-async-command-line-tools-and-scripts or https://stackoverflow.com/questions/71298098/swift-async-method-call-for-a-command-line-app) or keep the "program alive" https://stackoverflow.com/questions/31944011/how-to-prevent-a-command-line-tool-from-exiting-before-asynchronous-operation-co – Larme Jul 04 '23 at 11:47

1 Answers1

0

If you're creating a command line tool with @main, I suggest using the async form so you can use Alamofire's async APIs, it will be a much nicer experience.

@main
struct SwiftClient {
    static func main() async {
        let url = "http://127.0.0.1:8080/hello"
        let task = AF.request(url).serializingData()
        debugPrint(await task.response)
    }
}

If you're still not getting a response you can log your requests using an Alamofire EventMonitor, use a proxy tool like Proxyman, or a network inspector like Wireshark.

Jon Shier
  • 12,200
  • 3
  • 35
  • 37
  • Thanks, Jon. Your code works good. But i'm really curious why the callback in my code doesn't called. – Jack Jul 07 '23 at 15:45
  • Not sure. If your request was taking more than your `sleep` time, the process would have finished before your handler was called. With the await version it will stay alive exactly as long as necessary for the request to finish or timeout. – Jon Shier Jul 07 '23 at 19:33
  • I start the service on the same device. I'm quite sure the sleep time is long enough. Even it sleep 100 seconds, the callback still not called. – Jack Jul 08 '23 at 08:30
  • Ah, it may also be that `dispatchMain()` wasn't called to start up the main run loop, which Alamofire calls its default completions on. I believe Swift concurrency starts that for you. – Jon Shier Jul 10 '23 at 20:55