diff --git a/Sources/Amplitude/Utilities/HttpClient.swift b/Sources/Amplitude/Utilities/HttpClient.swift index 2ebda526..a641152b 100644 --- a/Sources/Amplitude/Utilities/HttpClient.swift +++ b/Sources/Amplitude/Utilities/HttpClient.swift @@ -72,8 +72,11 @@ class HttpClient { func getRequestData(events: String) -> Data? { let apiKey = configuration.apiKey + let formatter = ISO8601DateFormatter() + formatter.formatOptions.insert(.withFractionalSeconds) + let clientUploadTime: String = formatter.string(from: getDate()) var requestPayload = """ - {"api_key":"\(apiKey)","events":\(events) + {"api_key":"\(apiKey)","client_upload_time":"\(clientUploadTime)","events":\(events) """ if let minIdLength = configuration.minIdLength { requestPayload += """ @@ -83,6 +86,10 @@ class HttpClient { requestPayload += "}" return requestPayload.data(using: .utf8) } + + func getDate() -> Date { + return Date() + } } extension HttpClient { diff --git a/Tests/AmplitudeTests/Supports/TestUtilities.swift b/Tests/AmplitudeTests/Supports/TestUtilities.swift index da724473..3652ebf7 100644 --- a/Tests/AmplitudeTests/Supports/TestUtilities.swift +++ b/Tests/AmplitudeTests/Supports/TestUtilities.swift @@ -129,6 +129,11 @@ class FakeHttpClient: HttpClient { completion(Result.success(200)) return nil } + + override func getDate() -> Date { + // timestamp of 2023-10-24T18:16:24.000 in UTC time zone + return Date(timeIntervalSince1970: 1698171384) + } } class FakeResponseHandler: ResponseHandler { diff --git a/Tests/AmplitudeTests/Utilities/HttpClientTests.swift b/Tests/AmplitudeTests/Utilities/HttpClientTests.swift index 774746f0..0fc84599 100644 --- a/Tests/AmplitudeTests/Utilities/HttpClientTests.swift +++ b/Tests/AmplitudeTests/Utilities/HttpClientTests.swift @@ -42,6 +42,19 @@ final class HttpClientTests: XCTestCase { } } + func testGetRequestData() { + let httpClient = FakeHttpClient(configuration: configuration) + let event = BaseEvent(userId: "unit-test user", eventType: "unit-test event") + + let expectedRequestPayload = """ + {"api_key":"testApiKey","client_upload_time":"2023-10-24T18:16:24.000Z","events":[\(event.toString())]} + """.data(using: .utf8) + + let result = httpClient.getRequestData(events: "[\(event.toString())]") + + XCTAssertEqual(result, expectedRequestPayload) + } + func testUploadWithInvalidApiKey() { // TODO: currently this test is sending request to real Amplitude host, update to mock for better stability let httpClient = HttpClient(configuration: configuration)