Skip to content

Instantly share code, notes, and snippets.

@nareshdb
Last active April 12, 2019 05:35
Show Gist options
  • Save nareshdb/6fa9b7a2a11f1b11ac7f52c2d9dfa097 to your computer and use it in GitHub Desktop.
Save nareshdb/6fa9b7a2a11f1b11ac7f52c2d9dfa097 to your computer and use it in GitHub Desktop.
Adding components to URL, use this method instead of adding by yourself by appending string
extension URL {
@discardableResult
func append(_ queryItem: String, value: String?) -> URL {
guard var urlComponents = URLComponents(string: absoluteString) else { return absoluteURL }
// create array of existing query items
var queryItems: [URLQueryItem] = urlComponents.queryItems ?? []
// create query item if value is not nil
guard let value = value else { return absoluteURL }
let queryItem = URLQueryItem(name: queryItem, value: value)
// append the new query item in the existing query items array
queryItems.append(queryItem)
// append updated query items array in the url component object
urlComponents.queryItems = queryItems// queryItems?.append(item)
// returns the url from new url components
return urlComponents.url!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment