How do I make an HTTP request in Swift?

前端 未结 20 1071
不知归路
不知归路 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 05:59

    You can use URL, URLRequest and URLSession or NSURLConnection as you'd normally do in Objective-C. Note that for iOS 7.0 and later, URLSession is preferred.

    Using URLSession

    Initialize a URL object and a URLSessionDataTask from URLSession. Then run the task with resume().

    let url = URL(string: "http://www.stackoverflow.com")!
    
    let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
        guard let data = data else { return }
        print(String(data: data, encoding: .utf8)!)
    }
    
    task.resume()
    

    Using NSURLConnection

    First, initialize a URL and a URLRequest:

    let url = URL(string: "http://www.stackoverflow.com")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST" 
    

    Then, you can load the request asynchronously with:

    NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {(response, data, error) in
        guard let data = data else { return }
        print(String(data: data, encoding: .utf8)!)
    }
    

    Or you can initialize an NSURLConnection:

    let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)
    

    Just make sure to set your delegate to something other than nil and use the delegate methods to work with the response and data received.

    For more detail, check the documentation for the NSURLConnectionDataDelegate protocol

    Testing on an Xcode playground

    If you want to try this code on a Xcode playground, add import PlaygroundSupport to your playground, as well as the following call:

    PlaygroundPage.current.needsIndefiniteExecution = true
    

    This will allow you to use asynchronous code in playgrounds.

提交回复
热议问题