ホーム 暮らし Building an Apple Intelligence Image Generation App on iPad Only: Minimal Sample - Weekly Playgrounds Issue 23

Building an Apple Intelligence Image Generation App on iPad Only: Minimal Sample - Weekly Playgrounds Issue 23

八木 麻衣 八木 麻衣 • 更新: • 公開: • 読了約 37 分
目次

Introduction

nc91c5d77c936

With iPad Swift Playgrounds updated to version 4.7 and supporting the iOS 26 SDK, you can now experiment with app development in the era of Apple Intelligence using only an iPad.

In this issue, we will look at a simple sample that connects the brains of Apple Intelligence, Foundation Models, and Image Playground.

The user enters the image they want to generate in Japanese. Even with a simple, short sentence, Foundation Models will refine that short text into a Japanese sentence suitable for image generation. Then, Image Playground receives that refined sentence and generates the image.

In this article, we will focus only on this flow for now.
Fallbacks (alternative processing when Apple Intelligence is unavailable), features for saving and sharing generated images, and handling branches such as Apple Intelligence refusing generation (guardrail features) will be covered in the next full-spec sample code.

First, let's get a feel for how it works with such short code on just an iPad.
Including the display and the environment check for availability, it is about 180 lines.
(Download the following file or copy the code at the end of the article)
It works on an iPad that supports Apple Intelligence using the iPad Swift Playgrounds app (version 4.7 or later).

Please update and use ContentView.swift.

I have compressed the file for the iPad Swift Playgrounds app.

Did it work when you downloaded and tried it?
Some of you might not be able to generate anything.
Try entering something in the input field, for example

  • A blue night in a futuristic city

  • An abstract painting like a spring breeze

  • A geometric poster with drifting light

Try entering short sentences like these.
Then, Foundation Models will first create a "refined sentence for image generation" based on that short text, which will be displayed on the screen. Next, Image Playground will use that refined sentence to generate an image.
The important thing here is that the user does not need to write a long prompt from the start. Using short words as an entry point, Foundation Models will supplement it just a little. This is the core of this sample.

The following screenshot is an example where it could not be generated.

What the code is doing

What this code does is very simple.

1. Check the environment at startup

First, I want you to look at this.

switch SystemLanguageModel.default.availability

Here, we are checking if Foundation Models are available.

This allows us to branch the "Generate" button between

  • enabled if the environment is supported

  • disabled if the environment is not supported

as the logic.

In this simple version, we have only incorporated this availability check.
In the next full-spec version, we will also handle the "available but denied" state (guardrails) separately.

2. Creating formatted text with Foundation Models

The next core component is LanguageModelSession().

let session = LanguageModelSession()

And instead of passing the short sentence entered by the user directly to image generation, we are asking the FM to do the following:

  • One sentence in Japanese

  • For Image Playground

  • Slightly supplement with colors, atmosphere, and composition

  • No introduction or explanation needed

In other words, what we are doing here is not translation.
It is refining short Japanese input into Japanese sentences suitable for image generation.is what it is.

For example, if the input is

then we can expect the FM not to just repeat it, but to refine it into a sentence more suitable for generation.

3. Creating images with Image Playground

Once the formatted text is ready, we pass it to ImageCreator().

let creator = try await ImageCreator()

Here, the flow of "input in Japanese -> format in Japanese -> generate using that formatted text" is connected.

Since I focused only on this flow this time, the amount of code is quite small.
First, try rewriting the image to be generated in various ways with the current code.
Depending on the content of the text, there may be times when an image cannot be generated.

Next, please try rewriting the code and testing it.

What I would really like you to try with this code is to rewrite the instructions for the Foundation Models within makeJapanesePrompt(from:).

func makeJapanesePrompt(from input: String) async throws -> String 
    let session = LanguageModelSession()

    let instruction = """
    次のユーザー入力をもとに、Image Playground のイメージ生成に使いやすい日本語の説明文を1文だけ作成してください。
    条件:
    - 日本語で1文のみ
    - 60文字以上120文字以内を目安にする
    - ユーザーの意図を保ちながら、色、雰囲気、形、構図を少し補う
    - 前置きや解説は禁止
    ユーザー入力: \(input)
    """

    let response = try await session.respond(to: instruction)
    return response.content.trimmingCharacters(in: .whitespacesAndNewlines)

