Blog

Blog

Tutorial: How to Run Live2D Cubism Native Sample in SwiftUI

A step-by-step tutorial that shows you how to build a Live2D app with the Cubism SDK for Native in SwiftUI

#Live2D#iOSDevelopment

An iOS simulator running the Live2D Native demo app.

Figure. Running the Live2D Demo App in SwiftUI.

Tutorial: How to Run Live2D Cubism Native Sample in SwiftUI

You can find the tutorial Xcode project and patched code in cubism-sample-swiftui-prod.

This tutorial explains how to build a SwiftUI Xcode project from the Live2D Cubism SDK for Native. The SDK provides a UIKit-based sample app for iOS devices (the Sample app). However, likely to meet cross-platform requirements, the Sample app is built with a CMake-generated Xcode project that references source code and assets throughout the SDK folder. This design makes it difficult to manage project configurations, such as Xcode build settings, build phases, code files, and assets, with source control. Unless you plan to build an app without ever touching Xcode, you will most likely need to create an Xcode project from scratch.

In addition, the Sample app uses UIKit and a mix of Objective-C++ and C++ code, which probably feels "legacy" to many of today's iOS developers, who prefer (or start with) Swift and SwiftUI. Swift and SwiftUI not only have simpler syntax that helps you build faster, but also make long-term project management easier.

This is a hands-on tutorial on how to build a SwiftUI Xcode project from the Sample app. Step by step, we will show how to add the Cubism Core and the Cubism Framework to an Xcode project, and how to configure the project to compile all the source code in a single build target. We will then explain how to convert the Sample app into a SwiftUI app.

Learning Objectives: By the end of this post, you will:

  • Build a working Xcode project from the Cubism Sample app
  • Understand the composition of the Cubism SDK and the Sample app
  • Understand how to compile Objective-C/C++ code in a SwiftUI project
  • Understand how to (roughly) convert a UIKit-based app to a SwiftUI app

Prerequisites: To complete this post successfully, you'll need:

  • Cubism 5 SDK for Native R5
  • macOS and Xcode that can build and run an iOS project
  • Basic understanding of Swift/SwiftUI apps (syntax and code structure)
  • Basic understanding of bash, zsh, or similar shell scripting
  • Willingness to read and modify Objective-C/C++ code

Overview

  • Download the Cubism Native SDK (Core, Framework, Sample)
    • Download the SDK from the official website
    • Build an XCFramework from the Core SDK
  • Build and configure an Xcode project
    • Copy source files from the Framework and the Sample app
    • Configure the project to build the framework and the app
  • Compile everything in Xcode
    • Compile Metal shader code (.metal) to libraries (.metallib)
    • Compile the Framework
    • Compile the Sample app code
  • Build a SwiftUI app from the UIKit Sample app
    • Migrate to SwiftUI: Remove SceneDelegate and Move Its States
    • Wire up the AppDelegate and ViewController to SwiftUI
    • Add missing resources to the app bundle
    • Build and test on a simulator and a physical device

Step 1: Download the Cubism Native SDK (Core, Framework, Sample)

Download the SDK from the Official Website

Go to the Live2D official website and download the Cubism SDK for Native. Read through the Software License Agreement and, if you consent to the License, download the Cubism 5 SDK for Native R5. You will get a zip file like CubismSdkForNative-5-r.5.zip.

Unzip the archive, and you should see three folders: Core, Framework, and Samples. These are the three pillars of Live2D Cubism applications (see Cubism Core API Reference) and contain everything we need to build our SwiftUI app.

CubismSdkForNative-5-r.5
├── Core
│   ├── dll
│   ├── include     // we need this
│   └── lib
├── Framework
│   └── src         // we need this
└── Samples
    ├── Common
    ├── D3D11
    ├── D3D9
    ├── Metal       // we need this
    ├── OpenGL
    ├── Resources   // we need this
    └── Vulkan

In this post, we do not need to build the Sample app with cmake. We will grab the source code files directly and build our Xcode project from scratch. To learn more about this SDK, you can read our blog post How to Set Up a Live2D Cubism Native App in Xcode.

Build an XCFramework from the Core SDK

