Skip to content

Commit

Permalink
feat: add method to get device ID synchronously (#490)
Browse files Browse the repository at this point in the history
  • Loading branch information
bgiori authored Apr 4, 2024
1 parent 56446ae commit f5066b2
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
15 changes: 10 additions & 5 deletions Sources/Amplitude/Amplitude.m
Original file line number Diff line number Diff line change
Expand Up @@ -1669,6 +1669,9 @@ - (NSString *)getAdSupportID {
}

- (NSString *)getDeviceId {
if (self.deviceId == nil) {
return [self initializeDeviceId];
}
return self.deviceId;
}

Expand All @@ -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;
Expand Down
8 changes: 8 additions & 0 deletions Tests/AmplitudeTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -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
3 changes: 0 additions & 3 deletions Tests/SetupTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit f5066b2

Please sign in to comment.