From c2273e9eb222e0ee05ccc0cec5a2e2aa4b9cb253 Mon Sep 17 00:00:00 2001 From: Benni Date: Wed, 2 Feb 2022 22:45:32 +0100 Subject: [PATCH] fix(ios): null in body or result --- ios/Plugin/CapacitorUrlRequest.swift | 4 +++- ios/Plugin/HttpRequestHandler.swift | 14 +++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/ios/Plugin/CapacitorUrlRequest.swift b/ios/Plugin/CapacitorUrlRequest.swift index ac846d1a..fa27981b 100644 --- a/ios/Plugin/CapacitorUrlRequest.swift +++ b/ios/Plugin/CapacitorUrlRequest.swift @@ -25,7 +25,9 @@ public class CapacitorUrlRequest: NSObject, URLSessionTaskDelegate { private func getRequestDataAsJson(_ data: JSValue) throws -> Data? { // We need to check if the JSON is valid before attempting to serialize, as JSONSerialization.data will not throw an exception that can be caught, and will cause the application to crash if it fails. - if JSONSerialization.isValidJSONObject(data) { + if (data is NSNull) { + return "null".data(using: .utf8) + } else if JSONSerialization.isValidJSONObject(data) { return try JSONSerialization.data(withJSONObject: data) } else { throw CapacitorUrlRequest.CapacitorUrlRequestError.serializationError("[ data ] argument for request of content-type [ application/json ] must be serializable to JSON") diff --git a/ios/Plugin/HttpRequestHandler.swift b/ios/Plugin/HttpRequestHandler.swift index d3d5f26d..9d91e243 100644 --- a/ios/Plugin/HttpRequestHandler.swift +++ b/ios/Plugin/HttpRequestHandler.swift @@ -31,11 +31,15 @@ fileprivate enum ResponseType: String { /// - data: The JSON Data to parse /// - Returns: The parsed value or an error func tryParseJson(_ data: Data) -> Any { - do { - return try JSONSerialization.jsonObject(with: data, options: .mutableContainers) - } catch { - return error.localizedDescription - } + if data.elementsEqual("null".data(using: .utf8)!) { + return NSNull() + } + + do { + return try JSONSerialization.jsonObject(with: data, options: .mutableContainers) + } catch { + return error.localizedDescription + } } class HttpRequestHandler {