Skip to content

Commit

Permalink
Add id generator
Browse files Browse the repository at this point in the history
  • Loading branch information
codykerns committed Feb 17, 2024
1 parent 6f8f996 commit 56af9b8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
22 changes: 22 additions & 0 deletions Sources/StableID/Generators/IDGenerator.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//
// IDGenerator.swift
//
//
// Created by Cody Kerns on 2/17/24.
//

import Foundation

public protocol IDGenerator {
func generateID() -> String
}

extension StableID {
public class StandardGenerator: IDGenerator {
public init() { }

public func generateID() -> String {
return UUID().uuidString
}
}
}
13 changes: 8 additions & 5 deletions Sources/StableID/StableID.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@ public class StableID {
return _stableID
}

private init(_id: String) {
private init(_id: String, _idGenerator: IDGenerator) {
self._id = _id
self._idGenerator = _idGenerator
}

private static var _remoteStore = NSUbiquitousKeyValueStore.default
private static var _localStore = UserDefaults(suiteName: Constants.StableID_Key_DefaultsSuiteName)

public static func configure(id: String? = nil) {
public static func configure(id: String? = nil, idGenerator: IDGenerator = StandardGenerator()) {
guard isConfigured == false else {
self.logger.log(type: .error, message: "StableID has already been configured! Call `identify` to change the identifier.")
return
Expand All @@ -33,7 +34,7 @@ public class StableID {
self.logger.log(type: .info, message: "Configuring StableID...")

// By default, generate a new anonymous identifier
var identifier = UUID().uuidString
var identifier = idGenerator.generateID()

if let id {
// if an identifier is provided in the configure method, identify with it
Expand All @@ -59,7 +60,7 @@ public class StableID {
}
}

_stableID = StableID(_id: identifier)
_stableID = StableID(_id: identifier, _idGenerator: idGenerator)

self.logger.log(type: .info, message: "Configured StableID. Current user ID: \(identifier)")

Expand All @@ -71,6 +72,8 @@ public class StableID {

private static let logger = StableIDLogger()

private var _idGenerator: any IDGenerator

private var _id: String

private var delegate: (any StableIDDelegate)?
Expand Down Expand Up @@ -116,7 +119,7 @@ public class StableID {
} else {
Self.logger.log(type: .warning, message: "StableID removed from iCloud. Reverting to local value: \(_id)")

// The store was updated, but the id is empty. Reset to a new UUID
// The store was updated, but the id is empty. Reset back to configured identifier
self.setIdentity(value: _id)
}

Expand Down

0 comments on commit 56af9b8

Please sign in to comment.