Created
June 10, 2019 03:56
-
-
Save vinhnx/b13d196bf56b65bf47af890cafb4a6e3 to your computer and use it in GitHub Desktop.
simple URL builder in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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