Home > Software engineering >  iOS Swift API URLQueryitem
iOS Swift API URLQueryitem

Time:11-14

var urlComponents = URLComponents(string: "https://jsonplaceholder.typicode.com/users/")
    urlComponents?.queryItems = [URLQueryItem(name: "id", value: userId.id)]

 var urlComponents = URLComponents(string: "https://jsonplaceholder.typicode.com/users/")
    urlComponents?.queryItems = [URLQueryItem(name: "id", value: userId.id)]
    
    var urlRequest = URLRequest(url: (urlComponents?.url!)!)
    urlRequest.httpMethod = "GET"
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    
    print("urlRequest=====\(urlRequest)")
    
    session.dataTask(with: urlRequest) { (data, response, error) in
        
        guard let data = data else { return }
        
        do {
            let decoder = JSONDecoder()
            let userRes = try decoder.decode([UserResponse].self, from: data)
            self.delegate?.UserDetailsSuccess(userDetail: userRes)
        } catch let error {
            print("Error: ", error)
        }
    }.resume()

I am getting the url as : urlRequest=====https://jsonplaceholder.typicode.com/users/?id=1 The actual url : https://jsonplaceholder.typicode.com/users/1

I need to remove the ?id= How to remove this characters from this. Please help.

Thanks in advance.

CodePudding user response:

URLQueryItem adds the question mark which represents the query separator.

This REST URL doesn't use URL query so URLQueryItem is not needed at all. Add the user ID with String Interpolation.

URLRequest is not needed either, GET is the default and you don't use a special configuration

let url = URL(string: "https://jsonplaceholder.typicode.com/users/\(userId.id)")!

URLSession.shared.dataTask(with: url) { (data, response, error) in
    
    if let error { print(error); return }
    
    do {
        let decoder = JSONDecoder()
        let userRes = try decoder.decode([UserResponse].self, from: data!)
        self.delegate?.UserDetailsSuccess(userDetail: userRes)
    } catch {
        print("Error: ", error)
    }
}.resume()
  • Related