Search code examples
odataswift4swift5

urlEncoding issue with Swift Odata


Our OData service

 {{url}}/odata/GroupMembers?$filter=GroupName eq 'PDL-**-Users-Test'

The spaces before and after eq is becoming %2520 upon urlencoding in Swift which is leading to error code 400.

odata/GroupMembers?$filter=GroupName%2520eq%2520'PDL-**-Users-Test'

Solution

  • My earlier code was,

    urlComponents.queryItems = [URLQueryItem]()
    
    for (key,value) in parameters {
             let queryItem = URLQueryItem(name: key,
                                             value: "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))            
       }
    
    urlRequest.url = urlComponents.url
    

    by removing the following code, it worked.

    .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    

    Reason being Apple's URLComponents and URLQueryItem does the encoding in Swift.