iOS Swift API URL查询项

cwtwac6a  于 2022-11-19  发布在  iOS
关注(0)|答案(1)|浏览(150)
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()

我得到的网址为:实际jsonplaceholder.typicode.com/users/?id=1网址:https://jsonplaceholder.typicode.com/users/1
我需要删除?id=如何删除此字符。请帮助。
先谢谢你。

abithluo

abithluo1#

URLQueryItem添加表示查询分隔符的问号。
此REST URL不使用URL查询,因此根本不需要URLQueryItem。使用字符串插值添加用户ID。
也不需要URLRequest,GET是默认值,您不需要使用特殊配置

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()

相关问题