How to perform a curl request in swift?

后端 未结 1 1810
夕颜
夕颜 2021-02-08 01:22

I am trying to use an external API, which has an API request that is like the following. I am used to requests with just one url, but what do I do with the \"H\" and the \"d\" a

相关标签:
1条回答
  • 2021-02-08 02:20

    This is an example of how you can translate the curl command into URLRequest:

    guard let url = URL(string: "https://api.lucidtech.ai/v0/receipts"),
        let payload = "{\"documentId\": \"a50920e1-214b-4c46-9137-2c03f96aad56\"}".data(using: .utf8) else
    {
        return
    }
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("your_api_key", forHTTPHeaderField: "x-api-key")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = payload
    
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        guard error == nil else { print(error!.localizedDescription); return }
        guard let data = data else { print("Empty data"); return }
    
        if let str = String(data: data, encoding: .utf8) {
            print(str)
        }
    }.resume()
    
    0 讨论(0)
提交回复
热议问题