Skip to content

Commit

Permalink
fix: initialize device info before generating the device ID (#491)
Browse files Browse the repository at this point in the history
  • Loading branch information
bgiori authored Apr 5, 2024
1 parent 55188b6 commit 7960a7e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
11 changes: 6 additions & 5 deletions Sources/Amplitude/Amplitude.m
Original file line number Diff line number Diff line change
Expand Up @@ -524,8 +524,7 @@ - (void)initializeApiKey:(NSString *)apiKey
self.apiKey = apiKey;

[self runOnBackgroundQueue:^{
self->_deviceInfo = [[AMPDeviceInfo alloc] init];
[self initializeDeviceId];
[self initializeDeviceInfo];
if (setUserId) {
[self setUserId:userId];
} else {
Expand Down Expand Up @@ -1670,7 +1669,7 @@ - (NSString *)getAdSupportID {

- (NSString *)getDeviceId {
if (self.deviceId == nil) {
return [self initializeDeviceId];
[self initializeDeviceInfo];
}
return self.deviceId;
}
Expand All @@ -1679,8 +1678,11 @@ - (long long)getSessionId {
return _sessionId;
}

- (NSString *)initializeDeviceId {
- (void)initializeDeviceInfo {
@synchronized (self) {
if (self->_deviceInfo == nil) {
self->_deviceInfo = [[AMPDeviceInfo alloc] init];
}
if (self.deviceId == nil) {
self.deviceId = [self.dbHelper getValue:DEVICE_ID];
if (![self isValidDeviceId:self.deviceId]) {
Expand All @@ -1689,7 +1691,6 @@ - (NSString *)initializeDeviceId {
}
}
}
return self.deviceId;
}

- (NSString *)_getDeviceId {
Expand Down
18 changes: 14 additions & 4 deletions Tests/AmplitudeTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -1705,12 +1705,22 @@ - (void)testOpenURLFiresDeepLinkEvent {
XCTAssertEqualObjects([[event objectForKey:@"event_properties"] objectForKey:kAMPEventPropLinkUrl], @"https://test-app.com");
}

- (void)testGetDeviceIdAfterInit {
NSString *instanceName = @"testGetDeviceIdAfterInit";
- (void)testGetDeviceIdBeforeInit {
NSString *instanceName = @"testGetDeviceIdBeforeAndAfterInit";

// Clear device ID from db
AMPDatabaseHelper *dbHelper = [AMPDatabaseHelper getDatabaseHelper:instanceName];
[dbHelper insertOrReplaceKeyValue:@"device_id" value:nil];

// Device ID should get generated before api key init
Amplitude *client = [Amplitude instanceWithName:instanceName];
[client initializeApiKey:@"testGetDeviceIdAfterInit"];
NSString *deviceId = [client getDeviceId];
XCTAssertNotEqualObjects(deviceId, @"");
XCTAssertNotNil(deviceId);

// Device ID should match after init.
[client initializeApiKey:@"testGetDeviceIdBeforeAndAfterInit"];
NSString *deviceIdAfterInit = [client getDeviceId];
XCTAssertEqualObjects(deviceId, deviceIdAfterInit);
}

@end

0 comments on commit 7960a7e

Please sign in to comment.