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"
var urlComponents = URLComponents(string: urlString); urlComponents?.queryItems = [URLQueryItem(name: "name", value: "movies"), URLQueryItem(name: "Genre", value: "#Action")]; guard let url = urlComponents?.url else { return }