Last active
April 12, 2019 05:35
-
-
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
This file contains hidden or 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
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