How do I make an HTTP request in Swift?

前端 未结 20 1408
不知归路
不知归路 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

    You can use Just, a python-requests style HTTP library.

    Some example of sending HTTP request with Just:

    // synchronous GET request with URL query a=1
    let r = Just.get("https://httpbin.org/get", params:["a":1])
    
    // asynchronous POST request with form value and file uploads
    Just.post(
        "http://justiceleauge.org/member/register",
        data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
        files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
    ) { (r)
        if (r.ok) { /* success! */ }
    }
    

    In both cases, the result of a request r can be accessed in ways similar to python-request:

    r.ok            // is the response successful?
    r.statusCode    // status code of response
    r.content       // response body as NSData?
    r.text          // response body as text?
    r.json          // response body parsed by NSJSONSerielization
    

    You can find more examples in this playground

    Using this library in synchronous mode in a playground is the closest thing to cURL one can get in Swift.

提交回复
热议问题