Skip to content

Instantly share code, notes, and snippets.

@vinhnx
Created June 10, 2019 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinhnx/b13d196bf56b65bf47af890cafb4a6e3 to your computer and use it in GitHub Desktop.
Save vinhnx/b13d196bf56b65bf47af890cafb4a6e3 to your computer and use it in GitHub Desktop.
simple URL builder in Swift
import Foundation
class URLBuilder {
// MARK: - Properties
private var url: String = ""
// MARK: - Life Cycle
init(_ url: String) {
self.url = url
}
// MARK: - Builder
private func build() -> URLComponents? {
return URLComponents(string: url)
}
static func buildURLString(scheme: String, host: String, port: Int, queries: [URLQueryItem]) -> String {
guard let url = self.buildURL(scheme: scheme, host: host, port: port, queries: queries) else { return "" }
return url.absoluteString
}
static func buildURL(scheme: String, host: String, port: Int, queries: [URLQueryItem]) -> URL? {
var component = URLComponents()
component.host = host
component.scheme = scheme
component.port = port
component.queryItems = queries
return URL(string: component.string ?? "")
}
// MARK: - Components
var api: String {
// https://abc.com/foo
return "\(scheme)://\(host)\(path)"
}
var scheme: String {
return build()?.scheme ?? ""
}
var host: String {
return build()?.host ?? ""
}
var path: String {
return build()?.path ?? ""
}
var query: String {
return build()?.query ?? ""
}
var queryItems: [URLQueryItem] {
return build()?.queryItems ?? [URLQueryItem]()
}
var queryNames: [String] {
return queryItems.map { $0.name }
}
var queryValues: [String] {
return queryItems.map { $0.value ?? "" }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment