Skip to content

Instantly share code, notes, and snippets.

@anoop4real
Created March 25, 2017 14:37
Show Gist options
  • Select an option

  • Save anoop4real/e33c39790c611feebd34c030e5f595e9 to your computer and use it in GitHub Desktop.

Select an option

Save anoop4real/e33c39790c611feebd34c030e5f595e9 to your computer and use it in GitHub Desktop.
Reusable snippet to construct webservice url request. Note this is taken from Playground
struct Constants {
struct APIDetails {
static let APIScheme = "https"
static let APIHost = "restcountries.eu"
static let APIPath = "/rest/v1/alpha/"
}
}
private func createURLFromParameters(parameters: [String:Any], pathparam: String?) -> URL {
var components = URLComponents()
components.scheme = Constants.APIDetails.APIScheme
components.host = Constants.APIDetails.APIHost
components.path = Constants.APIDetails.APIPath
if let paramPath = pathparam {
components.path = Constants.APIDetails.APIPath + "\(paramPath)"
}
if !parameters.isEmpty {
components.queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)")
components.queryItems!.append(queryItem)
}
}
return components.url!
}
let url = createURLFromParameters(parameters: ["fullText" : "true"], pathparam: "IN")
//Result url= https://restcountries.eu/rest/v1/alpha/IN?fullText=true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment