skip to Main Content

I have a weird problem with HTTP requests in Swift. I have the following simple code:

let session = URLSession.shared
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!

let task = session.dataTask(with: url, completionHandler: { data, response, error in
    // Check the response
            print(error)
            print(response)
})
task.resume()

Running this code in a Xcode playground outputs the print statements. However, executing it in a standard Xcode project does not give any output.
I wonder if I am missing something in my code or if something is wrong with my Xcode setup.

Thanks in advance!

Edit:

Here’s a screenshot of Xcode
enter image description here

2

Answers


  1. Looking at this screenshot –
    enter image description here

    It doesn’t seem like any part of your code is executing at all. There’s no entry point defined.

    You can try following –

    @main
    struct NewApp {
        static func main() {
            // Paste all of your code here
            // Put breakpoints and inspect what you want
        }
    }
    
    Login or Signup to reply.
  2. As Tarun indicated, your executable is exiting before your call can be made. One way you can wait before exiting is to use a DispatchGroup like the following.

    let session = URLSession.shared
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
    let group = DispatchGroup()
    group.enter()
    let task = session.dataTask(with: url, completionHandler: { data, response, error in
        // Check the response
        print(error)
        print(response)
        group.leave()
    })
    task.resume()
    group.wait()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search