Zin Win Htet
Zin Win Htet

Reputation: 2565

How to encode url string properly to avoid question mark (?) from being %3F in swift?

I'm sending a request to server using Alamofire pod.

var urlComponents = URLComponents(string: "/hotel/v2")!
urlComponents.queryItems = [
     URLQueryItem(name: "page", value: page)
]
let urlString = urlComponents.url?.absoluteString
var urlRequest = URLRequest(url: url.appendingPathComponent(urlString))

The problem begins when I print out the urlRequest. It shows as : enter image description here

Then the request reach the backend and the backend returns me some error.

Upvotes: 4

Views: 3404

Answers (2)

Bola Ibrahim
Bola Ibrahim

Reputation: 780

You can simply do this - Swift 4 & 5

let url = URL(string: APIServant.API_DEV_URL + path)!
var urlRequest = URLRequest(url: url)

Upvotes: 2

rmaddy
rmaddy

Reputation: 318804

Don't use url.appendingPathComponent. You have created a URLComponents. Use it properly.

var urlComponents = URLComponents(string: url)!
urlComponents.path = "/hotel/v2"
urlComponents.queryItems = [
     URLQueryItem(name: "page", value: page)
]
var urlRequest = URLRequest(url: urlComponents.url!)

Here I am assuming that url is something like "https://somedomain.com".

Upvotes: 4

Related Questions