How do I make an HTTP request in Swift?

前端 未结 20 1335
不知归路
不知归路 2020-11-22 05:10

I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes

20条回答
  •  青春惊慌失措
    2020-11-22 06:01

    For XCUITest to stop the test finishing before the async request completes use this (maybe reduce the 100 timeout):

    func test_api() {
        let url = URL(string: "https://jsonplaceholder.typicode.com/posts/42")!
        let exp = expectation(description: "Waiting for data")
        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            print(String(data: data, encoding: .utf8)!)
            exp.fulfill()
        }
        task.resume()
        XCTWaiter.wait(for: [exp], timeout: 100)
    }
    

提交回复
热议问题