First, we need to obtain a copy of the Cubism Core library built for iOS platforms. The Core comes with the necessary APIs to process Live2D model files from the Cubism Editor. Open Core/lib/ios and you should see the following:

CubismSdkForNative-5-r.5/Core/lib/ios
├── Debug-iphoneos
├── Debug-iphonesimulator-arm64
├── Debug-iphonesimulator-x86_64
├── Release-iphoneos
│   └── libLive2DCubismCore.a         // *
├── Release-iphonesimulator-arm64
│   └── libLive2DCubismCore.a         // *
└── Release-iphonesimulator-x86_64

The R5 SDK comes with static libraries (.a) for physical devices (iphoneos) and simulators (iphonesimulator). Here we will use the release builds of iphoneos and the arm64 version of iphonesimulator. To make it easier to add the Core to an Xcode project, we can build an XCFramework from the static libraries:

CORE_DIR="CubismSdkForNative-5-r.5/Core"

xcodebuild -create-xcframework \
  -library "$CORE_DIR/lib/ios/Release-iphoneos/libLive2DCubismCore.a" \
  -headers "$CORE_DIR/include" \
  -library "$CORE_DIR/lib/ios/Release-iphonesimulator-arm64/libLive2DCubismCore.a" \
  -headers "$CORE_DIR/include" \
  -output Live2DCubismCore.xcframework

After that, you should see a Live2DCubismCore.xcframework folder, as shown below. We will need it when compiling the Cubism Framework.

Live2DCubismCore.xcframework
├── Info.plist
├── ios-arm64
│   ├── Headers
│   │   └── Live2DCubismCore.h
│   └── libLive2DCubismCore.a
└── ios-arm64-simulator
    ├── Headers
    │   └── Live2DCubismCore.h
    └── libLive2DCubismCore.a

Step 2: Build and Configure an Xcode Project

Next, we need an Xcode project to build and run a SwiftUI app. Open Xcode and create a new SwiftUI project, which we call SwiftSampleApp:

SwiftSampleApp
├── SwiftSampleApp
│   ├── Assets.xcassets
│   ├── ContentView.swift
│   └── MyApp.swift
└── SwiftSampleApp.xcodeproj
    ├── project.xcworkspace
    ├── xcuserdata
    └── project.xcproj

Copy source files from the Framework and the Sample app

We need to copy the source files from the Framework and the Sample app to the Xcode project. First, create a static library target in the project settings:

  • Open the Xcode project settings (the top-level item in the left Navigators).
  • In the TARGETS panel, click the "+" at the bottom left to add a static library.
  • Set the product name to Live2DCubismFramework.
  • Set the language to Objective-C.
  • Click Finish to create the target.

You should see a new folder Live2DCubismFramework in the navigators. Next, we need to copy the source code from the Framework in the SDK:

  • In the SDK folder, find Framework/src.
  • Drag the whole src folder into the Live2DCubismFramework folder in the Xcode navigators.
  • Xcode will ask you to choose options for adding the files:
    • Set Action to "Copy files to destination".
    • In Targets, check the static library target Live2DCubismFramework we just created.
    • Once you click Finish, you will see the source code files in the navigators.
  • Also, drag the Live2DCubismCore.xcframework we created above into the Xcode project.
    • Action: "Copy files to destination"
    • Targets: only check the Live2DCubismFramework target.
  • (Optional) Delete all CMakeLists.txt files from the subfolders.
  • (Optional) Except for src/Rendering/Metal, delete all platform folders in the src/Rendering folder.

Next, copy the Sample app code to the project:

  • Create a new Live2DCubismSample folder in the Xcode navigators.
  • In the SDK folder, find Samples/Metal. Drag the following into Live2DCubismSample:
    • Samples/Metal/Demo/proj.ios.cmake/src
    • Samples/Metal/thirdParty/stb
  • Xcode will ask you to choose options for adding the files:
    • Action: "Copy files to destination"
    • Targets: only check the target SwiftSampleApp.
  • In the src folder, delete Info.plist and main.m.
  • (Optional) Delete all CMakeLists.txt files from the subfolders.

At this point, we have all the files we need to build the SwiftUI app. However, the project isn't ready to compile yet and would throw all kinds of errors. To fix that, we need to adjust some project settings.

