πŸš€ 8.9 Released! β†’ ⚑️ New Node-API Engine Preview, πŸ“² ns widget ios, πŸ’… Tailwind v4 and more...
Read Announcement

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:

ts
constisPathValid:boolean= Utils.isFileOrResourcePath(
'https://nativescript.org/',
) // false

// or

constisPathValid:boolean= Utils.isFileOrResourcePath('res://icon') // true

Check if a URI is a data URI ​

To check if a specific URI is a valid data URI, use the isDataURI() method.

ts
constisDataURI:boolean= Utils.isDataURI(`data:image/png;base64,iVBORw0KGgoAAA
 ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
 //8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU
 5ErkJggg==`) // true

// or
constisDataURI:boolean= Utils.isDataURI(`base64,iVBORw0KGgoAAA
 ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
 //8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU
 5ErkJggg==`) // false

Opening 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.

ts
constdidUrlOpen:boolean= Utils.openUrl('https://nativescript.org/')

Escaping regex symbols ​

To escape regex metacharacters in string, use the escapeRegexSymbols() method.

ts
constescapedString:string= Utils.escapeRegexSymbols('$hello') // \$hello

Check if the application is running on a physical device ​

ts
constisOnPhysicalDevice:boolean= Utils.isRealDevice()

Checking if a value is a number ​

To check if a value is a number, use the isNumber() method.

ts
constisANumber:boolean= Utils.isNumber(2) // true
constisNumber:boolean= Utils.isNumber('test') // false
constisNumber:boolean= Utils.isNumber(true) // false

Get a class hierarchy of an object ​

To list all the classes an object is an instance of, use the getBaseClasses() method:

ts
constlabelHierarchy:Array<string> = Utils.getBaseClasses(newLabel())
/* [
 Label,
 TextBase,
 TextBaseCommon,
 View,
 ViewCommon,
 ViewBase,
 Observable,
 Object,
] */

Hiding a keyboard ​

To hide a soft keyboard on the screen, use the dismissKeyboard() method.

ts
Utils.dismissKeyboard()

Utils API ​

MajorVersion ​

ts
constmajorVersion:number= Utils.ios

(iOS only) Gets the iOS device major version. For example, for 16.0 ,it returns 16.


isFileOrResourcePath() ​

ts
constisFileOrResourcePath:boolean= Utils.isFileOrResourcePath(path)

Returns true if the specified path points to a resource or local file.


isDataURI() ​

ts
constisDataURI:boolean= Utils.isDataURI(uri)

openUrl() ​

ts
constisUrlOpened:boolean= Utils.openUrl(url)

Opens the passed url using the default application.


escapeRegexSymbols() ​

ts
constescapedString:string= Utils.escapeRegexSymbols(string)

Escapes special regex characters (., *, ^, $ and so on) in a string and returns a valid regex.


convertString() ​

ts
consttoStr: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() ​

ts
Utils.GC()

A utility function that invokes garbage collection on the JavaScript side.


queueMacrotask() ​

ts
Utils.queueMacrotask(task: () =>void)

Queues the passed function to be ran as a macroTask.


queueGC() ​

ts
Utils.queueGC(delay, useThrottle)
  • Optional: delay time, in milliseconds, to wait before garbage collection starts.
  • Optional: useThrottle If set to true throttling 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() ​

ts
constdebouncedFn= 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
constthrottledFn= Utils.throttle(fn, delay)

throttledFn()

A simple throttle utility.

  • fn The function to throttle.
  • Optional:delay delays the throttling, in milliseconds. Defaults to 300ms.

isFontIconURI() ​

ts
constisFontIconURI:boolean= Utils.isFontIconURI('font://&#xf51e;')

Returns true if the specified URI is a font icon URI.


executeOnMainThread() ​

ts
Utils.executeOnMainThread(fn: Function)

Checks if the current thread is the main thread. If it is, calls the passed function. Otherwise, it dispatches it to the main thread.

Important!

This will be made synchronously when invoked from the main thread, or asynchronously if it's not.


executeOnUIThread() ​

ts
Utils.executeOnUIThread(fn: Function)

Runs the passed function on the UI Thread.

Important!

Always dispatches asynchronously to the UI thread.


mainThreadify() ​

ts
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() ​

ts
constisMainThread:boolean= Utils.isMainThread()

Boolean value indicating whether the current thread is the main thread.


dispatchToMainThread() ​

ts
Utils.dispatchToMainThread(fn: Function)

Dispatches the passed function for execution on the main thread.


releaseNativeObject() ​

ts
Utils.releaseNativeObject(object: java.lang.Object | NSObject)

Releases the reference to the wrapped native object.


getModuleName() ​

ts
constmoduleName:string= Utils.getModuleName(path: string)

Gets module name from the specified path.


openFile() ​

ts
constdidFileOpen:boolean= Utils.openFile(filePath, title)

Opens the file at the specified filePath. Optional: (Android-only) title is the title of the file viewer.


isRealDevice() ​

ts
constisOnPhysicalDevice:boolean= Utils.isRealDevice()

Checks whether the application is running on a physical device and not on a simulator/emulator.


getClass() ​

ts
constobjectClass:string= Utils.getClass(object)

Gets the class name of an object.


getBaseClasses() ​

ts
constobjectParentClasses:Array<string> = Utils.getBaseClasses(object)

Returns an entire class inheritance hierarchy for the specified object.


getClassInfo() ​

ts
constobjectClassInfo: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() ​

ts
constisValueBoolean:boolean= Utils.isBoolean(someValue)

Checks if the specified value is a valid boolean.


isDefined() ​

ts
constisValueDefined:boolean= Utils.isDefined(someValue)

Checks if the specified value is not undefined.


isUndefined() ​

ts
constisUndefined:boolean= Utils.isUndefined(someValue)

Checks if a value is undefined.


isNullOrUndefined() ​

ts
constisNullOrUndefined:boolean= Utils.isNullOrUndefined(someValue)

Checks if a value is null or undefined.


isFunction() ​

ts
constisValueAFunction:boolean= Utils.isFunction(someValue)

Checks if a value is a function.


isNumber() ​

ts
constisNumber:boolean= Utils.isNumber(someValue)

Checks if a value is a valid number.


isObject() ​

ts
constisObject:boolean= Utils.isObject(someValue)

Returns true if a value is an object or array.


isString() ​

ts
constisString= (boolean = Utils.isString(someValue))

Checks if a value is a string.


toUIString() ​

ts
conststringified:string= Utils.toUIString(object)

Returns a string representation of an object to be shown in UI.


dataSerialize() ​

ts
constserializedData= Utils.dataSerialize(data, wrapPrimitives)

Data serialization from JS > Native.

  • Optional: data is the JavaScript data to serialize.
  • Optional: wrapPrimitives is a boolean parameter indicating whether to wrap primitive data types.

dataDeserialize() ​

ts
constdataDeserialized= Utils.dataDeserialize(nativeData)

Data deserialization from Native to JS.

  • Optional nativeData data to be deserialized.

setInterval() ​

ts
consttimerID: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() ​

ts
Utils.clearInterval(timerID)

Stops the interval timer of the provided id.


setTimeout() ​

ts
consttimerId: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() ​

ts
Utils.dismissKeyboard()

Hides any keyboard on the screen.


getApplication() ​

ts
constapp:android.app.Application= Utils.android.getApplication()

(Android-only)Gets the native Android application instance. Also see native app.


getApplicationContext() ​

ts
Utils.android.getApplicationContext()

(Android-only) Gets the Android application context.


getInputMethodManager() ​

ts
constinputMethodManager:android.view.inputmethod.InputMethodManager=
 Utils.android.getInputMethodManager()

(Android-only)Gets the native Android InputMethodManager instance.


showSoftInput() ​

ts
Utils.android.showSoftInput(nativeView)

(Android-only)Shows a soft keyboard. nativeView is an android.view.View instance to disable the soft input for.


stringArrayToStringSet() ​

ts
conststringSet:java.util.HashSet= Utils.android.collections.stringArrayToStringSet(str: string[])

Converts string array into a String hash set.


stringSetToStringArray() ​

ts
conststringArray:string[] =
 Utils.android.collections.stringSetToStringArray(stringSet)

Converts string hash set into array of strings.


getDrawableId() ​

ts
constdrawableId:number= Utils.android.resources.getDrawableId(resourceName)

Gets the drawable id from a given resource name.


getStringId() ​

ts
conststringId:number= Utils.android.resources.getStringId(resourceName)

Gets the string id from a given resource name.


getPaletteColor() ​

ts
constpaletteColor:number= Utils.android.resources.getPaletteColor(
 resourceName,
 Utils.android.getApplicationContext(),
)

Gets a color from the current theme.


joinPaths() ​

ts
constjoinedPath:string= Utils.ios.joinPaths('photos', 'cat.png')

Joins the passed strings into a path.


getWindow() ​

ts
constwindow:UIWindow= Utils.ios.getWindow()

Gets the UIWindow of the app.


copyToClipboard() ​

ts
Utils.copyToClipboard(value):

Copies the specified value to device clipboard.


setWindowBackgroundColor() ​

ts
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() ​

ts
constappPath:string= Utils.ios.getCurrentAppPath()

Gets the root folder for the current application. Also see currentApp()


getVisibleViewController() ​

ts
constvisibleView: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() ​

ts
constrootView:UIViewController= Utils.ios.getRootViewController()

Gets the root UIViewController of the app.


getShadowLayer() ​

ts
constshadowLayer:CALayer= Utils.ios.getShadowLayer(nativeView, name, create)

  • nativeView is 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 to true, it indicates that a new layer should be created if no layer is found.

createUIDocumentInteractionControllerDelegate() ​

Create a UIDocumentInteractionControllerDelegate implementation for use with UIDocumentInteractionController


jsArrayToNSArray() ​

ts
constjsArrayToNSArray: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() ​

ts
constnsArrayToJSArray:Array<T> =nsArrayToJSArray<T>(a: NSArray<T>)

(iOS only)Converts NSArray of elements of a type T to an equivalent JavaScript array.


API Reference(s) ​

Previous
Trace
On this page
  1. Using Utils
    1. Validating a path for a resource or a local file
    2. Check if a URI is a data URI
    3. Opening a url
    4. Escaping regex symbols
    5. Check if the application is running on a physical device
    6. Checking if a value is a number
    7. Get a class hierarchy of an object
    8. Hiding a keyboard
  2. Utils API
    1. MajorVersion
    2. isFileOrResourcePath()
    3. isDataURI()
    4. openUrl()
    5. escapeRegexSymbols()
    6. convertString()
    7. GC()
    8. queueMacrotask()
    9. queueGC()
    10. debounce()
    11. throttle()
    12. isFontIconURI()
    13. executeOnMainThread()
    14. executeOnUIThread()
    15. mainThreadify()
    16. isMainThread()
    17. dispatchToMainThread()
    18. releaseNativeObject()
    19. getModuleName()
    20. openFile()
    21. isRealDevice()
    22. getClass()
    23. getBaseClasses()
    24. getClassInfo()
    25. isBoolean()
    26. isDefined()
    27. isUndefined()
    28. isNullOrUndefined()
    29. isFunction()
    30. isNumber()
    31. isObject()
    32. isString()
    33. toUIString()
    34. dataSerialize()
    35. dataDeserialize()
    36. setInterval()
    37. clearInterval()
    38. setTimeout()
    39. dismissKeyboard()
    40. getApplication()
    41. getApplicationContext()
    42. getInputMethodManager()
    43. showSoftInput()
    44. stringArrayToStringSet()
    45. stringSetToStringArray()
    46. getDrawableId()
    47. getStringId()
    48. getPaletteColor()
    49. joinPaths()
    50. getWindow()
    51. copyToClipboard()
    52. setWindowBackgroundColor()
    53. getCurrentAppPath()
    54. getVisibleViewController()
    55. getRootViewController()
    56. getShadowLayer()
    57. createUIDocumentInteractionControllerDelegate()
    58. jsArrayToNSArray()
    59. nsArrayToJSArray()
  3. API Reference(s)

Contributors

Edit this page

Last updated:

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /