I'm trying to make a simple GET request to a localhost server on my machine. I run the following in the Swift REPL:
import Foundation
let session = URLSession.shared
let url = URL(string: "http://localhost:4000")!
let task = session.dataTask(with: url) { data, response, error in
print(data)
print(response)
print(error)
}
task.resume()
however, nothing happens. I don't get anything printed out and I don't see any request activity on my localhost web server. Is there something that I'm missing to make the request?
First off, I think you might want to do http://"YourMacName".local:3000 (you can find the exact name in System Preferences > Sharing). Moreover, URLSession requires all HTTP requests to use HTTPS unless exempt from App Transport Security in the Info.plist file:
which should print "hello" after 1 second never does. You'll need to run some function that "hangs" to keep the program running. If after the above you type say sleep(4), then it'll suddenly work.
See here
$ swift
Welcome to Apple Swift version 5.4 (swiftlang-1205.0.22.2 clang-1205.0.19.29).
Type :help for assistance.
1> import Dispatch
2> DispatchQueue.global().asyncAfter(deadline: .now() + 1) { print("hello") }
[ you can wait for a long time here, nothing will happen]
3> sleep(4) // this unblocks it because it resumes the process
hello
$R0: UInt32 = 0
URLSession will have a similar issue unless you win the race and the server responds super quickly (ie. before LLDB pauses the process).