Configure the project to build the framework and the app

When you are working on this part, make sure you select the right target in the left panel of the project settings. Each target has its own settings.

If you do not see any build settings listed, try switching to "All" on the second row of the Build Settings tab. If you see names in constant style, e.g., "SWIFT_OBJC_BRIDGING_HEADER", switch from "Names" to "Title" on the second row. For more details about build settings, check out the build settings reference.

We need to configure the project to build the framework and the app separately. This can be frustrating because the Xcode UI is a bit complicated. Below is a step-by-step list to configure the project. Note that this configuration is not complete yet; we will come back to it when we see compilation errors later.

For the framework target:

Let's start with the framework target. The Framework C++ code needs to know where to find the required headers. Because part of the code uses quoted includes and the rest uses angled ones, we need to set both the system and user header search paths.

  • Go to the Xcode project settings and select Live2DCubismFramework.
  • Under Build Settings:
    • "System Header Search Paths" = Live2DCubismFramework/src, non-recursive.
    • "User Header Search Paths" = Live2DCubismFramework/src, recursive.

For the app target:

There are three things to set here: header search paths, Swift/C++ interop, and a bridging header. Like the framework, some Sample app code needs to know about the Framework headers. Also, because we are compiling the ObjC/C++ Sample code in our Swift project, we need to enable interop and add a bridging header.

  • Create a file "cubism_bridge_header.h" in Live2DCubismSample/src.
  • Go to the Xcode project settings and select the app target.
  • Under Build Settings:
    • "System Header Search Paths" = Live2DCubismFramework/src, non-recursive.
    • "User Header Search Paths" = Live2DCubismSample/stb, non-recursive.
    • "C++ and Objective-C Interoperability" = "C++ / Objective-C++"
    • "Bridging Header" = Live2DCubismSample/src/cubism_bridge_header.h

Step 3: Compile Everything in Xcode

At this point, your Xcode project can compile to some extent, but you will start seeing error messages such as Metal compilation errors or undefined symbols. To compile the app successfully, we need to update the build process. Specifically, we will update the Build Phases (and some source code) to compile Metal shaders, the Framework, and the Sample app.

Compile Metal shader code (.metal) to libraries (.metallib)

This version of the Cubism SDK for Native includes many Metal shader files (.metal) that must be compiled into libraries (.metallib) before building the Framework. By default, Xcode compiles them together into one default library. Unfortunately, this does not fit the Framework's workflow, which needs each Metal shader in its own library. Instead of refactoring the Framework's shader loader, we replicate the existing workflow in Xcode with a script.

First, we need to disable the default Metal compilation process in Xcode:

  • Go to the Build Phases of the Live2DCubismFramework target.
  • Under Compile Sources, remove all .metal files. Hold the Command key to select multiple files, then press Delete to remove them together.

Be careful not to remove any other source files. If you remove one by accident, you can add it back when the compiler complains that the file is missing. Or, consider using git or another version control tool to track your Xcode project file.

Once the .metal files are removed from the list, Xcode will no longer compile the shader files for you. Now we can add a script step to compile each shader file into a library:

  • Go to the Build Phases of the Live2DCubismFramework target.
  • Click the plus sign ("+") in the top left and add a new Run Script phase.
  • (Optional) Rename the phase to "Compile Metal Shaders" or something readable.
  • (Optional) Drag the phase before the Compile Sources phase.
  • Copy and paste the compile_metal_shaders.sh script below into the Run Script phase.

Due to the user script sandboxing setting, we have to declare the input and output files:

  • Add two files to SwiftSampleApp: MetalInputs.xcfilelist and MetalOutputs.xcfilelist.
  • Fill in their content by following our examples:
  • In the same Run Script phase:
    • Add $(SRCROOT)/SwiftSampleApp/MetalInputs.xcfilelist to Input File Lists.
    • Add $(SRCROOT)/SwiftSampleApp/MetalOutputs.xcfilelist to Output File Lists.

compile_metal_shaders.sh:

# Compile each Metal shader file to a library of the same name. It will output multiple .metallib files (and intermediate .air artifacts) to the Xcode product folder. Later, we will use another script to move the .metallib files into the app bundle.

set -e

SRC_DIR="$SRCROOT/Live2DCubismFramework/src/Rendering/Metal/Shaders"
AIR_DIR="$DERIVED_FILE_DIR/FrameworkShaders/MetalAir"
OUT_DIR="$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/FrameworkShaders/FrameworkMetallibs"

mkdir -p "$AIR_DIR" "$OUT_DIR"

for f in "$SRC_DIR"/*.metal; do
  name=$(basename "$f" .metal)
  srcFile="$f"
  airFile="$AIR_DIR/$name.air"
  outFile="$OUT_DIR/$name.metallib"

  echo "Compiling: $name"
  xcrun -sdk "$PLATFORM_NAME" metal -D CSM_ALPHA_BLEND_MODE=1 -D CSM_COLOR_BLEND_MODE=1 -c "$srcFile" -o "$airFile"
  xcrun -sdk "$PLATFORM_NAME" metallib "$airFile" -o "$outFile"

  echo "Done: $outFile"
done

Once the Run Script phase is ready, rebuilding the framework target will produce multiple .metallib files in the build products folder, even though Xcode still fails to compile the rest of the source code. To find the products folder, choose "Product" > "Show Build Folder in Finder" from the Xcode menu. You should see something like:

.../Debug-iphonesimulator/
├── FrameworkShaders
│   └── FrameworkMetallibs
│       ├── FragShaderSrcAlphaBlend.metallib
│       ├── FragShaderSrcBlend.metallib
│       ├── FragShaderSrcColorBlend.metallib
│       ├── FragShaderSrcMaskBlend.metallib
│       ├── FragShaderSrcMaskInvertedBlend.metallib
│       ├── FragShaderSrcMaskInvertedPremultipliedAlphaBlend.metallib
│       ├── FragShaderSrcMaskPremultipliedAlphaBlend.metallib
│       ├── FragShaderSrcPremultipliedAlphaBlend.metallib
│       ├── MetalShaders.metallib
│       ├── VertShaderSrcBlend.metallib
│       └── VertShaderSrcMaskedBlend.metallib
└── ...

We will add these files to our app bundle later. Now, let's get Xcode to compile the Framework code.

Compile the Framework

The complete build phases list in the framework

Figure. The complete build phases list in the framework.

We just copied multiple source files from the Framework to our static library Live2DCubismFramework. If you try to build it, you should see a bunch of error messages about "ARC" or the "release" and "autorelease" keywords. ARC stands for Automatic Reference Counting, a memory management system used by Swift and Objective-C in Xcode. In this project, all you need to know is that ARC does not allow you to call methods like release to manage memory manually.

You can learn more about ARC from this WWDC video or the wiki page.

Instead of refactoring the Framework code that manages memory manually, we resort to adding the "no ARC" flag to some source files. To do this:

  • Go to Build Phases of the Live2DCubismFramework target.
  • Under Compile Sources, add -fno-objc-arc to the Compiler Flags of files that raise ARC errors.

If you have time, you can fix each file one by one instead. These are the files we flagged in our project:

  • CubismShader_Metal.mm
  • CubismRenderTarget_Metal.mm
  • CubismCommandBuffer_Metal.mm

After setting the flag, Live2DCubismFramework should compile successfully!

...but there are a LOT of issues and warnings, mostly about parameters not found in declarations. If you have time, or really want to use this in production, we suggest going over the code and addressing them, including the ARC issues.

Compile the Sample app code

The complete build phase list in the app target

Figure. The complete build phase list in the app target.

The next challenge is compiling the Sample app code in Xcode. This is very similar to compiling the Framework, except that we need to link additional libraries and patch some of the code. If you try to build the app target now, you will see errors flying around.

Let's fix them step by step. First, we need to add the Live2DCubismFramework we just built to the app target:

  • Go to the Build Phases of the SwiftSampleApp app target.
  • Under "Link Binary With Libraries":
    • Add libLive2DCubismFramework.a from our project.
    • Also add MetalKit.framework from the Apple SDKs.

Next, we also need to disable ARC for some Sample code files. Under Compile Sources, add -fno-objc-arc to the Compiler Flags of the files in the following list:

  • AppDelegate.mm
  • LAppLive2DManager.mm
  • LAppSprite.mm
  • LAppModelSprite.mm
  • LAppTextureManager.mm
  • ViewController.mm
  • MetalView.m

In the same Compile Sources list, also delete SceneDelegate.mm. We do not need this file in our SwiftUI app because SwiftUI has its own scene management process. We will cover this later when we start building the app.

Xcode should start complaining that some methods should not return a value. This is because some void functions in the Sample code return nil;, which is not allowed in our build setup. We need to open these files and replace those statements with return;. Here is the list to go through:

  • LAppSprite.mm
    • Remove the "return self" statement from "resizeImmidiate".
    • Replace "return nil;" with "return;" in SetMTLFunction.
    • Replace "return nil;" with "return;" in SetMTLRenderPipelineState.

Step 4: Build a SwiftUI App from the UIKit Sample App

At this point, the compiler starts complaining about undefined symbols in the app code. That's a good sign! To make the Sample code work in SwiftUI, we need to remove some legacy UIKit code.

Migrate to SwiftUI: Remove SceneDelegate and Move Its States

You can find the patched files in SwiftSampleApp/Live2DCubismSample/src.

For your reference, we also keep a copy of the changes we made in changes.patch. It may help you find where and how to patch the source code. Because the file may be incomplete, your compiler and its error messages remain the best source of truth. Keep addressing issues iteratively.

Also, Xcode does not report compiler errors in some Objective-C/C++ code, only issues and warnings. Check the Xcode Issue Navigator for any glaring issues in those files.

An illustration that shows the before and after patterns

Figure. The Pattern Before and After the Migration.

The original sample code is based on UIKit and comes with a SceneDelegate. This is the UIKit way to manage life cycle events in a scene (see UISceneDelegate). SwiftUI has its own life cycle system for managing scenes, so we no longer need the scene delegate. To remove it:

  1. Remove SceneDelegate.mm and SceneDelegate.h from Live2DCubismSample/src.
  2. Remove scene-related imports and processes from the source code.
  3. Move the states managed by the scene delegate elsewhere.

The first step is easy, but the other two may be ambiguous. This is the most difficult part of the tutorial: we need to replace the scene delegate and transfer its responsibilities elsewhere, such as the AppDelegate. If you get lost, you can download complete copies of those files from our repository. See SwiftSampleApp/Live2DCubismSample/src for more details.

Here is what we did during the migration:

  1. Remove scene-related processes from AppDelegate.
  2. Keep a reference to ViewController and an LAppTextureManager in AppDelegate.
  3. Add a singleton property to AppDelegate so other code can access the view controller and the texture manager.
  4. Remove all "SceneDelegate.h" imports from the rest of the code base.
  5. Replace all other access to the view controller and the texture manager with the AppDelegate versions.

After this, Xcode should compile and run the app successfully, but the screen is still empty.

Wire up the AppDelegate and ViewController to SwiftUI

Now, we need to wire up the app delegate and the view controller to our SwiftUI view. We can do this with @UIApplicationDelegateAdaptor and call those Objective-C/C++ types from Swift through the bridging header.

First, update our MyApp.swift:

import SwiftUI

@main struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            Live2DView().ignoresSafeArea()
        }
    }
}

struct Live2DView: UIViewControllerRepresentable {

    func makeUIViewController(context: Context) -> ViewController {
        let vc = ViewController()
        AppDelegate.sharedInstance().viewController = vc
        return vc
    }

    func updateUIViewController(
        _ uiViewController: ViewController,
        context: Context
    ) {}
}

Xcode will throw many errors around ViewController and AppDelegate. To fix them, import their headers in the cubism_bridge_header.h file we created earlier:

#import "AppDelegate.h"
#import "ViewController.h"

Now, all of the above errors should be gone. If you run the app again, you will see the following messages in the console:

[CSM][I]Live2D Cubism Core version: 06.00.0001 (100663297)
[CSM][I]CubismFramework::StartUp() is complete.
[CSM][I]CubismFramework::Initialize() is complete.

This means our SwiftUI app successfully found the AppDelegate and initialized the Cubism SDK! However, the app crashes right after that with EXC_BAD_ACCESS. This is because we haven't added assets and resources to the app bundle, such as Live2D models, background images, and shader libraries.

Add missing resources to the app bundle

There are several things we need to include in the app bundle: Live2D model files, background images, and shader libraries.

Assets such as Live2D models and background images:

The Cubism SDK ships with a set of example Live2D models in Samples/Resources. We need to copy them to our app bundle.

  • Go to the Build Phases of the app target.
  • Add a new Copy Files phase and rename it to "Copy Live2D Resources".
    • Destination: "Resources"
    • Subpath: "Res" (which matches the setting in LAppDefine.mm)
  • Use "+ > Add Other…" to add the whole Samples/Resources folder.

The SpriteEffect shader from the Cubism Sample code:

  • Go to the Build Phases of the app target.
  • Add a new Copy Bundle Resources phase if it's not already there.
  • Use "+ > Add Other…" to add the whole SwiftSampleApp/Live2DCubismSample/src/Shaders folder to the bundle resources.

Compiled Metal shaders (.metallib):

  • Go to the Build Phases of the app target.
  • Add a new Run Script phase and rename it to "Copy Compiled Metal Shaders".
  • Add the following script to the script box.
  • Add the following xcfilelists to the input and output file lists:

copy_compiled_metal_shaders.sh:

set -e

SRC="${BUILT_PRODUCTS_DIR}/FrameworkShaders/FrameworkMetallibs"
DST="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/FrameworkMetallibs"
if [ ! -d "$SRC" ]; then
  echo "Failed: Framework metallibs not found at $SRC"
  exit 1
fi

mkdir -p "$DST"

found=0
for lib in "$SRC"/*.metallib; do
  [ -e "$lib" ] || continue
  cp -f "$lib" "$DST/"
  echo "Copied $(basename "$lib") to $DST"
  found=1
done

if [ "$found" -eq 0 ]; then
  echo "Failed: No .metallib files found in $SRC"
  exit 1
fi

Build and test on a simulator and a physical device

Congrats! You should now be able to build and run the app on a simulator or a physical device. All functionality should be the same as the original (drag to track, tap to play a motion, tap the gear to change to the next model, etc.), except for some issues with certain Live2D models (see Limitations below). From this project, you can start building new features with Swift/SwiftUI. You can also rewrite the view controller and app delegate for better state management, especially if you plan to build more features into your app.

A screenshot that shows the app running in an iPhone simulator

Figure. The app running in an iPhone simulator.

Conclusion

In this post, we walked through how to turn the Cubism Native Sample app into a SwiftUI Xcode project. We built an XCFramework from the Cubism Core, added the Cubism Framework as a static library target, and configured the project to compile Objective-C/C++ code next to Swift. To make the code work in SwiftUI, we removed the UIKit SceneDelegate and transferred its responsibilities to the AppDelegate. Finally, we wrote a simple SwiftUI wrapper to run the app with the same Cubism Native workflow.

Keep in mind that this app is still a UIKit sample wearing a SwiftUI coat. Much of the legacy logic is intact, many warnings remain, and some Live2D models may not render correctly. For a production app, you'll probably want to go further: clean up the ARC issues, trim the Objective-C/C++ code down to a thin wrapper, and expose a Swift-friendly interface for controlling the Live2D model.

We hope this tutorial gives you a solid starting point.

Limitations

The SwiftUI sample app is based on the original Sample app. The overall logic should be almost the same as the original, including control, view, state, resource, and asset management. Because the logic is not optimized for SwiftUI, the app may have performance issues or produce inconsistent results in SwiftUI views. We also found that some Live2D models do not work in the SwiftUI app due to unknown shader issues.

If you plan to build an app for production, we suggest that you review the original Sample code, refactor or clean up legacy features, and rebuild the Cubism initialization process to better integrate the logic into the modern SwiftUI life cycle. For example, you can minimize Objective-C/C++ code by keeping only a light wrapper around the Sample view controller with the abilities you need, cleaning up deprecated types and features, and exposing public interfaces for Swift views to control the Live2D model.

References