Files and storage
Pick and save photos and files, read bundled assets, store settings and data, sync through the cloud and keep secrets.
Photos and files
Section titled “Photos and files”cx.PickImages shows the system’s photo picker and answers with core.PickedFiles, whose bytes, name, type and pixel size the app reads. cx.TakePhoto shows the camera where the platform has one; cx.Env().CanTakePhoto says whether it does. On macOS, Windows and Linux it shows the scanner’s camera preview with a Take Photo button. cx.ScanCode opens a camera preview and answers with the first code it reads, a QR code unless ScanOptions.Kinds asks for others, or nil when the user closes it; cx.Env().CanScanCode says whether the platform has a scanner, on macOS, iOS and Android devices with a camera, Windows machines with one, Linux desktops with the Camera portal and GStreamer pipewiresrc, and browsers with getUserMedia and BarcodeDetector. macOS presents a sheet when the requesting window is visible, Windows and Linux a modal over the window, and the web an overlay over the page. Put NSCameraUsageDescription in apple.info for macOS and iOS, and CAMERA in android.permissions for Android. Android, Windows and Linux read every kind but PDF417. Treat the code’s text as untrusted input.
On tvOS, PickImages answers with no images and TakePhoto returns core.ErrNoCamera; NSGo does not provide the Continuity Camera picker.
In tests, nsgotest.App.PickImages, nsgotest.App.TakePhoto and nsgotest.App.ScanCode receive nsgotest.ImagePick records for picks and captures and nsgotest.CodeScan records for scans, and answer in place of system UI. The hooks work headless and under supported nsgo test -target hosts. nsgotest.Environment(core.Environment{Camera: true, ScanCode: true}) gives a target without a camera one.
cx.PickImages(core.PickOptions{Limit: 1, MaxDimension: 2048}, func(files []core.PickedFile) { if len(files) == 1 { avatar.Set(files[0].Data) }})cx.PickFiles picks files of any type, cx.PickDirectories picks folders as an fs.FS, and cx.SaveFile saves a file or bytes through the system’s save dialog. Both pickers take a Title, a Button label and a Start folder, and PickFilesOptions.TypesName names the type menu, so an app can show them in its own language; these are hints, which macOS, Windows and Linux follow, iOS only for Start, and Android and the web not at all. cx.PickScreenColor picks a color anywhere on the screen where cx.Env().CanPickScreenColor() is true: macOS, Windows, Linux with the desktop Screenshot portal, and browsers with EyeDropper.
Set core.PickDirectoriesOptions.Persist to keep read access to a picked folder across app restarts: each returned core.Directory carries an opaque serializable Token on Android (a persisted SAF tree permission), iOS and macOS (a security-scoped bookmark), and Windows and Linux (the folder’s path). Save that token (for example in cx.Storage()) and call cx.OpenDirectory(token, done) on a later launch to reopen the folder — persisting dir.Token again if the platform refreshed a stale bookmark — and cx.ReleaseDirectory(token, done) when the user removes the folder so persisted grants and security scopes are freed. Platforms without persistent folder grants (such as the web) leave Token empty and answer OpenDirectory and ReleaseDirectory with core.CodeUnavailable.
Call dir.MediaURI(name) to get a read-only URI for a file inside a core.Directory that core.Video can stream directly without copying it into app storage: a content:// document URI on Android, or a file:// URL on macOS, iOS, Windows and Linux. Directories without a direct playback URI (such as on the web) return core.ErrNoMediaURI. For pathless directories (Android), call MediaURI off the engine’s goroutine as you do Open and ReadDir.
Set core.SaveOptions.Start to an existing absolute folder to open the save dialog there on macOS, Windows, Linux and iOS. With an empty or unusable hint, or on other targets, the system chooses the folder.
Set core.SaveOptions.Accept to validate the chosen destination before writing. It runs on the engine’s goroutine. Returning an error leaves the destination untouched. On macOS, Windows and in the in-process GTK chooser on Linux, the dialog shows the reason and lets the user choose another path. Cancelling after a refusal reports saved == false, the refused path and the error. On Android and in the Linux desktop portal, a refusal completes the save with that result. Android lets the user choose a folder and supplies a tree URI with the requested file name as its name query parameter. It creates the document after approval and reports the new document’s URI on success. The platform abandons the write if the check does not answer within five seconds. iOS and HarmonyOS report an error for saves requiring a check. The web has no destination path and uses its ordinary save flow.
In headless tests, App.PickFiles, App.PickDirectories and App.SaveFile receive nsgotest.FilePick, nsgotest.DirectoryPick and nsgotest.FileSave records. The same records are in app.FilePicks, app.DirectoryPicks and app.Saves. Persisted picks are stored in app.PersistedDirectories, answered by app.OpenDirectory and cleared by app.ReleaseDirectory (recording tokens in app.ReleasedDirectories).
Saving photos
Section titled “Saving photos”Use mobile.SavePhoto(cx, mobile.PhotoSaveOptions{Name: "photo.jpg", Path: path}, done) to add an encoded image to the device’s photo library on iOS and Android. Supply Data instead of Path for bytes; MIME defaults to the name’s extension. The callback func(saved bool, path string, err error) runs on the engine goroutine after the library finishes, with a PHAsset local identifier on iOS or a MediaStore URI on Android when available. iOS preserves the image’s original format, including GIF animation.
On iOS, put NSPhotoLibraryAddUsageDescription in apple.info; the service asks only for permission to add photos. Android 28 requires android.permission.WRITE_EXTERNAL_STORAGE in android.permissions and asks for it when saving. Android 29 and later need no storage permission. Access denial and write failures report an error. Other platforms report that photo library saving is unavailable; use cx.SaveFile for a desktop save dialog. In headless tests, App.SaveFile receives FileSave{Photo: true} and returning a non-absolute identifier or URI answers as a saved photo.
Bundled assets
Section titled “Bundled assets”Put files under the app’s resources/ directory and use cx.ReadAsset("asset:maps/level.bin", done) to read them from Go. The callback receives ([]byte, error) on the engine’s goroutine after the read and is dropped if its owner goes away or runs again. Use errors.Is(err, core.ErrAssetNotFound) to identify missing files. The read loads the entire file into memory.
Packages skip dotfiles and dot-directories under resources/. A symbolic link encountered while packaging, including a linked resources/ directory, is an error and cannot be allowed. Files with credential-like names (*.pem, *.key, *.p8, *.p12, *.pfx, *.jks, *.keystore, id_rsa*, id_ed25519*, service-account*.json, credentials.json) or a PEM private-key header fail packaging. Keep secrets outside packaged directories; files that ship on the web can be downloaded by anyone.
For safe files you intend to ship, list exact paths relative to nsgo.yaml, with forward slashes and no globs:
build: allow_resources: - resources/.well-known/ - resources/certs/public-ca.pemListing a dot-directory, with or without a trailing slash, lets ordinary files inside it ship; each nested dotfile, dot-directory, or credential-like file still needs its own entry. Use mobile.exclude_resources with paths relative to resources/ to leave files out of the base mobile package; build.allow_resources does not override those exclusions.
Storage
Section titled “Storage”cx.Storage() is the app’s string key-value store. The first use loads the entries; subsequent reads are served from memory, and reads in a computation subscribe it to changes. Storage.Err() reports a failed load (for example, in a sandboxed iframe); that store will refuse all mutations. SetItem returns *core.StorageFullError above the app’s quota (core.StorageQuota, 5 MiB by default), or an error if the browser refuses the write. A failed set keeps the previous value.
cx.Store() returns the underlying store, for a host that creates another root with core.RootOptions.Storage, such as one running a plugin on a goroutine of its own: both roots then share the app’s entries and what is kept on the device. It is the whole store, not the partition cx.ProvideStorage gives code the app did not write.
A host supplying its own persistence calls core.NewStore(backend) with a core.StorageBackend: Load() (map[string]string, error) loads once, and Write(core.StorageChange) receives changes in order. Optionally implement core.StorageBackendWithErrors to run WriteErr(core.StorageChange) error instead of Write, returning success only once the change is kept. Switch on change.Op (core.StorageSet, core.StorageRemove, core.StorageClear) and use change.Key and change.Value. Pass nil for storage held only in memory.
store := cx.Storage()if tab, ok := store.GetItem("tab"); ok { selected.Set(tab)}if err := store.SetItem("tab", "library"); err != nil { log.Printf("settings could not be saved: %v", err)}store.Keys() lists the keys, RemoveItem deletes one and Clear empties the storage. Call store.Err() immediately after either of those two mutators to check for a persistence failure. A clear that removes keys individually stops if a removal fails. cx.DataDir() and cx.CacheDir() give the app’s folders for files the key-value storage is too small for; cx.LogsDir() gives the platform’s directory for log files, and Scope.ProvideStorage gives a subtree a partition of its own.
On the web, the default backend is localStorage. For larger saves, set web.storage: indexeddb. IndexedDB writes return only after the transaction commits; save before navigation rather than relying on a page-close handler. Neither backend encrypts its data: keep tokens and passwords in secrets on targets that support them.
An iOS App Clip and its full app share these data and storage locations when app_clip and explicit apple.app_group are configured; their caches stay separate. Enabling the group does not migrate existing sandbox data. App Clip storage covers configuration and signing.
On HarmonyOS, Go file operations such as os.ReadFile, os.WriteFile and os.Rename work under these directories and os.TempDir(). Relative paths start in the files directory. Advisory file locks and symbolic links are unavailable.
The user’s folders
Section titled “The user’s folders”desktop.UserDir(cx, desktop.DownloadsDir) returns the path of one of the user’s folders: DocumentsDir, DownloadsDir, DesktopDir, PicturesDir, MusicDir or VideosDir. It asks the system each time, so a folder the user moved is followed: the folders in the home directory on macOS (Movies for videos), the known folders on Windows, OneDrive’s included, and the XDG user directories on Linux. The folder may not exist yet. Phones, the web and HarmonyOS have no such folders an app reaches by path, nor does Linux for a folder user-dirs.dirs leaves out: UserDir returns core.ErrUserDirUnavailable, and the app asks the user with cx.PickDirectories or cx.SaveFile instead.
dir, err := desktop.UserDir(cx, desktop.DownloadsDir)if err != nil { dir = cx.DataDir()}Tests never get the user’s folders: each is an empty directory of the test’s temporary one, and nsgotest.UserDirs(map[core.StandardDir]string{…}) pins them, a folder left out unavailable.
Crash reports
Section titled “Crash reports”Native release builds keep Go crash traces under cx.LogsDir()/crashes. Apple records uncaught Objective-C exceptions, Android records uncaught Java exceptions, and Windows records SEH exceptions that reach its top-level filter. List pending reports on the next launch with cx.CrashReports(). Each report identifies the version, build and platform that produced it. Call Open() to read the diagnostic text, close the reader, then call Acknowledge() to delete the report when the app has processed it. Run these file operations on a goroutine.
Disk space
Section titled “Disk space”cx.DiskSpace(func(space core.DiskSpace, err error) { … }) queries the volume containing cx.DataDir() asynchronously and calls back on the engine goroutine. Total is the system-reported capacity, Available is what the app can use for a user-requested operation, and Opportunistic is what it can use for caches and prefetching. All three are in bytes. Available includes space the system reclaims on demand where it reports that figure. Platforms with a single free-space figure return it in both fields. On the web, Total is the browser’s estimated storage quota for the origin and Available is the unused portion. When the service is unavailable it returns core.ErrDiskSpaceUnavailable.
Apple builds require apple.privacy.accessed_apis in nsgo.yaml to declare NSPrivacyAccessedAPICategoryDiskSpace. Declare E174.1 to check space before writing or to free files when space is low, with a change the user can observe. Declare 85F4.1 to show the user the available space. The app must follow Apple’s restrictions on using and sharing the readings. A build without the category returns core.ErrNotDeclared. Apple’s approved reasons
Set a test’s answer with nsgotest.DiskSpace(space, err).
Cloud storage
Section titled “Cloud storage”Package cloud syncs small key-value entries (cloud.Get, cloud.Set, cloud.Delete, cloud.Keys) and larger files or save snapshots (cloud.ReadFile, cloud.WriteFile, cloud.DeleteFile, cloud.ListFiles) across devices: iCloud Key-Value Store and ubiquity document containers on macOS and iOS, and Google Play Games Saved Games on Android.
Every operation delivers its callback on the engine goroutine and skips it if cx has been disposed. cx.Env().CanUseCloudStorage() reports whether cloud storage is available; when the user is signed out, entitlements are absent, or the platform has no native cloud backend (Windows, Linux and the web), every call returns cloud.ErrUnavailable and never silently drops writes.
if cx.Env().CanUseCloudStorage() { cloud.WriteFile(cx, "saves/slot1.sav", saveBytes, func(err error) { if err != nil { status.Set(err.Error()) } })}
cloud.WatchChanges(cx, func(ev cloud.ChangeEvent) { reload(ev.Keys, ev.Files)})
cloud.OnConflict(cx, func(c cloud.Conflict) { _ = c.Resolve(mergeSaves(c.Local, c.Remote))})cloud.WatchChanges and cloud.OnConflict deliver external multi-device changes and version conflicts on the engine goroutine and clean themselves up automatically when cx is disposed. Reading a conflicted file returns a *cloud.ConflictError (matching errors.Is(err, cloud.ErrConflict)).
To enable Apple iCloud entitlements in nsgo build, add a cloud: (or icloud:) section to nsgo.yaml:
cloud: kv_store: true containers: - iCloud.com.example.myappThe signing profile must grant the iCloud capabilities you ask for. On macOS only Mac App Store builds (sign.macos_profile) carry iCloud, since macOS grants it only with a provisioning profile; a Developer ID build leaves it out with a warning. On Android, cloud storage needs the Play Games Services v2 SDK in the app and a signed-in player.
On desktop stores such as Steam, Steam Auto-Cloud syncs cx.DataDir() directly with zero extra code — keep writing local save files there and let Steam synchronize the directory.
In tests, nsgotest gives each app an isolated in-memory cloud store: toggle availability with nsgotest.CloudAvailable or app.SetCloudAvailable, simulate external multi-device updates with app.SimulateCloudChange, and test conflict resolution with app.SimulateCloudConflict.
Secrets
Section titled “Secrets”cx.Secrets() is the app’s secure store, for refresh tokens, API keys and passwords: Get, Set and Delete a string by account, which the platform protects. A missing account reads as ("", false, nil), and where the platform has no secure store, as on the web, every call returns core.ErrSecretsUnavailable; NSGo never falls back to plain storage. The system may make a call wait, as a keychain asking the user does, so call them off the engine’s goroutine and hand the result back with cx.Post.
secrets := cx.Secrets()go func() { token, ok, err := secrets.Get("refresh-token") cx.Post(func() { if err == nil && ok { login(token) } })}()| Platform | Where a secret is kept |
|---|---|
| macOS | A generic password of the login keychain: kSecAttrService is the service, kSecAttrAccount the account |
| iOS, tvOS, watchOS | A generic password of the keychain, the same way |
| Windows | A generic credential of the Credential Manager whose target is service/account, at most 2560 bytes |
| Linux | An item of the Secret Service (GNOME Keyring, KWallet) with service and account attributes; unavailable where the session runs none |
| Android | Encrypted with an AES key of the Android Keystore, in the app’s private files, outside backups; reads also fall back to values expo-secure-store encrypted into its SecureStore SharedPreferences |
| WeChat mini programs | Platform-encrypted storage (wx.setStorage / wx.getStorage with encrypt: true, base library 2.21.3+); unavailable on older base libraries |
| Web, other mini programs | Unavailable (core.ErrSecretsUnavailable): browsers have no OS-protected client secret store (keep web sessions in server-set HttpOnly cookies), and QQ, Alipay and Douyin mini programs lack encrypted storage |
The service is the app’s ID (core.App().ID) by default. An app that moves from another framework keeps its users signed in by naming the items that framework wrote: Service, and on Apple platforms AccessGroup and Accessible. On Android, set Service to expo-secure-store’s keychainService ("key_v1" by default) to read values it encrypted into SharedPreferences; writing or deleting clears the migrated entry. On iOS, core.SecretAfterFirstUnlock lets background work read an item while the phone is locked, and a ThisDeviceOnly accessibility keeps it out of backups. On macOS an AccessGroup moves the items to the data protection keychain, which needs a build signed by a team whose keychain-access-groups entitlement lists the group, configured under macos.entitlements in nsgo.yaml for both Mac App Store and Developer ID builds.
s := cx.Secrets()s.Service = "app:no-auth" // the service an earlier build useds.Accessible = core.SecretAfterFirstUnlockThisDeviceOnlyerr := s.Set("refresh-token", token)nsgotest keeps an app’s secrets in memory, in App.Secrets, and nsgotest.Secrets starts a test with some, so a test never touches the machine’s keychain.