Using URLSession in the REPL?

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?

1 Like

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:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Since you're using the REPL though I'm not sure you have access to the Info.plist file.

@nikitamounier thanks for replying, I tried https://google.com instead and I get the same result. Nothing printed out.

You might want to do https://www.google.com, that worked for me.

1 Like

Ah, that makes sense. URLSession is likely not following the 301 redirect. Thanks!

1 Like

I think your problem may be that the process is stopped when you're on the REPL prompt.

Notice how

import Dispatch
DispatchQueue.global().asyncAfter(deadline: .now() + 1) { print("hello") }

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).

Terms of Service

Privacy Policy

Cookie Policy