How do I make an HTTP request in Swift?

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

    Using URLSession + Swift 5

    Just adding to cezar's answer, if you want to make web request using Apple's URLSession class, there are multiple way to do the task

    1. Simple GET Request with URL
    2. Simple GET Request with URL and Parameters
    3. Simple GET Request with URL with Error Handlings
    4. Simple POST Request with URL, Parameters with Error Handlings

    1. Simple GET Request with URL

    func simpleGetUrlRequest()
        {
            let url = URL(string: "https://httpbin.org/get")!
    
            let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
                guard let data = data else { return }
                print("The response is : ",String(data: data, encoding: .utf8)!)
                //print(NSString(data: data, encoding: String.Encoding.utf8.rawValue) as Any)
            }
            task.resume()
        }
    

    Note : Make sure You must add "NSAppTransportSecurity" key in pList for http requests

    NSAppTransportSecurity
    
    NSAllowsArbitraryLoads
    
    
    

    2. Simple GET Request with URL and Parameters

    func simpleGetUrlWithParamRequest()
        {
            let url = URL(string: "https://www.google.com/search?q=peace")!
            
            let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
                
                if error != nil || data == nil {
                    print("Client error!")
                    return
                }
                guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                    print("Server error!")
                    return
                }
                print("The Response is : ",response)
            }
            task.resume()
        }
    

    3. Simple GET Request with URL with Error Handlings

    func simpleGetUrlRequestWithErrorHandling()
        {
            let session = URLSession.shared
            let url = URL(string: "https://httpbin.org/get")!
            
            let task = session.dataTask(with: url) { data, response, error in
                
                if error != nil || data == nil {
                    print("Client error!")
                    return
                }
                
                guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                    print("Server error!")
                    return
                }
                
                guard let mime = response.mimeType, mime == "application/json" else {
                    print("Wrong MIME type!")
                    return
                }
                
                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: [])
                    print("The Response is : ",json)
                } catch {
                    print("JSON error: \(error.localizedDescription)")
                }
                
            }
            task.resume()
        }
    

    4. Simple POST Request with URL, Parameters with Error Handlings.

    func simplePostRequestWithParamsAndErrorHandling(){
            let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 30
            configuration.timeoutIntervalForResource = 30
            let session = URLSession(configuration: configuration)
            
            let url = URL(string: "https://httpbin.org/post")!
            
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            
            let parameters = ["username": "foo", "password": "123456"]
            
            do {
                request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
            } catch let error {
                print(error.localizedDescription)
            }
            
            let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
                
                if error != nil || data == nil {
                    print("Client error!")
                    return
                }
                
                guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                    print("Oops!! there is server error!")
                    return
                }
                
                guard let mime = response.mimeType, mime == "application/json" else {
                    print("response is not json")
                    return
                }
                
                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: [])
                    print("The Response is : ",json)
                } catch {
                    print("JSON error: \(error.localizedDescription)")
                }
                
            })
            
            task.resume()
        }
    

    Your suggestions are appreciated!!

提交回复
热议问题