From f5066b25a604518784f0e2c89de233afaa6d7fb5 Mon Sep 17 00:00:00 2001 From: Brian Giori Date: Thu, 4 Apr 2024 08:02:10 -0700 Subject: [PATCH] feat: add method to get device ID synchronously (#490) --- Sources/Amplitude/Amplitude.m | 15 ++++++++++----- Tests/AmplitudeTests.m | 8 ++++++++ Tests/SetupTests.m | 3 --- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/Sources/Amplitude/Amplitude.m b/Sources/Amplitude/Amplitude.m index c080ecf6..2c9f3d11 100644 --- a/Sources/Amplitude/Amplitude.m +++ b/Sources/Amplitude/Amplitude.m @@ -1669,6 +1669,9 @@ - (NSString *)getAdSupportID { } - (NSString *)getDeviceId { + if (self.deviceId == nil) { + return [self initializeDeviceId]; + } return self.deviceId; } @@ -1677,11 +1680,13 @@ - (long long)getSessionId { } - (NSString *)initializeDeviceId { - if (self.deviceId == nil) { - self.deviceId = [self.dbHelper getValue:DEVICE_ID]; - if (![self isValidDeviceId:self.deviceId]) { - self.deviceId = [self _getDeviceId]; - [self.dbHelper insertOrReplaceKeyValue:DEVICE_ID value:self.deviceId]; + @synchronized (self) { + if (self.deviceId == nil) { + self.deviceId = [self.dbHelper getValue:DEVICE_ID]; + if (![self isValidDeviceId:self.deviceId]) { + self.deviceId = [self _getDeviceId]; + [self.dbHelper insertOrReplaceKeyValue:DEVICE_ID value:self.deviceId]; + } } } return self.deviceId; diff --git a/Tests/AmplitudeTests.m b/Tests/AmplitudeTests.m index af997e1f..48ae32ed 100644 --- a/Tests/AmplitudeTests.m +++ b/Tests/AmplitudeTests.m @@ -1705,4 +1705,12 @@ - (void)testOpenURLFiresDeepLinkEvent { XCTAssertEqualObjects([[event objectForKey:@"event_properties"] objectForKey:kAMPEventPropLinkUrl], @"https://test-app.com"); } +- (void)testGetDeviceIdAfterInit { + NSString *instanceName = @"testGetDeviceIdAfterInit"; + Amplitude *client = [Amplitude instanceWithName:instanceName]; + [client initializeApiKey:@"testGetDeviceIdAfterInit"]; + NSString *deviceId = [client getDeviceId]; + XCTAssertNotEqualObjects(deviceId, @""); +} + @end diff --git a/Tests/SetupTests.m b/Tests/SetupTests.m index 3d9fdcf4..d1a85467 100644 --- a/Tests/SetupTests.m +++ b/Tests/SetupTests.m @@ -115,15 +115,12 @@ - (void)testUserPropertiesSet { - (void)testSetDeviceId { AMPDatabaseHelper *dbHelper = [AMPDatabaseHelper getDatabaseHelper]; - NSString *initialDeviceId = [self.amplitude getDeviceId]; - XCTAssertNil(initialDeviceId); // device id not initialized yet [self.amplitude initializeApiKey:apiKey]; [self.amplitude flushQueueWithQueue:self.amplitude.initializerQueue]; [self.amplitude flushQueue]; NSString *generatedDeviceId = [self.amplitude getDeviceId]; XCTAssertNotNil(generatedDeviceId); - XCTAssertNotEqualObjects(initialDeviceId, generatedDeviceId); #if !TARGET_OS_OSX XCTAssertEqual(generatedDeviceId.length, 36); #else