How do I make an HTTP request in Swift?

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

    Swift 4 and above : Data Request using URLSession API

       //create the url with NSURL
       let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! //change the url
    
       //create the session object
       let session = URLSession.shared
    
       //now create the URLRequest object using the url object
       let request = URLRequest(url: url)
    
       //create dataTask using the session object to send data to the server
       let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    
           guard error == nil else {
               return
           }
    
           guard let data = data else {
               return
           }
    
          do {
             //create json object from data
             if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
             }
          } catch let error {
            print(error.localizedDescription)
          }
       })
    
       task.resume()
    

    Swift 4 and above, Decodable and Result enum

    //APPError enum which shows all possible errors
    enum APPError: Error {
        case networkError(Error)
        case dataNotFound
        case jsonParsingError(Error)
        case invalidStatusCode(Int)
    }
    
    //Result enum to show success or failure
    enum Result {
        case success(T)
        case failure(APPError)
    }
    
    //dataRequest which sends request to given URL and convert to Decodable Object
    func dataRequest(with url: String, objectType: T.Type, completion: @escaping (Result) -> Void) {
    
        //create the url with NSURL
        let dataURL = URL(string: url)! //change the url
    
        //create the session object
        let session = URLSession.shared
    
        //now create the URLRequest object using the url object
        let request = URLRequest(url: dataURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
    
        //create dataTask using the session object to send data to the server
        let task = session.dataTask(with: request, completionHandler: { data, response, error in
    
            guard error == nil else {
                completion(Result.failure(AppError.networkError(error!)))
                return
            }
    
            guard let data = data else {
                completion(Result.failure(APPError.dataNotFound))
                return
            }
    
            do {
                //create decodable object from data
                let decodedObject = try JSONDecoder().decode(objectType.self, from: data)
                completion(Result.success(decodedObject))
            } catch let error {
                completion(Result.failure(APPError.jsonParsingError(error as! DecodingError)))
            }
        })
    
        task.resume()
    }
    

    example:

    //if we want to fetch todo from placeholder API, then we define the ToDo struct and call dataRequest and pass "https://jsonplaceholder.typicode.com/todos/1" string url.

    struct ToDo: Decodable {
        let id: Int
        let userId: Int
        let title: String
        let completed: Bool
    
    }
    
    dataRequest(with: "https://jsonplaceholder.typicode.com/todos/1", objectType: ToDo.self) { (result: Result) in
        switch result {
        case .success(let object):
            print(object)
        case .failure(let error):
            print(error)
        }
    }
    

    //this prints the result:

    ToDo(id: 1, userId: 1, title: "delectus aut autem", completed: false)
    

提交回复
热议问题