I am trying to create URL from String like the following
let searchParam = "?name=movies&Genre=#Action"
func searchMovies(searchString: String) {
let encodedString = searchParam.encodeSearchString()
let urlString = "https://search.movies.local/list.html" + encodedString
guard let url = URL(string: searchParam) else {
return
}
print("URL: ", url)
}
func encodeSearchString() -> String? {
let unreserved = "#?=&"
let allowed = NSMutableCharacterSet.alphanumeric()
allowed.addCharacters(in: unreserved)
return addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
}
It works fine when the search param is "?name=movies&Genre=#Action" but if the search param contains more than one #, then the URL is nil.
For eg., if the searchParam is "?name=#movies&Genre=#Action"
The problem is that the
#character is the separator for thefragmentof the URL.The most reliable way to build an URL with multiple components is
URLComponentsandURLQueryItem, the encoding is freeOr