Skip to content

Ai Image Generation

Mr.P edited this page Aug 29, 2026 · 2 revisions

Image Generation

Generate one or more UIImage results from a text prompt. Provider limits and selectable styles are optional capabilities; they are not prerequisites for submitting a generation task.

Image-generation task lifecycle

Prepare a prompt, use provider limits or styles when available, and fall back to the default task configuration when they are not exposed.

  1. Prepare Prompt — Require a nonempty description of the images to generate.
  2. Read Optional Limit — Use a positive provider maximum when available; otherwise request one image.
  3. Load Optional Styles — Use a returned styleCode when the provider exposes styles; otherwise leave style empty.
  4. Configure Task — Set the resolved count and style, plus optional size and language.
  5. Create Task — Start generation and retain the task ID from onTaskCreated.
  6. Receive Images — Use success, images, task ID, and error from the completion callback.

Prerequisites

  • Initialize AIBudsAISDK, select a provider, and complete provider authentication when required.
  • Confirm that the selected provider implements AIGCServiceAPI.
  • Define an application policy for displaying, storing, and sharing generated images.

API Reference

Framework

AIBudsAI.xcframework

Declaration

Swift

/// The available styles cached by the selected image-generation provider.
static var aigcStyles: [AIGCStyleModel]? { get }

/// The maximum number of images accepted in one task. A positive value can be
/// used to constrain the requested image count.
static var aigcMaxGenerateCount: Int { get }

/// Fetches styles supported by the selected provider.
public static func fetchAigcStyles(completion: ((_ styles: [AIGCStyleModel]?, _ error: NSError?) -> Void)? = nil)

/// Generates images from a text prompt and configuration.
/// - Parameters:
///   - prompt: The text prompt for image generation.
///   - config: Task configuration. Defaults to `.default`.
///   - onTaskCreated: Called with the provider task identifier.
///   - completion: Returns the task identifier, success flag, generated images,
///     and failure information.
public static func generateAIPhoto(prompt: String,
                                   config: AIGCTaskConfig = .default,
                            onTaskCreated: ((_ taskId: String) -> Void)? = nil,
                               completion: ((
                                   _ taskId: String?,
                                   _ success: Bool,
                                   _ images: [UIImage]?,
                                   _ error: NSError?
                               ) -> Void)? = nil)

Objective-C

/// Styles cached by the selected image-generation provider.
@property(nonatomic, class, readonly, copy) NSArray<AIBudsAIGCStyleModel *> *_Nullable aigcStyles;

/// Maximum image count accepted by one provider task.
@property(nonatomic, class, readonly) NSInteger aigcMaxGenerateCount;

/// Fetches styles supported by the selected provider.
+ (void)fetchAigcStylesWithCompletion:(void (^ _Nullable)(NSArray<AIBudsAIGCStyleModel *> * _Nullable, NSError * _Nullable))completion;

/// Generates images from a text prompt and configuration.
+ (void)generateAIPhotoWithPrompt:(NSString * _Nonnull)prompt
                           config:(AIBudsAIGCTaskConfig * _Nonnull)config
                      taskCreated:(void (^ _Nullable)(NSString * _Nonnull))onTaskCreated
                       completion:(void (^ _Nullable)(NSString * _Nullable, BOOL, NSArray<UIImage *> * _Nullable, NSError * _Nullable))completion;

See generateAIPhoto, fetchAigcStyles, and AIGCTaskConfig.

Task Configuration

Property Meaning
style Provider style code returned by AIGCStyleModel.styleCode. Leave it as nil when styles are unavailable or the app does not offer style selection.
imageCount Requested count. Use the default value 1 when no positive aigcMaxGenerateCount is available; otherwise keep it within the reported limit.
imageSize Optional positive width and height; nil uses the provider default.
language Prompt language such as en-US; nil uses app localization and an empty string requests auto-detection when supported.

Usage Examples

Generate with Optional Provider Capabilities

If the app does not offer style selection, skip fetchAigcStyles and call the generation helper with nil. The example below attempts to load styles but still submits the prompt when the style list is empty or the request fails.

Swift

let prompt = "A lightweight wearable assistant on a clean studio background"

func generate(styleCode: String?) {
    let maximum = AIBudsAISDK.aigcMaxGenerateCount
    let config = AIGCTaskConfig()
    config.style = styleCode
    config.imageCount = maximum > 0 ? min(2, maximum) : 1
    config.language = "en-US"

    AIBudsAISDK.generateAIPhoto(
        prompt: prompt,
        config: config,
        onTaskCreated: { taskID in
            DispatchQueue.main.async { showTask(id: taskID) }
        },
        completion: { taskID, success, images, error in
            DispatchQueue.main.async {
                guard success, let images, !images.isEmpty else {
                    if let error {
                        show(error)
                    } else {
                        print("The provider returned no images")
                    }
                    return
                }
                show(images: images, taskID: taskID)
            }
        }
    )
}

AIBudsAISDK.fetchAigcStyles { styles, error in
    // Style discovery is optional. A nil style uses the provider default.
    let styleCode = error == nil ? styles?.first?.styleCode : nil
    generate(styleCode: styleCode)
}

Objective-C

NSString *prompt = @"A lightweight wearable assistant on a clean studio background";

void (^generate)(NSString *_Nullable) = ^(NSString *styleCode) {
    NSInteger maximum = AIBudsAISDK.aigcMaxGenerateCount;
    AIBudsAIGCTaskConfig *config = [[AIBudsAIGCTaskConfig alloc] init];
    config.style = styleCode;
    config.imageCount = maximum > 0 ? MIN(2, maximum) : 1;
    config.language = @"en-US";

    [AIBudsAISDK generateAIPhotoWithPrompt:prompt
        config:config
        taskCreated:^(NSString *taskID) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showTaskID:taskID];
            });
        }
        completion:^(
            NSString *taskID, BOOL success, NSArray<UIImage *> *images, NSError *generationError) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!success || images.count == 0) {
                    [self showError:generationError];
                    return;
                }
                [self showImages:images taskID:taskID];
            });
        }];
};

[AIBudsAISDK
    fetchAigcStylesWithCompletion:^(NSArray<AIBudsAIGCStyleModel *> *styles, NSError *error) {
        // Style discovery is optional. A nil style uses the provider default.
        NSString *styleCode = error == nil ? styles.firstObject.styleCode : nil;
        generate(styleCode);
    }];

Error Handling

A style-fetch failure or an unavailable generation limit is not a generation failure. Fall back to style = nil and imageCount = 1, then treat the generation completion callback as the authoritative task result.

Notes

  • Style codes and positive maximum counts are optional provider data and can change; do not hard-code the Demo values.
  • An empty style list is valid. Submit the prompt with style = nil to use the provider default.
  • The task-created callback does not mean images have been generated successfully.
  • The public API does not currently expose image-generation progress or cancellation.

AIBuds SDK iOS Wiki

Clone this wiki locally