简体   繁体   English

在 Swift 中发布解码异步/等待响应

[英]Issue decoding Async/Await response in Swift

I am trying to submit an order to production but keep getting a decoding error and I have no idea where it's going wrong.我正在尝试向生产提交订单,但一直出现解码错误,我不知道哪里出了问题。

This is the full error:这是完整的错误:

ERROR DECODING keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))错误解码 keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) (" id").", underlyingError: nil))

My Model:我的模型:

struct PrintifyOrderResponse: Codable {
    let id: String
}

My function/call:我的功能/电话:

func fetch<T: Codable>(type: PrintifyRequestType) async throws -> T? {
    let req = type.getRequest()
    
    let (data, _) = try await URLSession.shared.data(for: req)
    
    do {
        let decoder = JSONDecoder()
        let decoded = try decoder.decode(T.self, from: data)
        return decoded
    } catch {
        print("ERROR DECODING")
        print(error)
        print()
        print(error.localizedDescription)
        return nil
    }
}

in async func:在异步函数中:

do {
        var res: PrintifyOrderResponse?
        res = try await service.fetch(type: .sendToProduction(id))
        guard let res = res else {
            statusError(message: "Error sending to production")
            return
        }
        
        orderSuccess(id: res.id)
        
    } catch {
        print("ERROR: \(error)")
        statusError()
    }
}

The response is quite simple as seen from postman below.从下面的邮递员那里可以看出,响应非常简单。 I'm not sure why/how this decoding error is happening我不确定为什么/如何发生此解码错误

在此处输入图像描述

On the basis of what you shared with us, the response is not what you said you expected.根据您与我们分享的内容,回复不是您所说的预期。 To determine what went wrong, we should add some diagnostics.为了确定哪里出了问题,我们应该添加一些诊断。

So, to diagnose this, you should print the contents of the data .因此,要对此进行诊断,您应该打印data的内容。 You should also capture and print the response .您还应该捕获并打印response

func fetch<T: Decodable>(type: PrintifyRequestType) async throws -> T {
    let request = type.getRequest()
    
    let (data, response) = try await URLSession.shared.data(for: request)
    
    do {
        guard
            let response = response as? HTTPURLResponse,
            200...299 ~= response.statusCode
        else {
            throw URLError(.badServerResponse)
        }
            
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        print("data: \(String(data: data, encoding: .utf8) ?? "cannot represent as string")")
        print("response: \(String(describing: response))")
        print(error)
        throw error
    }
}

While we're here, we should probably re- throw the error and change the return type to not be optional.当我们在这里时,我们可能应该重新throw错误并将返回类型更改为非可选的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM