Fundamental Concepts
Utils
Utils provides convenient utilities covering a broad range of common helpers used in projects from light JavaScript utilities to iOS and Android specific properties and methods.
Using Utils
Validating a path for a resource or a local file
To verify if a path is valid resource or local file path, use the isFileOrResourcePath() method:
const isPathValid: boolean = Utils.isFileOrResourcePath(
'https://nativescript.org/',
) // false
// or
const isPathValid: boolean = Utils.isFileOrResourcePath('res://icon') // trueCheck if a URI is a data URI
To check if a specific URI is a valid data URI, use the isDataURI() method.
const isDataURI: boolean = Utils.isDataURI(`data:image/png;base64,iVBORw0KGgoAAA
ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU
5ErkJggg==`) // true
// or
const isDataURI: boolean = Utils.isDataURI(`base64,iVBORw0KGgoAAA
ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU
5ErkJggg==`) // falseOpening a url
The openUrl() method allows you to open a url and returns true if a browser tab with the specified url opened successfully or false otherwise.
const didUrlOpen: boolean = Utils.openUrl('https://nativescript.org/')Escaping regex symbols
To escape regex metacharacters in string, use the escapeRegexSymbols() method.
const escapedString: string = Utils.escapeRegexSymbols('$hello') // \$helloCheck if the application is running on a physical device
const isOnPhysicalDevice: boolean = Utils.isRealDevice()Checking if a value is a number
To check if a value is a number, use the isNumber() method.
const isANumber: boolean = Utils.isNumber(2) // true
const isNumber: boolean = Utils.isNumber('test') // false
const isNumber: boolean = Utils.isNumber(true) // falseGet a class hierarchy of an object
To list all the classes an object is an instance of, use the getBaseClasses() method:
const labelHierarchy: Array<string> = Utils.getBaseClasses(new Label())
/* [
Label,
TextBase,
TextBaseCommon,
View,
ViewCommon,
ViewBase,
Observable,
Object,
] */To hide a soft keyboard on the screen, use the dismissKeyboard() method.
Utils.dismissKeyboard()Utils API
MajorVersion
const majorVersion: number = Utils.ios
(`iOS only`) Gets the iOS device major version. For example, for `16.0` ,it returns `16`.
---
### isFileOrResourcePath()
```ts
const isFileOrResourcePath: boolean = Utils.isFileOrResourcePath(path)Returns true if the specified path points to a resource or local file.
isDataURI()
const isDataURI: boolean = Utils.isDataURI(uri)openUrl()
const isUrlOpened: boolean = Utils.openUrl(url)Opens the passed url using the default application.
escapeRegexSymbols()
const escapedString: string = Utils.escapeRegexSymbols(string)Escapes special regex characters (., *, ^, $ and so on) in a string and returns a valid regex.
convertString()
const toStr: number | boolean = Utils.convertString(value)Converts a string value to a number or boolean. If it can not convert, it returns the passed string.
GC()
Utils.GC()A utility function that invokes garbage collection on the JavaScript side.
queueMacrotask()
Utils.queueMacrotask(task: () => void)queueGC()
- Optional:
delaytime, in milliseconds, to wait before garbage collection starts. - Optional:
useThrottleIf set totruethrottling is used instead of default debounce strategy.
A utility function that queues a garbage collection. Multiple calls in quick succession are debounced by default and only one gc will be executed after 900ms.
debounce()
const debouncedFn = Utils.debounce(fn, delay)
debouncedFn()
A simple debounce utility.
- `fn` The function to debounce.
- _Optional_:`delay` delays the bouncing, in milliseconds. Defaults to 300ms.
---
### throttle()
```ts
const throttledFn = Utils.throttle(fn, delay)
throttledFn()A simple throttle utility.
fnThe function to throttle.- Optional:
delaydelays the throttling, in milliseconds. Defaults to 300ms.
isFontIconURI()
const isFontIconURI: boolean = Utils.isFontIconURI('font://')Returns true if the specified URI is a font icon URI.
executeOnMainThread()
Utils.executeOnMainThread(fn: Function)Important!
This will be made synchronously when invoked from the main thread, or asynchronously if it's not.
executeOnUIThread()
Utils.executeOnUIThread(fn: Function)Runs the passed function on the UI Thread.
Important!
Always dispatches asynchronously to the UI thread.
mainThreadify()
Utils.mainThreadify(fn: Function): (...args: any[])Returns a function wrapper which executes the supplied function on the main thread. The wrapper behaves like the original function and passes all of its arguments BUT discards its return value.
isMainThread()
const isMainThread: boolean = Utils.isMainThread()Boolean value indicating whether the current thread is the main thread.
dispatchToMainThread()
Utils.dispatchToMainThread(fn: Function)Dispatches the passed function for execution on the main thread.
releaseNativeObject()
Utils.releaseNativeObject(object: java.lang.Object | NSObject)Releases the reference to the wrapped native object.
getModuleName()
const moduleName: string = Utils.getModuleName(path: string)Gets module name from the specified path.
openFile()
const didFileOpen: boolean = Utils.openFile(filePath, title)Opens the file at the specified filePath. Optional: (Android-only) title is the title of the file viewer.
isRealDevice()
const isOnPhysicalDevice: boolean = Utils.isRealDevice()Checks whether the application is running on a physical device and not on a simulator/emulator.
getClass()
const objectClass: string = Utils.getClass(object)Gets the class name of an object.
getBaseClasses()
const objectParentClasses: Array<string> = Utils.getBaseClasses(object)Returns an entire class inheritance hierarchy for the specified object.
getClassInfo()
const objectClassInfo: ClassInfo = Utils.getClassInfo(object)Gets the ClassInfo for an object. ClassInfo object has the following properties:
_name: The name of the class of the object.
isBoolean()
const isValueBoolean: boolean = Utils.isBoolean(someValue)Checks if the specified value is a valid boolean.
isDefined()
const isValueDefined: boolean = Utils.isDefined(someValue)Checks if the specified value is not undefined.
isUndefined()
const isUndefined: boolean = Utils.isUndefined(someValue)Checks if a value is undefined.
isNullOrUndefined()
const isNullOrUndefined: boolean = Utils.isNullOrUndefined(someValue)Checks if a value is null or undefined.
isFunction()
const isValueAFunction: boolean = Utils.isFunction(someValue)Checks if a value is a function.
isNumber()
const isNumber: boolean = Utils.isNumber(someValue)Checks if a value is a valid number.
isObject()
const isObject: boolean = Utils.isObject(someValue)Returns true if a value is an object or array.
isString()
const isString = (boolean = Utils.isString(someValue))Checks if a value is a string.
toUIString()
const stringified: string = Utils.toUIString(object)Returns a string representation of an object to be shown in UI.
dataSerialize()
const serializedData = Utils.dataSerialize(data, wrapPrimitives)Data serialization from JS > Native.
- Optional:
datais the JavaScript data to serialize. - Optional:
wrapPrimitivesis abooleanparameter indicating whether to wrap primitive data types.
dataDeserialize()
const dataDeserialized = Utils.dataDeserialize(nativeData)Data deserialization from Native to JS.
- Optional
nativeDatadata to be deserialized.
setInterval()
const timerID: number = Utils.setInterval((args) => {}, milliseconds, [
arg1,
arg2,
])A timer method that allows you to run callback every milliseconds(milliseconds). It returns an id that is used to stop the timer.
clearInterval()
Utils.clearInterval(timerID)Stops the interval timer of the provided id.
setTimeout()
const timerId: number = Utils.setTimeout((args) => {}, milliseconds, [
arg1,
arg2,
])A timer method that allows you to wait milliseconds(milliseconds) before running the callback. It returns an id to be used to stop the timer.
dismissKeyboard()
Utils.dismissKeyboard()Hides any keyboard on the screen.
Utils.android
getApplication()
const app: android.app.Application = Utils.android.getApplication()(Android-only)Gets the native Android application instance. Also see native app.
getCurrentActivity()
const activity:
| androidx.appcompat.app.AppCompatActivity
| android.app.Activity
| null = Utils.android.getCurrentActivity()(Android-only) Gets the current foreground Android Activity if available, otherwise null.
getApplicationContext()
Utils.android.getApplicationContext()(Android-only) Gets the Android application context.
getResources()
const resources: android.content.res.Resources = Utils.android.getResources()(Android-only) Gets the native Android Resources for the application.
getPackageName()
const pkg: string = Utils.android.getPackageName()(Android-only) Gets the application package name.
enableEdgeToEdge()
function enableEdgeToEdge(
activity: androidx.appcompat.app.AppCompatActivity,
options?: {
statusBarLightColor?: Color
statusBarDarkColor?: Color
navigationBarLightColor?: Color
navigationBarDarkColor?: Color
handleDarkMode?: (
bar: 'status' | 'navigation',
resources: android.content.res.Resources,
) => boolean
},
): voidEnables full edge-to-edge rendering on Android and lets you customize system UI overlay colors and behavior.
activityThe currentAppCompatActivityinstance.- Optional
optionsmay include:statusBarLightColorColor to use for light appearance of the status bar (icons dark on light background).statusBarDarkColorColor to use for dark appearance of the status bar (icons light on dark background).navigationBarLightColorColor to use for light appearance of the navigation bar.navigationBarDarkColorColor to use for dark appearance of the navigation bar.handleDarkModeDecide whether light or dark system UI should be used for the given bar based on your own logic. Returntrueto use light appearance,falsefor dark.
Notes:
- Works together with Page
androidOverflowEdgeandandroidOverflowInsetto control inset application/consumption. - When insets are applied, they are added to the view's padding.
Example:
import { Application, Utils, Color } from '@nativescript/core'
const activity = Utils.android.getCurrentActivity()
Utils.android.enableEdgeToEdge(activity, {
statusBarLightColor: new Color('#FFFFFF'),
statusBarDarkColor: new Color('#000000'),
navigationBarLightColor: new Color('#FFFFFF'),
navigationBarDarkColor: new Color('#000000'),
handleDarkMode: (bar, resources) => {
// Decide per your theme; return true for light appearance
return true
},
})setDarkModeHandler()
Utils.android.setDarkModeHandler(options?: {
activity?: androidx.appcompat.app.AppCompatActivity
handler: (
bar: 'status' | 'navigation',
resources: android.content.res.Resources,
) => boolean
})(Android-only) Sets a handler to decide whether the specified system bar should use light or dark appearance based on your logic.
setNavigationBarColor()
Utils.android.setNavigationBarColor(options?: {
activity?: androidx.appcompat.app.AppCompatActivity
lightColor?: Color
darkColor?: Color
})(Android-only) Sets the navigation bar color for the application for light/dark appearances.
setStatusBarColor()
Utils.android.setStatusBarColor(options?: {
activity?: androidx.appcompat.app.AppCompatActivity
lightColor?: Color
darkColor?: Color
})(Android-only) Sets the status bar color for the application for light/dark appearances.
getInputMethodManager()
const inputMethodManager: android.view.inputmethod.InputMethodManager =
Utils.android.getInputMethodManager()(Android-only)Gets the native Android InputMethodManager instance.
showSoftInput()
Utils.android.showSoftInput(nativeView)(Android-only)Shows a soft keyboard. nativeView is an android.view.View instance to disable the soft input for.
dismissSoftInput()
Utils.android.dismissSoftInput(nativeView?)(Android-only) Hides the soft input method (soft keyboard). Optionally provide a specific android.view.View.
stringArrayToStringSet()
const stringSet: java.util.HashSet = Utils.android.collections.stringArrayToStringSet(str: string[])Converts string array into a String hash set.
stringSetToStringArray()
const stringArray: string[] =
Utils.android.collections.stringSetToStringArray(stringSet)Converts string hash set into array of strings.
getDrawableId()
const drawableId: number = Utils.android.resources.getDrawableId(resourceName)Gets the drawable id from a given resource name.
getStringId()
const stringId: number = Utils.android.resources.getStringId(resourceName)Gets the string id from a given resource name.
getId()
const viewId: number = Utils.android.resources.getId(resourceName)Gets an id resource by name.
getResource()
const resId: number = Utils.android.resources.getResource(name, type?)Gets a resource identifier by name with an optional type. This sets an explicit package name under the hood. See Android's Resources.getIdentifier.
getPaletteColor()
const paletteColor: number = Utils.android.resources.getPaletteColor(
resourceName,
Utils.android.getApplicationContext(),
)Gets a color from the current theme.
getWindow()
const window: android.view.Window = Utils.android.getWindow()Deprecated. Use the generic Utils.getWindow<android.view.Window>() instead.
Utils.ios
copyToClipboard()
Utils.copyToClipboard(value):Copies the specified value to device clipboard.
setWindowBackgroundColor()
Utils.ios.setWindowBackgroundColor(someColorString)Sets the window background color of base view of the app. Often this is shown when opening a modal as the view underneath scales down revealing the window color.
getCurrentAppPath()
const appPath: string = Utils.ios.getCurrentAppPath()Gets the root folder for the current application. Also see currentApp()
getVisibleViewController()
const visibleView: UIViewController = Utils.ios.getVisibleViewController(rootViewController: UIViewController)Gets the currently visible(topmost) UIViewController.rootViewController is the root UIViewController instance to start searching from (normally window.rootViewController).
getRootViewController()
const rootView: UIViewController = Utils.ios.getRootViewController()Gets the root UIViewController of the app.
getShadowLayer()
const shadowLayer: CALayer = Utils.ios.getShadowLayer(nativeView, name, create)nativeViewis a UIView instance to find shadow layer with- Optional:
name(string) is the name of the shadow layer if looking for a specific layer. - Optional:
create(boolean) if set totrue, it indicates that a new layer should be created if no layer is found.
createUIDocumentInteractionControllerDelegate()
Create a UIDocumentInteractionControllerDelegate implementation for use with UIDocumentInteractionController
getMainScreen()
const screen: UIScreen = Utils.ios.getMainScreen()(iOS only) Returns the main UIScreen.
isLandscape() (deprecated)
const landscape: boolean = Utils.ios.isLandscape()(iOS only) Deprecated. Use Application.orientation instead.
snapshotView()
const image: UIImage = Utils.ios.snapshotView(view: UIView, scale: number)(iOS only) Takes a snapshot image of the provided UIView at the desired screen scale.
applyRotateTransform()
const result: CATransform3D = Utils.ios.applyRotateTransform(
transform: CATransform3D,
x: number,
y: number,
z: number,
)(iOS only) Returns a transform rotated by the specified degrees around the X, Y and Z axes.
printCGRect()
Utils.ios.printCGRect(rect: CGRect)(iOS only) Debug utility to print CGRect values in logs (printing CGRect directly may appear blank otherwise).
copyLayerProperties()
Utils.ios.copyLayerProperties(
view: UIView,
toView: UIView,
customProperties?: { view?: Array<keyof UIView>; layer?: Array<keyof CALayer> },
)(iOS only) Copies layer-related properties from one view to another. You can provide custom property lists for view and layer.
animateWithSpring()
Utils.ios.animateWithSpring(options?: {
tension?: number
friction?: number
mass?: number
delay?: number
velocity?: number
animateOptions?: UIViewAnimationOptions
animations?: () => void
completion?: (finished?: boolean) => void
})(iOS only) Animates property changes with a configurable spring effect.
jsArrayToNSArray()
const jsArrayToNSArray : NSArray<T> =Utils.ios.collections.jsArrayToNSArray<T>(str: T[])(iOS only)Converts JavaScript array with elements of type T to NSArray of type T.
nsArrayToJSArray()
const nsArrayToJSArray: Array<T> = nsArrayToJSArray<T>(a: NSArray<T>)(iOS only)Converts NSArray of elements of a type T to an equivalent JavaScript array.
getWindow()
const window: UIWindow = Utils.ios.getWindow()Gets the UIWindow of the app.
Deprecated. Use the generic Utils.getWindow<UIWindow>() instead.
API Reference(s)
- @nativescript/core/utils module
