Disclaimer: This website requires JavaScript to function properly. Some features may not work as expected. Please enable JavaScript in your browser settings for the best experience.

The availability of features may depend on your plan type. Contact your Customer Success Manager if you have any questions.

Dev guideRecipesAPI Reference
Dev guideAPI ReferenceUser GuideLegal TermsGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev guide

Real-Time Segments for Feature Experimentation segment qualification methods for the Swift SDK

Use the Real-Time Segments for Feature Experimentation segment methods to fetch external audience mapping for the user. You can fetch user segments with the user identifier of the user context.

Prerequisites

You must enable and configure Real-Time Segments for Feature Experimentation before fetching qualified segments and checking if the user is qualified for the given audience segment.

fetchQualifiedSegments - asynchronous

Minimum SDK version

4.0.0

Description

Fetches all qualified segments for the user context.

fetchQualfiedSegments is a method of the UserContext object. See OptimizelyUserContext for details.

Parameters

The following table describes the parameters for the fetchQualifiedSegments method:

ParameterTypeDescription
options (optional)[OptimizelySegmentOption]A set of options for fetching qualified segments from ODP.
completion(OptimizelyError?) -> VoidA completion handler to be called with the fetch result.

Returns

The completion handler to be called on completion that updates the qualified segments array.

  • On success, it passes a nil error.
  • On failure, it passes one of these errors:
    • OptimizelvError.invalidSegmentidentifier
    • OptimizelyError.fetchSegmentsFailed.

📘

Qualified segments array

You can read and write directly to the qualified segments array to bypass the remote fetching process from Optimizely Data Platform (ODP) or utilize your own fetching service. This can be helpful when testing or debugging.

Example fetchQualifiedSegments – asynchronous

The following is an example of calling the fetchQualifiedSegments method and accessing the returned completion object:

let attributes: [String: Any] = ["app_version": "1.3.2"]
let user = optimizelyClient.createUserContext(userId: "user123", attributes: attributes)
    
// Without segment option
Task {
   let attributes: [String: Any] = ["app_version": "1.3.2"]
   let user = optimizely.createUserContext(userId: "user123", attributes: attributes)
   try? user.fetchQualifiedSegments()
}

    
// With segment options
Task {
   var odpSegmentOptions: [OptimizelySegmentOption] = [.ignoreCache, .resetCache]
   let attributes: [String: Any] = ["app_version": "1.3.2"]
   let user = optimizely.createUserContext(userId: "user123", attributes: attributes)
   try? user.fetchQualifiedSegments(options: odpSegmentOptions)
}

fetchQualifiedSegments – synchronous

Minimum SDK version

4.0.0

Description

This is a synchronous version of the fetchQualifiedSegments asynchronous version above.

📘

Note

This call blocks the calling thread until fetching is completed.

Parameters

The following table describes the parameters for the fetchQualifiedSegments method:

ParameterTypeDescription
options (optional)[OptimizelySegmentOption]A set of options for fetching qualified segments from ODP.

Returns

This method does not provide a return value. If it fails, it throws one of these errors:

  • OptimizelyError.invalidSegmentIdentifier
  • OptimizelyError-fetchSegmentsFailed(String)

Example fetchQualifiedSegments - synchronous

The following is an example of calling the fetchQualifiedSegments method and accessing the returned completion object:

let optimizely = OptimizelyClient(sdkKey: <Your_SDK_Key>)

optimizely.start { result in
   let attributes: [String: Any] = ("app version": "1.3.2")
	 let user = optimizelyClient.createUserContext(userld: "user123", attributes: attributes)
                  
	 do {
      // this will block the calling thread until fetch is completed. 
      try user.fetchQualifiedSegments()

      let decision = user. decide(key: "flag1")
   } catch OptimizelyError.invalidSeqmentIdentifier {
			print("[AudienceSegments] audience segments fetch failed (user id is not registered yet or invalid)")
   } catch {
			print("[AudienceSegments] \(error)")
   }
}

The following diagram shows the network calls between your application, the Swift SDK, and the ODP server when calling fetchQualifiedSegments:

fetchQualifiedSegments Swift SDK network diagram
  1. Call the fetchQualifiedSegments method.
  2. Swift SDK makes a GraphQL call to ODP to fetch segments.
  3. ODP responds with segments.
  4. Fetched segments mapping user IDs to segments are cached.
  5. Appropriate variations are returned for the user.

The SDK fetches the segments and then caches them. This means that if the same user is requesting the segments again (when new user contexts are created), you can retrieve the audience segment information from the cache rather than from the remote ODP server.

The cache is used for the fetchQualifiedSegments call. This method is called on the user context (the user context is fixed, including the real-time segments the user qualifies for).

The cache only applies when calling the fetchQualifiedSegments call. If you set the cache timeout to 0, the cache is disabled. Optimizely uses the LRU algorithm, so the oldest record is bumped out when the maximum size is reached. If there is a cache miss upon the method call, Optimizely makes a network request.

You can add the following options to your odpSegmentOptions array to bypass caching:

  • ignoreCache – Bypass segments cache for lookup and save.
  • resetCache – Reset all segments cache.

isQualifiedFor

Minimum SDK version

4.0.0

Description

Check if the user qualifies for the given audience segment.

Parameters

The following table describes the parameters for the isQualifiedFor method:

ParameterTypeDescription
segmentStringThe ODP audience segment name to check if the user qualifies

Returns

true if the user is qualified.

Examples

The following is an example of whether or not the user qualifies for an ODP segment:

let attributes: [String: Any] = ["laptop_os": "mac"]
let user = optimizelyClient.createUserContext(userId: "user123", attributes: attributes)

user.fetchQualifiedSegments { segments, err in
   let isQualified = user.isQualifiedFor(segment: "segment1")
}

Source files

The language and platform source files containing the implementation for Swift are available on Github.