Home > Mobile >  Swift completion handlers - using escaped closure?
Swift completion handlers - using escaped closure?

Time:09-23

Hi i am a beginner studying swift and would like to know what to use when making an api request. What is the modern and professional way?

is it using an escaping closure like so:

func getTrendingMovies(completion:  @escaping (Result< [Movie], Error >) -> Void) {
    guard let url = URL(string: "\(Constants.baseUrl)/trending/all/day?api_key=\.(Constants.API_KEY)") else {return}
    
    let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _,
 error in
        guard let data = data, error == nil else  {
            return
        }
        do {
            let results = try JSONDecoder().decode(TrendingMoviesResponse.self, from:
 data)
            completion(.success(results.results))
        } catch {
            completion(.failure(error))
        }
    }
    task.resume()
}

or should i make an api request without escaping closure while using a sort of delegate like so:

func performRequest(with urlString: String){
    if let url = URL(string: urlString){
        let session = URLSession(configuration: .default)
        let task = session.dataTask(with: url) { data, response, error in
            if error != nil {
                delegate?.didFailWithError(error: error!)
                return
            }
            if let safeData = data{
                // created parseJson func
                if let weather = parseJSON(safeData){
                    delegate?.didUpdateWeather(self,weather: weather)
                }
            }
        }
        task.resume()
    } else {
        print("url is nil")
    }
}

CodePudding user response:

I agree with matt, the modern and professional way is async/await

func getTrendingMovies() async throws -> [Movie] {
    let url = URL(string: "\(Constants.baseUrl)/trending/all/day?api_key=\(Constants.API_KEY)")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode(TrendingMoviesResponse.self, from: data).results
}
  • Related