OptimizelyUserContext for the Swift SDK
The OptimizelyUserContext object lets you make flag decisions and track events for a user context you have already created using the Create User ContextCreate User Context method.
Also, if you have Real-Time Audiences for Feature ExperimentationReal-Time Audiences for Feature Experimentation, you can evaluate if your user qualifies for an audience segment.
OptimizelyUserContext minimum SDK version
SDK version 3.7 and higher.
Forced decision methods minimum SDK version
setForcedDecision(), getForcedDecision(), removeForcedDecision() and removeAllForcedDecisions() methods are supported on SDK version 3.10.0 and higher.
Real-Time Audiences for Feature Experimentation minimum SDK version
fetchQualifiedSegments() and isQualifiedFor() methods are supported on version 4.0.0 and higher.
OptimizelyUserContext definition
The following code shows the object definition for OptimizelyUserContext:
public class OptimizelyUserContext {
public var userId: String
public var attributes: [String: Any?] { get }
public init(optimizely: OptimizelyClient,
userId: String,
attributes: [String: Any?]? = nil)
// Set an attribute for the user.
public func setAttribute(key: String, value: Any?)
// Make a decision about which flag variation the user buckets into for the flag key.
public func decide(key: String,
options: [OptimizelyDecideOption]? = nil) -> OptimizelyDecision
// Make decisions about which flag variations the user buckets into for flag keys.
public func decide(keys: [String],
options: [OptimizelyDecideOption]? = nil) -> [String: OptimizelyDecision]
// Make decisions about which flag variations the user buckets into for all flags.
public func decideAll(options: [OptimizelyDecideOption]? = nil) -> [String: OptimizelyDecision]
// Track user event.
public func trackEvent(eventKey: String, eventTags: [String: Any]? = nil) throws
// Asynchronously make a decision for the flag key (required for CMAB flags).
public func decideAsync(key: String,
options: [OptimizelyDecideOption]? = nil,
completion: @escaping DecideCompletion)
public func decideAsync(key: String,
options: [OptimizelyDecideOption]? = nil) async -> OptimizelyDecision
// Asynchronously make decisions for the flag keys.
public func decideAsync(keys: [String],
options: [OptimizelyDecideOption]? = nil,
completion: @escaping DecideForKeysCompletion)
public func decideAsync(keys: [String],
options: [OptimizelyDecideOption]? = nil) async -> [String: OptimizelyDecision]
// Asynchronously make decisions for all flags.
public func decideAllAsync(options: [OptimizelyDecideOption]? = nil,
completion: @escaping DecideForKeysCompletion)
public func decideAllAsync(options: [OptimizelyDecideOption]? = nil) async -> [String: OptimizelyDecision]
// Sets a forced decision (variationKey) for a given decision context (flagKey and optional ruleKey).
public func setForcedDecision(context: OptimizelyDecisionContext,
decision: OptimizelyForcedDecision) -> Bool
// Returns the forced decision (variationKey) for a given decision context (flagKey and optional ruleKey).
public func getForcedDecision(context: OptimizelyDecisionContext) -> OptimizelyForcedDecision?
// Removes the forced decision (variationKey) for a given decision context (flagKey and optional ruleKey).
public func removeForcedDecision(context: OptimizelyDecisionContext) -> Bool
// Removes all the forced decisions (variationKeys) for the user context.
public func removeAllForcedDecisions() -> Bool
//
// The following methods require Real-Time Audiences for Feature Experimentation.
// See note following this code sample.
//
// An array of audience segment names that the user is qualified for.
// The result of **fetchQualifiedSegments()** is saved here.
// Can be nil if not properly updated with fetchQualifiedSegments().
//
// You can read and write directly to the qualified segments array.
// This lets you bypass the remote fetching process from ODP
// or for utilizing your own fetching service.
public var qualifiedSegments: [String]?
// Fetch all qualified audience segments for the user context.
//
// The segments fetched are saved in **qualifiedSegments** and can be accessed any time.
// On failure, **qualifiedSegments** is nil and one of the following errors are returned:
// - OptimizelyError.invalidSegmentIdentifier
// - OptimizelyError.fetchSegmentsFailed(String)
//
// - Parameters:
// - options – (Optional) A set of options for fetching qualified segments.
// - completionHandler – A completion handler to be called with the fetch result.
// On success, it passes a nil error and the fetched segments are saved in qualifiedSegments.
// On failure, it passes a non-nil error.
public func fetchQualifiedSegments(options: [OptimizelySegmentOption] = [],
completionHandler: @escaping (OptimizelyError?) -> Void)
// async form – throws the error instead of passing it to a completion handler.
public func fetchQualifiedSegments(options: [OptimizelySegmentOption] = []) async throws
// Synchronous form – blocks the calling thread until the fetch completes.
public func fetchQualifiedSegments(options: [OptimizelySegmentOption] = []) throws
// Check if the user is qualified for the given segment.
// - Parameter segment – The segment name to check qualification for.
// - Returns – True, if qualified.
public func isQualifiedFor(segment: String) -> Bool
}
public typealias DecideCompletion = (OptimizelyDecision) -> Void
public typealias DecideForKeysCompletion = ([String: OptimizelyDecision]) -> Void
// OptimizelyDecisionContext
public struct OptimizelyDecisionContext {
public let flagKey: String
public let ruleKey: String?
public init(flagKey: String, ruleKey: String? = nil)
}
// OptimizelyForcedDecision
public struct OptimizelyForcedDecision {
public let variationKey: String
public init(variationKey: String)
}Note You must configure Real-Time Audiences for Feature ExperimentationReal-Time Audiences for Feature Experimentation to access thequalifiedSegments variable and the fetchQualifiedSegments() and isQualifiedFor() methods.
Properties
The following table shows attributes for the OptimizelyUserContext object:
Attribute | Type | Comment |
|---|---|---|
userId | String | The ID of the user |
attributes | Map | A map of custom key-value pairs specifying attributes for the user that are used for audience targetingaudience targeting. You can pass the map with the user ID when you create the user. |
Methods
The following table shows methods for the OptimizelyUserContext object:
Method | Comment |
|---|---|
`setAttribute` | Pass a custom user attribute as a key-value pair to the user context. |
`decide` | Returns a decision result for a flag key for a user in an `OptimizelyDecision` object containing all data required to deliver the flag rule. See [Decide methods](https://docs.developers.optimizely.com/feature-experimentation/docs/decide-methods-swift#decide). |
`decide(keys:)` | Returns a map of flag decisions for specified flag keys. See [Decide methods](https://docs.developers.optimizely.com/feature-experimentation/docs/decide-methods-swift#decide-for-specified-keys). |
`decideAll` | Returns decisions for all active (unarchived) flags for a user. See [Decide methods](https://docs.developers.optimizely.com/feature-experimentation/docs/decide-methods-swift#decide-all). |
`trackEvent` | Tracks a conversion event, which is an action a user takes. Throws `OptimizelyError.eventKeyInvalid` when the event key does not match an existing event. See [Track Event](https://docs.developers.optimizely.com/feature-experimentation/docs/track-event-swift). |
`setForcedDecision` | Forces a user into a specific variation. See [Set Forced Decision](https://docs.developers.optimizely.com/feature-experimentation/docs/forced-decision-methods-swift#set-forced-decision-method---setforceddecision) |
`getForcedDecision` | Returns what variation the user was forced into. See [Get Forced Decision](https://docs.developers.optimizely.com/feature-experimentation/docs/forced-decision-methods-swift#get-forced-decision-method---getforceddecision). |
`removeForcedDecision` | Removes a user from a specific forced variation. See [Remove Forced Decision](https://docs.developers.optimizely.com/feature-experimentation/docs/forced-decision-methods-swift#remove-forced-decision-method---removeforceddecision). |
`removeAllForcedDecisions` | Removes a user from all forced variations. See [Remove All Forced Decisions](https://docs.developers.optimizely.com/feature-experimentation/docs/forced-decision-methods-swift#remove-all-forced-decisions-method---removeallforceddecisions). |
`fetchQualifiedSegments` ** | Fetch Optimizely Data Platform (ODP) real-time audience segments that the user context qualified for. See [Real-Time Audiences for Feature Experimentation segment qualification methods](https://docs.developers.optimizely.com/feature-experimentation/docs/real-time-audiences-for-feature-experimentation-segment-qualification-methods-swift). |
`isQualifiedFor` ** | Check if the user context qualified for a given ODP real-time segment. See [Real-Time Audiences for Feature Experimentation segment qualification methods](https://docs.developers.optimizely.com/feature-experimentation/docs/real-time-audiences-for-feature-experimentation-segment-qualification-methods-swift). |
** Requires Real-Time Audiences for Feature ExperimentationReal-Time Audiences for Feature Experimentation.
See also
Create User ContextCreate User Context
Source files
The language and platform source files containing the implementation for Swift are available on GitHub.