iosswiftopenapi-generator

Convert Swift OpenAPIRuntime.HTTPBody into JSON-String


I'm using Apple's Open API Generator in my iOS mobile app. I need to convert the http response in case of a failure from the backend, for this I have the following implementation:

switch response {
case .internalServerError(let error):
case .badRequest(let badRequest):
case .created(let player):
case .undocumented(statusCode: let statusCode, let payload):
}

The http response is of type OpenAPIRuntime.HTTPBody and I don't know how to convert it into a String or other Type. Does anyone know how?


Solution

  • Try this implementation:

    switch response {
    case .internalServerError(let error):
        // Handle internal server error
        print("Internal Server Error: \(convertToJSONString(httpBody: error))")
    case .badRequest(let badRequest):
        // Handle bad request
        print("Bad Request: \(convertToJSONString(httpBody: badRequest))")
    case .created(let player):
        // Handle success case
        print("Created: \(convertToJSONString(httpBody: player))")
    case .undocumented(statusCode: let statusCode, let payload):
        // Handle undocumented cases
        print("Undocumented Status Code: \(statusCode), Payload: \(convertToJSONString(httpBody: payload))")
    }
    
    // Helper function to convert HTTPBody to JSON String
    func convertToJSONString(httpBody: OpenAPIRuntime.HTTPBody) -> String {
        guard let data = httpBody.data else {
            return "No Data"
        }
        
        // Convert data to a string
        if let jsonString = String(data: data, encoding: .utf8) {
            return jsonString
        } else {
            return "Unable to convert data to String"
        }
    }
    

    example:

    func convertToJSON(httpBody: OpenAPIRuntime.HTTPBody) -> Any? {
        guard let data = httpBody.data else {
            return nil
        }
        
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            return json
        } catch {
            print("Failed to convert to JSON: \(error)")
            return nil
        }
    }