Search code examples
jsonswiftencodingurlencode

How do i encode any character in my search input in Swift?


I am not sure if i understand how this exactly works, i am trying to percent encode the user input because letters like ø,æ,å and backspace is frequently used for the input. This is my attempt so far.

    func SearchData(){
        let name = searchText
        // updating page every time...
        let encode = name.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        let url = "http://xmlopen.rejseplanen.dk/bin/rest.exe/location?input=\(String(describing: encode))&format=json"
        print(url)
        self.vm.SearchData(url: url)
    }
    
}

Final solution that was made by vadians answer below.

   func searchData(){
        // updating page every time...
        let encode = searchText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        let url = "http://xmlopen.rejseplanen.dk/bin/rest.exe/location?input=\(encode)&format=json"
        print(url)
        self.vm.searchData(url: url)
    }

Solution

  • First of all you are misusing String(describing. It doesn't fix a failed percent encoding.

    Second of all the percent encoding is related to the query portion of the URL, not to the host.

    Third of all name functions with starting lowercase letter

    Force unwrapping the encoded string is safe because the content of a search field is always in the range of encodable characters.

    func searchData(){
        // updating page every time...
        let encode = searchText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        let url = "http://xmlopen.rejseplanen.dk/bin/rest.exe/location?input=\(encode))&format=json"
        print(url)
        self.vm.SearchData(url: url)
    }
    

    A suitable alternative is URLComponents and URLQueryItem which encodes the string properly.