What we are doing here is exactly the kind of processing unique to generative AI.
Instead of passing the short Japanese input by the user directly to image generation, we are asking the Foundation Models tochange it into a formatted Japanese sentence that is easy to use in Image Playground.

This is a part I would really like you to try freely.
For example,

  • make the character count shorter

  • strengthen the "poster style"

  • add "abstract art-like qualities"

  • remove the "composition" specification

Even just making changes like these will change the atmosphere of the resulting formatted text.
And that difference will directly affect the image generation results.

While this sample aims to run with a minimal configuration, it is also designed to make it easy to experience thatthe behavior changes even by slightly altering the instructions to the Foundation Models. I recommend starting by rewriting this instruction little by little to see what kind of differences emerge.

Why this sample is simple

There are things I intentionally did not include in this code.

  • fallback drawing

  • detailed branching for refusals

  • sharing functionality

  • switching between multiple modes

  • granularity in state management of generation results

In other words, I am prioritizing clarity as a minimal configuration.

In the previous VisionKit article, the flow was also to run a short piece of code first and then organize the background. The same approach is taken this time. It is easier to understand if you grasp the connections between APIs first and then proceed to practical design.

This sample is strictly for

  • Foundation Models

  • Image Playground

  • iPad Swift Playgrounds

  • Japanese short text input

It is intended to confirm the connection of these four elements.

What becomes clear here

Running this code reveals something interesting about development in the Apple Intelligence era.

In the past, when incorporating image generation into an app, developers tended to write long English prompts from the start or require detailed input from users.

However, this time, by placing Foundation Models in the preceding stage, we can adopt a configuration where:

  • the user only needs to input short words

  • the model handles formatting into a prompt suitable for generation

.

This is not just about "using two AIs." It is a design that
reduces the burden of input while bridging to a format suitable for generation.

For example, thinking about it as an app UI:

  • the user inputs a short mood or impression

  • the app formats it for generation

  • returns it as an image

This makes it easier to create a natural flow.

Consultation Recipes for Generative AI

If you suddenly ask generative AI for code like this,

it might return something that works.

However, in that case,

  • it might assume English prompts

  • it might include unnecessarily complex state management

  • the intent of this 'minimal sample' might be diluted

can happen.

Therefore, it is easier to organize things if you set the following conditions beforehand.

Example of a consultation

By communicating it this way, the role of the code becomes quite clear.

As I have touched upon several times in this series, when consulting with generative AI, it is important to convey not only 'what to make' but also,

  • what to include

  • what not to include

  • what you want to show the reader

In Issue 19, it was also noted that by conveying 'for whom and why,' the code better reflected the intended purpose.

Next Issue Preview

This simple version is just the shortest entry point.

When you actually try to make it closer to a real app, you start to worry about things like the following:

  • What to do on devices where Foundation Models cannot be used

  • What to do if formatted text generation is rejected even in a supported environment

  • How to handle rejections or failures on the Image Playground side

  • Wanting to be able to try local drawing fallbacks in addition to AI generation

  • Wanting to share the generated results

Next time, you will likely encounter errors and failures when trying various things. Including those, we will cover the differences between using generative AI (LLM) and building existing apps, and continue with a full-spec version that includes these points.

Grasp the flow with the simple version, actually try it and analyze the errors, and then look at practical design in the full-spec version.
Following this order should make the relationship between Foundation Models and Image Playground much easier to see.

Summary

Let's organize what we confirmed this time.

  • You can create a minimal sample that connects Foundation Models and Image Playground even in iPad Swift Playgrounds

  • You only need to have the user input a short Japanese sentence

  • Foundation Models can convert that short sentence into Japanese formatted text for image generation

  • You can pass that formatted text directly to Image Playground

  • It is easier to understand if you first check the flow with minimal code, and then expand to state management and fallbacks

Instead of "sending short input directly to image generation," inserting Foundation Models in between creates a step in the app's design.
This is the interesting part of this sample.

