Skip to content

Commit

Permalink
fix: set offline when receiving certain error responses (#212)
Browse files Browse the repository at this point in the history
  • Loading branch information
crleona authored Aug 19, 2024
1 parent 0ef306e commit 056ccbf
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
15 changes: 12 additions & 3 deletions Sources/Amplitude/Utilities/HttpClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,19 @@ class HttpClient {
let request = try getRequest()
let requestData = getRequestData(events: events)

sessionTask = session.uploadTask(with: request, from: requestData) { [callbackQueue] data, response, error in
sessionTask = session.uploadTask(with: request, from: requestData) { [callbackQueue, configuration] data, response, error in
callbackQueue.async {
if error != nil {
completion(.failure(error!))
if let error = error {
let nsError = error as NSError
if nsError.domain == NSURLErrorDomain {
switch nsError.code {
case NSURLErrorCannotConnectToHost, NSURLErrorNetworkConnectionLost, NSURLErrorCannotFindHost, NSURLErrorAppTransportSecurityRequiresSecureConnection:
configuration.offline = true
default:
break
}
}
completion(.failure(error))
} else if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 1..<300:
Expand Down
21 changes: 21 additions & 0 deletions Tests/AmplitudeTests/Utilities/HttpClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,25 @@ final class HttpClientTests: XCTestCase {
}
_ = XCTWaiter.wait(for: [asyncExpectation], timeout: 5)
}

func testUploadWithCannotConnectToHostError() {
let config = Configuration(apiKey: "fake", serverUrl: "http://localhost:3000", offline: false)
let httpClient = HttpClient(configuration: config, diagnostics: diagonostics)
let uploadExpectation = expectation(description: "Did Call Upload")
let event = BaseEvent(userId: "unit-test user", eventType: "unit-test event")

_ = httpClient.upload(events: "[\(event.toString())]") { result in
switch result {
case .success:
XCTFail("Expected failure")
case .failure(let error):
XCTAssertEqual((error as NSError).code, NSURLErrorCannotConnectToHost)
}

uploadExpectation.fulfill()
}

waitForExpectations(timeout: 5)
XCTAssertEqual(config.offline, true)
}
}

0 comments on commit 056ccbf

Please sign in to comment.