获取请求未在 swift 中执行,在请求中传递 URL 时出现空值错误

Get request doesn't get executed in swift, getting nil value error where URL is passed in the request

我正在尝试在我的应用程序中添加 GET 请求。 值或最终 url 字符串在我的 sURL 变量中正确流动。但是仍然在执行此代码时,我在行中得到“发现零错误” - “var request = URLRequest(url: URL(string: sUrl)!)”

请帮忙。

我的代码-

class AllStickerService {
    static let allStickerInstance: AllStickerService = AllStickerService()
    var delegateAllSticker: AllStickerProtocol!
    
    func fetchAllSticker(category: String, APITokenString: String) {
        var sUrl = "http://xyzabc.com/api/stickers"
        let params = ["category": category]
        
        var sParams = ""
           for (key,value) in params {
              sParams += key + "=" + value
            print("\(key), \(value)")
           }
        if !sParams.isEmpty {
            sParams = "?" + sParams
            sUrl = sUrl + sParams
        }

        var request = URLRequest(url: URL(string: sUrl)!)
        print(request)
        request.httpMethod = "GET"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.addValue("Bearer "+APITokenString, forHTTPHeaderField: "Authorization")
        
        let session = URLSession.shared
        session.dataTask(with: request) { (data, response, error) in
            
            if (response as? HTTPURLResponse) != nil {
                
                if let httpResponse = response as? HTTPURLResponse {
                    print("statusCode: \(httpResponse.statusCode)")
                    print(httpResponse)
                }
                
                if let data = data{
                    do {
                        guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return }
                        print(json)
                    }catch {
                        print("Error\(error)")
                    }
                }
            }
        }.resume()
    }
}

强制展开很少是个好主意。要么使用字符串连接来创建 URLs;除了潜在的安全问题,您还必须担心 url 编码之类的问题,这是您的问题。

您的 category 参数值有一个 space,这需要编码为 %20,但您不这样做,最终得到一个无效的 URL 字符串.您在 Postman 中看不到这一点,因为它在幕后为您编码 space。

更好的方法是使用 URLComponentsURLQueryItem 和条件展开

func fetchAllSticker(category: String, APITokenString: String) {
     var sUrl = "http://xyzabc.com/api/stickers"
     let params = URLQueryItem(name:"category", value: category)

     if var urlComponents = URLComponents(string:"http://xyzabc.com/api/stickers") {
         
         urlComponents.queryItems = params
         
         if let url = urlComponents.url {
             var request = URLRequest(url: url) 
             ...
         }
    }

我还建议您考虑使用 Decodable 来处理您的 JSON 响应,而不是 JSONSerialization