@craft-native/ios
Build native iOS apps with web technologies using Craft.
Bluetooth GATT discovery includes iOS-connected peripherals matching the requested
services as well as new advertisements. A watch connected through another app can
therefore appear without changing its system pairing. Discovery still requires
Bluetooth permission and does not prove that the device accepts the app's protocol.
Compact tab accessories
Native and hybrid tab bars stay expanded while scrolling. An accessory can use
iconOnly: true for a 48-point trailing button above the tabs:
craft.navigation.setOptions({
tabAccessory: { path: '/messages', title: 'Messages', symbol: 'message', iconOnly: true, badge: '3' },
})
The title remains its accessible name and the badge announces the unread count.
The compact button overlays content: it adds no bottom safe-area inset and no
extra --craft-tab-bar-height reservation in hybrid web pages. A native
screen's vertical scroll views and lists get room at their end; a web page is
told how far the button reaches up into it as --craft-floating-actions-height
(and the craftFloatingActionsLayout event), for padding such as
max(var(--craft-tab-bar-height, 0px), var(--craft-floating-actions-height, 0px)). Set
tabAccessory: null to remove it. Accessories without iconOnly keep the
system's standard presentation. Removing an accessory keeps all tabs expanded.
Native celebration
Any native View may opt into a finite card entrance, light sweep and confetti
burst with :celebration="{ replay: replayCount, enabled: true }". The numeric
replay value identifies the request: unrelated renders keep the current run;
increment it to replay. enabled: false displays an existing card quietly.
The effect takes three seconds, uses native animation frames, never captures
touches, and keeps the view's authored transform. iOS Reduce Motion and Android's
disabled animations show the complete content without movement or confetti.
Leaving the screen, detaching the view or backgrounding the app cancels the
decoration. Resuming does not replay it. Available on both native renderers.
Features
Core
- WKWebView - Native iOS WebView with full JavaScript support
- Safe Areas - Automatic handling of notch and home indicator
- Dark Mode - Native dark/light theme support
Input & Feedback
- Native Speech Recognition - iOS SFSpeechRecognizer (works offline!)
- Haptic Feedback - UIImpactFeedbackGenerator, UINotificationFeedbackGenerator
- Audio Recording - AVAudioRecorder with compressed output
- Video Recording - UIImagePickerController video capture
Shake gesture configuration
enableShakeGesture is an opt-in boolean, separate from
enableMotionSensors. It defaults to false and arms the host's shake gesture
only while the app is in the foreground. Both configuration readers validate
its type: an invalid value rejects the configuration instead of letting the
Swift and Zig hosts disagree about which capabilities are enabled.
Native voice capture
With enableAudioRecording, the native renderer exposes
craft.audioRecording.start(owner, { maxSeconds }), stop(owner) and
cancel(owner). Use a fresh UUID owner and at most 300 seconds. Stop returns
an owned temporary M4A descriptor with its MIME type, size and duration for
craft.files multipart uploads. Cancel and backgrounding erase the recording.
Permission is answered on the main thread. Recorder startup, stopping and
file inspection run on a serial audio queue. Startup has a 15-second deadline
after permission is granted; cancellation or timeout prevents a delayed encoder
from publishing a recording. A startup failure leaves the interface responsive. Deletion runs independently of
encoder work, so a stalled encoder cannot retain a cancelled capture. Voice files
use their own temporary namespace and are erased on the next native launch after
an interruption or process termination, including the earlier recorder's M4A files.
Picked files and downloads retain their separate lifetime.
For cancellation diagnostics, the native voice-recording log records the
removal queue delay, removal duration, ownership check and whether the path still
exists, without including the path or audio content. The blocked-encoder unit
test retains the same receipt alongside each file-absence predicate observation
in its XCResult. Its original two-second cleanup bound still applies before the
encoder is released. These observations distinguish delayed removal from a
missed observation; a later passing run alone does not explain issue #448's
original timeout.
Device Access
- Camera & Gallery - Take photos or pick from gallery
- Barcode/QR Scanner - VisionKit DataScanner (iOS 16+)
- File Picker - UIDocumentPickerViewController
- File Download - Download and save files to device
Sensors & Location
- Geolocation - GPS and network location via CLLocationManager
- Motion Sensors - Accelerometer & gyroscope via CoreMotion
- NFC - Read NFC tags via CoreNFC
Communication
- Share Sheet - Native UIActivityViewController
- Clipboard - Read and write to system clipboard
- Push Notifications - APNs integration
Security & Auth
- Biometric Auth - Face ID / Touch ID
- Social Auth - Apple Sign In
- Secure Storage - Keychain integration
Data & Storage
- Local Database - SQLite with full SQL support
- Bluetooth LE - CoreBluetooth scanning
System
- Device Info - Device model, OS version, screen info
- Network Status - Connection type monitoring (WiFi/Cellular)
- App Badge - Notification badge count
- App State - Foreground/background detection
- Flashlight - Camera flash control
- Open URL - External browser launch
- Vibration - Custom vibration patterns
- App Review - StoreKit review prompt
- Screen Capture - Take screenshots programmatically
- Health/Fitness - HealthKit integration
Installation
The iOS support is built into the main craft CLI:
Pressable, TouchableOpacity, and TouchableHighlight render as native
pressable flow containers. Modal renders a parent-scoped native layer in native mode, with visible,
transparent, nonModal, dismissOnOutsideTap, animationType, onShow,
onDismiss, and onRequestClose support. Non-modal popups remain pass-through
unless outside-tap dismissal is explicitly enabled. FlatList item roots receive the same onLayout callback as ordinary native
views when rows are materialized or recycled.
View.measure and non-modal left/top placement use the same screenViewport
coordinate space. Safe-area and navigation-bar offsets are not added implicitly;
anchored callers must clamp against the measured viewport when needed. Re-run
measurement after the anchor or screen root emits onLayout, and after every
onScroll from an ancestor; those are the host-neutral invalidation signals for
repositioning an anchored popup.
bun add craft-native
Native map input contract
Map coordinates are finite and range-checked at the native boundary; invalid
points and pole-crossing regions are ignored on iOS just as on Android.
Quick Start
1. Initialize Project
craft ios init MyApp --bundle-id com.example.myapp
cd ios
2. Add Your Web Content
Replace dist/index.html with your web app, or point to a dev server:
craft ios build --html-path ../dist/index.html
# or
craft ios build --dev-server http://localhost:3456
3. Open in Xcode
craft ios open
4. Run on Device
In Xcode:
- Select your Team in Signing & Capabilities
- Connect your iPhone
- Select your device
- Click Run
Configuration
Experimental WebView-free screen
Native screens also support ImageBackground, which loads an image behind
ordinary native children while preserving the shared flex layout contract.
Native image sources accept HTTPS everywhere and loopback HTTP for local
development (localhost, 127.0.0.1, ::1, and *.localhost); public HTTP
and unsupported schemes are rejected.
KeyboardAvoidingView also responds to the native keyboard with padding,
position, or height behavior.
Native screens also expose the iOS-only craft.badge capability. craft.badge.set(count)
and craft.badge.clear() update the app icon without requesting notification
authorization or requiring local notifications to be enabled.
Keyboard frame changes update the native controller's additional safe area, so
focused inputs and responsive onLayout measurements move with the keyboard.
Shared view transforms, z-order, view/text shadows, per-edge border styles,
and linear gradients are applied by UIKit with the same style keys as Android;
elevation remains Android-specific. Gradient layers follow the native view's
bounds and corners through layout changes.
The opt-in native renderer hosts compiled .stx screens in JavaScriptCore and renders their View, SafeAreaView, KeyboardAvoidingView, StatusBar, RefreshControl, Text, Button, Link, Checkbox, TextInput, Picker, SegmentedControl, DatePicker, Switch, Slider, ActivityIndicator, Icon, Image, ImageBackground, Video, Map, Svg, G, SvgText, ScrollView, SectionList, and recycling FlatList nodes as UIKit controls. StatusBar and RefreshControl are screen/scroll utility nodes rather than visible children. Map uses MapKit for trail polylines and marker taps; its overlays carry flat latitude/longitude geometry arrays, strokeWidth is expressed in logical points, and the camera supports controlled region, one-time initialRegion, and fitToBounds. Svg is a DOM-free drawing surface; grouped G and SvgText nodes are painted inside it. Icon uses SF Symbols with the shared symbol/name contract and accessibility metadata. SectionList uses the same native scroll host for ordinary .stx slot children; grouped section data should use FlatList until the section-data protocol is available. FlatList uses UICollectionView with stable keyed rows, incremental diffs, grids, horizontal and inverted layouts, list chrome, and end-reached pagination. Native views support onLayout callbacks with point-based frame measurements that refresh after safe-area or orientation changes. Flex items support flex, flexGrow, flexShrink, and numeric flexBasis for main-axis space distribution. Native screens also expose the versioned capability bridge: JSON storage and SQLite survive relaunch, lifecycle and deep-link events are scoped to the top route, and local notifications use UNUserNotificationCenter. Enable each capability in craft.config.json; disabled calls preserve Craft's CAPABILITY_DISABLED rejection code and every request has deterministic timeout/cancellation behavior. The default remains web; existing iOS apps are unchanged. Checkbox supports controlled checked/value, indeterminate state, and boolean onValueChange; Picker renders <select>/<option> values with onValueChange or onChange; DatePicker emits local date/time values plus ISO and millisecond timestamp fields; Switch supports state-aware trackColor, thumbColor, and iOS ios_backgroundColor; Slider supports track/thumb tint props and step snapping; Image reports load lifecycle events and structured failures; Video uses an AVPlayerViewController attached to the native screen for URI playback, native controls, and route-safe teardown. craft.navigation.setOptions also accepts a tabAccessory destination beside the tab pill; it uses an app-local path, title, symbol, optional badge, and accessibilityLabel, and null clears it. Dynamic craft.shortcuts.set/clear are not installed by the all-native host yet; configure static appShortcuts in craft.config.json to publish home-screen quick actions. Runtime shortcut registration remains tracked in #412. The portable component, capability, list, style, image-source, event, accessibility, and reconciliation behavior is specified in the Native STX guide.
FlatList rows are authored as keyed :for child rows in native STX; the
maintained protocol does not serialize data/renderItem callbacks.
JavaScriptCore has no DOM window; Craft aliases globalThis.window to
globalThis before installing the native bridge so browser-safe SDK calls such
as window.craft.dialog.actionSheet() reach the native capability host. This
does not add document or DOM rendering; routes that do not opt into native
continue using the WebView renderer.
craft ios init NativeDemo --renderer native --output ./ios-native
stx native compile Screen.stx --format bundle --output ./screen.js
craft ios build --output ./ios-native --native-bundle ./screen.js
craft ios run --output ./ios-native --simulator
stx native compile is part of the stx CLI (@stacksjs/stx); build tools can call compileNativeBundle from @stacksjs/stx/native instead. A runnable screen is in fixtures/native-screen/Screen.stx. In native mode, the app never instantiates WKWebView; a missing dist/native-screen.js fails the build rather than silently opening the web placeholder.
Keep application repositories free of handwritten Swift with the built-in audit:
craft-ios audit-sources --app-root .
The command ignores Craft's generated storage/framework/mobile tree, build
output, and dependencies. It exits non-zero and lists the relative paths when
an app owns a .swift file; use the exported assertNoApplicationSwiftSources
function when the check belongs inside an existing TypeScript test.
Native screen updates use the versioned mutation protocol when the bundle
supports it and fall back to whole-document rendering for older bundles.
Updates reconcile the UIKit tree by sibling-scoped key (or testID for
existing screens); unkeyed children reuse their position. TextInput objects
therefore keep focus and selection while unrelated labels and buttons change.
Native TextInput also applies placeholderTextColor, selectionColor,
positive maxLength, multiline, and numberOfLines values while preserving
the WebView fallback for routes that do not opt into the renderer.
The protocol wire format, atomic validation, revisions, and error codes are in
the Native STX guide. On macOS,
bun packages/ios/scripts/test-native-render.ts runs the renderer's unit and
simulator UI tests.
initSimulatorDriver can also drive an installed release on a paired iPhone.
Pass script: serializeSimulatorSteps(steps) to bundle a journey in the test
target. shot, tree and systemtree then save native XCTest attachments;
checks appear in the Xcode test log. Generate the project with XcodeGen, sign
the test runner for your team and run it against the device. The installed app
under test is activated by its bundle identifier and is not rebuilt by the
driver. Export evidence with xcrun xcresulttool export attachments --path <result.xcresult> --output-path <evidence>. Omitting script restores the
control-server protocol, required for the net, delay and exec hooks.
Journeys stop at the first failed check so later actions cannot operate on the
wrong screen. systemtap waits for an exact system button label or identifier.
For a Live Activity, its exact text identifies the enclosing system button rather
than tapping remotely hosted text. Partial labels never select a permission choice. The Live Activity layout fixture
exercises long names and timer alignment using the production widget.
Use universallink https://example.com/profile to test an associated HTTPS
link after a fresh install. The driver host uses Apple's public
universalLinksOnly option and waits up to 60 seconds for iOS to accept the
association downloaded from Apple's CDN. A rejected association fails the
journey; it cannot fall back to Safari. This operation does not launch the app
under test directly, so a preceding terminate still tests a cold handoff.
Use openurl for browser fallback checks and custom URL schemes.