Next time, we will look at: ・Image generation may not be possible ・Rejection (guardrails). Furthermore, in subsequent installments, we will look at the full-spec version including fallbacks.


Here is the code for this time. It is the same content as the download at the top.

import SwiftUI
import FoundationModels
import ImagePlayground

struct ContentView: View 
    @State private var inputText: String = "青い夜の未来都市"
    @State private var generatedPrompt: String = ""
    @State private var generatedImage: UIImage?

    @State private var availabilityMessage: String = "確認中..."
    @State private var isFMAvailable: Bool = false

    @State private var isLoading: Bool = false
    @State private var errorMessage: String = ""

    var body: some View 
        ScrollView
            VStack(spacing: 16) 
                VStack(alignment: .leading, spacing: 8) 
                    Text("環境状態")
                        .font(.headline)

                    Text(availabilityMessage)
                        .font(.subheadline)
                        .foregroundStyle(isFMAvailable ? .primary : .secondary)
                
                .frame(maxWidth: .infinity, alignment: .leading)

                TextField("生成したいイメージを短文で入力", text: $inputText, axis: .vertical)
                    .textFieldStyle(.roundedBorder)
                    .lineLimit(2...4)

                Button 
                    Task 
                        await generateImage()
                    
                 label: 
                    if isLoading 
                        ProgressView()
                            .frame(maxWidth: .infinity)
                     else 
                        Text("生成")
                            .frame(maxWidth: .infinity)
                    
                
                .buttonStyle(.borderedProminent)
                .disabled(!isFMAvailable 
            .padding()
            .task 
                await checkAvailability()
            
        
    

    func checkAvailability() async 
        if #available(iOS 26.0, *) 
            switch SystemLanguageModel.default.availability 
            case .available:
                isFMAvailable = true
                availabilityMessage = "Foundation Models を利用できます。"
            case .unavailable(let reason):
                isFMAvailable = false
                availabilityMessage = "Foundation Models を利用できません: \(String(describing: reason))"
            
         else 
            isFMAvailable = false
            availabilityMessage = "iOS 26 以降が必要です。"
        
    

    func generateImage() async 
        let trimmed = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else  return 

        isLoading = true
        errorMessage = ""
        generatedPrompt = ""
        generatedImage = nil

        defer 
            isLoading = false
        

        do 
            let prompt = try await makeJapanesePrompt(from: trimmed)
            generatedPrompt = prompt

            let image = try await makeImage(from: prompt)
            generatedImage = image

         catch 
            errorMessage = error.localizedDescription
        
    

    func makeJapanesePrompt(from input: String) async throws -> String 
        let session = LanguageModelSession()

        let instruction = """
        次のユーザー入力をもとに、Image Playground のイメージ生成に使いやすい日本語の説明文を1文だけ作成してください。
        条件:
        - 日本語で1文のみ
        - 60文字以上120文字以内を目安にする
        - ユーザーの意図を保ちながら、色、雰囲気、形、構図を少し補う
        - 前置きや解説は禁止
        ユーザー入力: \(input)
        """

        let response = try await session.respond(to: instruction)
        return response.content.trimmingCharacters(in: .whitespacesAndNewlines)
    

    func makeImage(from prompt: String) async throws -> UIImage 
        let creator = try await ImageCreator()

        guard let style = creator.availableStyles.first else 
            throw SimpleSampleError.noStyleAvailable
        

        let stream = creator.images(
            for: [.text(prompt)],
            style: style,
            limit: 1
        )

        for try await result in stream 
            return UIImage(cgImage: result.cgImage)
        

        throw SimpleSampleError.imageNotGenerated
    


enum SimpleSampleError: LocalizedError 
    case noStyleAvailable
    case imageNotGenerated

    var errorDescription: String? 
        switch self 
        case .noStyleAvailable:
            return "利用可能なスタイルが見つかりませんでした。"
        case .imageNotGenerated:
            return "画像を生成できませんでした。"
        
    



同じカテゴリの記事

八木 麻衣
トレンドリサーチャー 八木 麻衣
プロフィールを見る →

全記事の事実確認を担当。一次情報・公式発表・公開資料の三点を確認できない場合は公開を見送る判断をします。

おすすめの関連記事