Skip to content

Instantly share code, notes, and snippets.

@hassanvfx
Last active October 1, 2019 22:47
Show Gist options
  • Save hassanvfx/217d75a9ca60af441e20b5e3207753dd to your computer and use it in GitHub Desktop.
Save hassanvfx/217d75a9ca60af441e20b5e3207753dd to your computer and use it in GitHub Desktop.
import UIKit
enum APIEndpoints {
case getMovie(String)
case getMovieRelated(String)
case getTrendingMovies(Int)
func url()->String{
switch self {
case .getMovie(let movieId):
return signedUrl("/movie/\(movieId)")
case .getTrendingMovies(let page):
return signedUrl("/trending/movie/day?page=\(page)")
case .getMovieRelated(let movieId):
return signedUrl("/movie/\(movieId)/recommendations")
}
}
}
extension APIEndpoints {
fileprivate func apiBaseURL()->String{
return "https://api.themoviedb.org/3"
}
fileprivate func signedUrl(_ path:String)->String{
let urlstring = "\(apiBaseURL())\(path)"
guard let url = URL(string: urlstring) else{
assert(false,"this should never be reached")
return urlstring
}
let signatureParams = ["api_key": APIService.API_KEY_V3]
let composedURL = APIService.compose(url: url, params: signatureParams)
if let finalstring = composedURL?.absoluteString {
return finalstring
}
assert(false,"this should never be reached")
return urlstring
}
}
extension APIService {
static func compose(url:URL, params:[String:String])->URL?{
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
var queryItems = Array(components.queryItems ?? [])
params.forEach { param in
queryItems.append( URLQueryItem(name: param.key, value: param.value))
}
components.queryItems = queryItems
return try? components.asURL()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment