In Xcode, the code that works in Playground does not run properly in the CommandLineTool project.

Asked 2 years ago, Updated 2 years ago, 117 views

I wrote a simple code to make a GET request to githubAPI as follows.

import Foundation

Let url=URL (string: "https://api.github.com/users/( hidden characters)"!
let get = URLSession.shared.dataTask(with:url, completionHandler: {data, response, error in)
    iflet error = error {
        print(error.localizedDescription)
        return
    }

    guard let data = data,
          let response = response as ?HTTPURLResponse else {
        print("data or response is nil")
        return
    }

    if response.statusCode==200 {
        print(String(data:data, encoding:.utf8))
    } else{
        print("statusCode:\(response.statusCode)")
    }
})

get.resume()

When I run this code in Playground, I get a successful value back, but when I select CommandLineTool when I create a project, it runs without errors, but I get no value back.(Even if you can't get it, something should be printed, but it only says program ended with exit code:0) Please give me a solution.

Xcode 13.3
macOS 12.3.1

swift xcode https

2022-09-30 19:30

1 Answers

If you add the following to the last line, the program will no longer exit, and you can see that asynchronous ones will also run.

RunLoop.main.run()


2022-09-30 19:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.