Make REST API call in Swift

前端 未结 15 1380
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 04:20

I\'m trying to use Swift to make a GET call to a REST API, and have tried to follow numerous tutorials, but can\'t figure it out. Either because I cannot figure out how to

15条回答
  •  心在旅途
    2020-12-02 04:43

    Swift 5

    API call method

    //Send Request with ResultType
        func fetch(requestURL:URL,requestType:String,parameter:[String:AnyObject]?,completion:@escaping (Result) -> () ){
            //Check internet connection as per your convenience
            //Check URL whitespace validation as per your convenience
            //Show Hud
            var urlRequest = URLRequest.init(url: requestURL)
            urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
            urlRequest.timeoutInterval = 60
            urlRequest.httpMethod = String(describing: requestType)
            urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
            
            //Post URL parameters set as URL body
            if let params = parameter{
                do{
                    let parameterData = try JSONSerialization.data(withJSONObject:params, options:.prettyPrinted)
                    urlRequest.httpBody = parameterData
                }catch{
                   //Hide hude and return error
                    completion(.failure(error))
                }
            }
            //URL Task to get data
            URLSession.shared.dataTask(with: requestURL) { (data, response, error) in
                //Hide Hud
                //fail completion for Error
                if let objError = error{
                    completion(.failure(objError))
                }
                //Validate for blank data and URL response status code
                if let objData = data,let objURLResponse = response as? HTTPURLResponse{
                    //We have data validate for JSON and convert in JSON
                    do{
                        let objResposeJSON = try JSONSerialization.jsonObject(with: objData, options: .mutableContainers)
                        //Check for valid status code 200 else fail with error
                        if objURLResponse.statusCode == 200{
                            completion(.success(objResposeJSON))
                        }
                    }catch{
                        completion(.failure(error))
                    }
                }
            }.resume()
        }
    

    Use of API call method

    func useOfAPIRequest(){
            if let baseGETURL = URL(string:"https://postman-echo.com/get?foo1=bar1&foo2=bar2"){
                self.fetch(requestURL: baseGETURL, requestType: "GET", parameter: nil) { (result) in
                          switch result{
                          case .success(let response) :
                            print("Hello World \(response)")
                          case .failure(let error) :
                            print("Hello World \(error)")
                              
                          }
                      }
            }
          
        }
    

提交回复
热议问题