ionic-native
- Version 2.9.0
- Published
- 1 dependency
- MIT license
Install
npm i ionic-native
yarn add ionic-native
pnpm add ionic-native
Overview
Native plugin wrappers for Cordova and Ionic with TypeScript, ES6+, Promise and Observable support
Index
Variables
Functions
Classes
Appodeal
- AD_TYPES
- cache()
- confirm()
- disableLocationPermissionCheck()
- disableNetwork()
- disableNetworkType()
- disableWriteExternalStoragePermissionCheck()
- enableBannerCallbacks()
- enableInterstitialCallbacks()
- enableNonSkippableVideoCallbacks()
- enableRewardedVideoCallbacks()
- enableSkippableVideoCallbacks()
- getVersion()
- hide()
- initialize()
- isInitialized()
- isLoaded()
- isPrecache()
- onBannerClicked()
- onBannerFailedToLoad()
- onBannerLoaded()
- onBannerShown()
- onInterstitialClicked()
- onInterstitialClosed()
- onInterstitialFailedToLoad()
- onInterstitialLoaded()
- onInterstitialShown()
- onNonSkippableVideoClosed()
- onNonSkippableVideoFailedToLoad()
- onNonSkippableVideoFinished()
- onNonSkippableVideoLoaded()
- onNonSkippableVideoShown()
- onRewardedVideoClosed()
- onRewardedVideoFailedToLoad()
- onRewardedVideoFinished()
- onRewardedVideoLoaded()
- onRewardedVideoShown()
- onSkippableVideoClosed()
- onSkippableVideoFailedToLoad()
- onSkippableVideoFinished()
- onSkippableVideoLoaded()
- onSkippableVideoShown()
- resetUUID()
- set728x90Banners()
- setAge()
- setAlcohol()
- setAutoCache()
- setBannerAnimation()
- setBannerBackground()
- setBirthday()
- setCustomBooleanRule()
- setCustomDoubleRule()
- setCustomIntegerRule()
- setCustomStringRule()
- setEmail()
- setGender()
- setInterests()
- setLogging()
- setOccupation()
- setOnLoadedTriggerBoth()
- setRelation()
- setSmartBanners()
- setSmoking()
- setTesting()
- setUserId()
- show()
- showWithPlacement()
BackgroundGeolocation
- Accuracy
- changePace()
- configure()
- deleteAllLocations()
- deleteLocation()
- finish()
- getLocations()
- getLogEntries()
- getStationaryLocation()
- getValidLocations()
- isLocationEnabled()
- LocationProvider
- Mode
- onStationary()
- setConfig()
- showAppSettings()
- showLocationSettings()
- start()
- stop()
- stopWatchingLocationMode()
- switchMode()
- watchLocationMode()
Calendar
- createCalendar()
- createEvent()
- createEventInteractively()
- createEventInteractivelyWithOptions()
- createEventWithOptions()
- deleteCalendar()
- deleteEvent()
- deleteEventFromNamedCalendar()
- findAllEventsInNamedCalendar()
- findEvent()
- findEventWithOptions()
- getCalendarOptions()
- hasReadPermission()
- hasReadWritePermission()
- hasWritePermission()
- listCalendars()
- listEventsInRange()
- modifyEvent()
- modifyEventWithOptions()
- openCalendar()
- requestReadPermission()
- requestReadWritePermission()
- requestWritePermission()
Diagnostic
- bluetoothState
- getBackgroundRefreshStatus()
- getBluetoothState()
- getCalendarAuthorizationStatus()
- getCameraAuthorizationStatus()
- getCameraRollAuthorizationStatus()
- getContactsAuthorizationStatus()
- getExternalSdCardDetails()
- getExternalStorageAuthorizationStatus()
- getLocationAuthorizationStatus()
- getLocationMode()
- getMicrophoneAuthorizationStatus()
- getPermissionAuthorizationStatus()
- getPermissionsAuthorizationStatus()
- getRemindersAuthorizationStatus()
- getRemoteNotificationTypes()
- hasBluetoothLEPeripheralSupport()
- hasBluetoothLESupport()
- hasBluetoothSupport()
- isBackgroundRefreshAuthorized()
- isBluetoothAvailable()
- isBluetoothEnabled()
- isCalendarAuthorized()
- isCameraAuthorized()
- isCameraAvailable()
- isCameraPresent()
- isCameraRollAuthorized()
- isContactsAuthorized()
- isExternalStorageAuthorized()
- isGpsLocationAvailable()
- isGpsLocationEnabled()
- isLocationAuthorized()
- isLocationAvailable()
- isLocationEnabled()
- isMicrophoneAuthorized()
- isMotionAvailable()
- isMotionRequestOutcomeAvailable()
- isNetworkLocationAvailable()
- isNetworkLocationEnabled()
- isNFCAvailable()
- isNFCEnabled()
- isNFCPresent()
- isRegisteredForRemoteNotifications()
- isRemindersAuthorized()
- isRemoteNotificationsEnabled()
- isRequestingPermission()
- isWifiAvailable()
- isWifiEnabled()
- locationAuthorizationMode
- locationMode
- NFCState
- permission
- permissionGroups
- permissionStatus
- registerBluetoothStateChangeHandler()
- registerLocationStateChangeHandler()
- registerNFCStateChangeHandler()
- registerPermissionRequestCompleteHandler()
- requestAndCheckMotionAuthorization()
- requestBluetoothAuthorization()
- requestCalendarAuthorization()
- requestCameraAuthorization()
- requestCameraRollAuthorization()
- requestContactsAuthorization()
- requestExternalStorageAuthorization()
- requestLocationAuthorization()
- requestMicrophoneAuthorization()
- requestRemindersAuthorization()
- requestRuntimePermission()
- requestRuntimePermissions()
- setBluetoothState()
- setWifiState()
- switchToBluetoothSettings()
- switchToLocationSettings()
- switchToMobileDataSettings()
- switchToNFCSettings()
- switchToSettings()
- switchToWifiSettings()
- switchToWirelessSettings()
EstimoteBeacons
- authorizationStatus()
- BeaconColorBlueberryPie
- BeaconColorCandyFloss
- BeaconColorIcyMarshmallow
- BeaconColorLemonTart
- BeaconColorLiquoriceSwirl
- BeaconColorMintCocktail
- BeaconColorSweetBeetroot
- BeaconColorTransparent
- BeaconColorUnknown
- BeaconColorVanillaJello
- BeaconColorWhite
- connectToBeacon()
- disconnectConnectedBeacon()
- enableAnalytics()
- isAnalyticsEnabled()
- isAuthorized()
- ProximityFar
- ProximityImmediate
- ProximityNear
- ProximityUnknown
- RegionStateInside
- RegionStateOutside
- RegionStateUnknown
- requestAlwaysAuthorization()
- requestWhenInUseAuthorization()
- setupAppIDAndAppToken()
- startAdvertisingAsBeacon()
- startEstimoteBeaconDiscovery()
- startMonitoringForRegion()
- startRangingBeaconsInRegion()
- startRangingSecureBeaconsInRegion()
- startSecureMonitoringForRegion()
- stopAdvertisingAsBeacon()
- stopEstimoteBeaconDiscovery()
- stopMonitoringForRegion()
- stopRangingBeaconsInRegion()
- stopRangingSecureBeaconsInRegion()
- stopSecureMonitoringForRegion()
- writeConnectedMajor()
- writeConnectedMinor()
- writeConnectedProximityUUID()
File
- applicationDirectory
- applicationStorageDirectory
- cacheDirectory
- checkDir()
- checkFile()
- copyDir()
- copyFile()
- cordovaFileError
- createDir()
- createFile()
- dataDirectory
- documentsDirectory
- externalApplicationStorageDirectory
- externalCacheDirectory
- externalDataDirectory
- externalRootDirectory
- getDirectory()
- getFile()
- getFreeDiskSpace()
- listDir()
- moveDir()
- moveFile()
- readAsArrayBuffer()
- readAsBinaryString()
- readAsDataURL()
- readAsText()
- removeDir()
- removeFile()
- removeRecursively()
- resolveDirectoryUrl()
- resolveLocalFilesystemUrl()
- sharedDirectory
- syncedDataDirectory
- tempDirectory
- writeExistingFile()
- writeFile()
GoogleMap
- addCircle()
- addEventListener()
- addGroundOverlay()
- addKmlOverlay()
- addListenerOnce()
- addMarker()
- addPolygon()
- addPolyline()
- addTileOverlay()
- animateCamera()
- clear()
- closeDialog()
- empty()
- fromLatLngToPoint()
- fromPointToLatLng()
- get()
- getCameraPosition()
- getLicenseInfo()
- getMyLocation()
- getVisibleRegion()
- isAvailable()
- moveCamera()
- on()
- one()
- panBy()
- refreshLayout()
- remove()
- set()
- setAllGesturesEnabled()
- setBackgroundColor()
- setCenter()
- setClickable()
- setCompassEnabled()
- setDebuggable()
- setDiv()
- setIndoorEnabled()
- setMapTypeId()
- setMyLocationEnabled()
- setOptions()
- setPadding()
- setTilt()
- setTrafficEnabled()
- setVisible()
- setZoom()
- showDialog()
- toDataURL()
GoogleMapsMarker
- addEventListener()
- addListenerOnce()
- empty()
- get()
- getHashCode()
- getMap()
- getOpacity()
- getPosition()
- getRotation()
- getSnippet()
- getTitle()
- hideInfoWindow()
- isDraggable()
- isVisible()
- on()
- one()
- remove()
- set()
- setAnimation()
- setDraggable()
- setFlat()
- setIcon()
- setIconAnchor()
- setInfoWindowAnchor()
- setOpacity()
- setPosition()
- setRotation()
- setSnippet()
- setTitle()
- setVisible()
- setZIndex()
- showInfoWindow()
Hotspot
- addWifiNetwork()
- configureHotspot()
- connectToWifi()
- connectToWifiAuthEncrypt()
- createHotspot()
- getAllHotspotDevices()
- getConnectionInfo()
- getMacAddressOfHost()
- getNetConfig()
- isAvailable()
- isConnectedToInternet()
- isConnectedToInternetViaWifi()
- isDnsLive()
- isHotspotEnabled()
- isPortLive()
- isRooted()
- isWifiDirectSupported()
- isWifiOn()
- isWifiSupported()
- pingHost()
- removeWifiNetwork()
- scanWifi()
- scanWifiByLevel()
- startHotspot()
- startWifiPeriodicallyScan()
- stopHotspot()
- stopWifiPeriodicallyScan()
- toggleWifi()
IBeacon
- appendToDeviceLog()
- BeaconRegion()
- Delegate()
- disableBluetooth()
- disableDebugLogs()
- disableDebugNotifications()
- enableBluetooth()
- enableDebugLogs()
- enableDebugNotifications()
- getAuthorizationStatus()
- getDelegate()
- getMonitoredRegions()
- getRangedRegions()
- isAdvertising()
- isAdvertisingAvailable()
- isBluetoothEnabled()
- isMonitoringAvailableForClass()
- isRangingAvailable()
- onDomDelegateReady()
- requestAlwaysAuthorization()
- requestStateForRegion()
- requestWhenInUseAuthorization()
- setDelegate()
- startAdvertising()
- startMonitoringForRegion()
- startRangingBeaconsInRegion()
- stopAdvertising()
- stopMonitoringForRegion()
- stopRangingBeaconsInRegion()
LocationAccuracy
- canRequest()
- ERROR_ALREADY_REQUESTING
- ERROR_CANNOT_CHANGE_ACCURACY
- ERROR_EXCEPTION
- ERROR_GOOGLE_API_CONNECTION_FAILED
- ERROR_INVALID_ACCURACY
- ERROR_INVALID_ACTION
- ERROR_USER_DISAGREED
- isRequesting()
- request()
- REQUEST_PRIORITY_BALANCED_POWER_ACCURACY
- REQUEST_PRIORITY_HIGH_ACCURACY
- REQUEST_PRIORITY_LOW_POWER
- REQUEST_PRIORITY_NO_POWER
- SUCCESS_SETTINGS_SATISFIED
- SUCCESS_USER_AGREED
OneSignal
- deleteTag()
- deleteTags()
- enableSound()
- enableVibrate()
- endInit()
- getIds()
- getTags()
- handleNotificationOpened()
- handleNotificationReceived()
- inFocusDisplaying()
- iOSSettings()
- OSInFocusDisplayOption
- postNotification()
- promptLocation()
- registerForPushNotifications()
- sendTag()
- sendTags()
- setLogLevel()
- setSubscription()
- startInit()
- syncHashedEmail()
Interfaces
BackgroundGeolocationConfig
- activitiesInterval
- activityType
- debug
- desiredAccuracy
- distanceFilter
- fastestInterval
- httpHeaders
- interval
- locationProvider
- maxLocations
- notificationIconColor
- notificationIconLarge
- notificationIconSmall
- notificationText
- notificationTitle
- pauseLocationUpdates
- saveBatteryOnBackground
- startForeground
- startOnBoot
- stationaryRadius
- stopOnStillActivity
- stopOnTerminate
- syncThreshold
- syncUrl
- url
InAppBrowserOptions
- allowInlineMediaPlayback
- clearcache
- clearsessioncache
- closebuttoncaption
- disallowoverscroll
- enableViewportScale
- fullscreen
- hardwareback
- hidden
- keyboardDisplayRequiresUserAction
- location
- mediaPlaybackRequiresUserAction
- presentationstyle
- shouldPauseOnSuspend
- suppressesIncrementalRendering
- toolbar
- toolbarposition
- transitionstyle
- zoom
OSNotification
- adm_big_picture
- adm_group
- adm_group_message
- adm_large_icon
- adm_small_icon
- adm_sound
- amazon_background_data
- android_accent_color
- android_group
- android_group_message
- android_led_color
- android_sound
- android_visibility
- androidNotificationId
- app_id
- app_ids
- big_picture
- buttons
- chrome_big_picture
- chrome_icon
- chrome_web_icon
- content_available
- contents
- data
- delayed_option
- delivery_time_of_day
- displayType
- excluded_segments
- firefox_icon
- groupedNotifications
- headings
- include_amazon_reg_ids
- include_android_reg_ids
- include_chrome_reg_ids
- include_chrome_web_reg_ids
- include_ios_tokens
- include_player_ids
- include_wp_uris
- include_wp_wns_uris
- included_segments
- ios_badgeCount
- ios_badgeType
- ios_category
- ios_sound
- isAdm
- isAndroid
- isAnyWeb
- isAppInFocus
- isChrome
- isChromeWeb
- isIos
- isSafari
- isWP
- isWP_WNS
- large_icon
- payload
- priority
- send_after
- shown
- small_icon
- tags
- template_id
- ttl
- url
- wp_sound
- wp_wns_sound
ThemeableBrowserOptions
- allowInlineMediaPlayback
- backButton
- backButtonCanClose
- clearcache
- clearsessioncache
- closeButton
- closebuttoncaption
- customButtons
- disableAnimation
- disallowoverscroll
- enableViewportScale
- forwardButton
- fullscreen
- hardwareback
- hidden
- keyboardDisplayRequiresUserAction
- location
- mediaPlaybackRequiresUserAction
- menu
- presentationstyle
- shouldPauseOnSuspsend
- statusbar
- suppressesIncrementalRendering
- title
- toolbar
- toolbarposition
- transitionstyle
- zoom
Enums
Type Aliases
Variables
variable ContactError
var ContactError: { new (code: number): IContactError; UNKNOWN_ERROR: number; INVALID_ARGUMENT_ERROR: number; TIMEOUT_ERROR: number; PENDING_OPERATION_ERROR: number; IO_ERROR: number; NOT_SUPPORTED_ERROR: number; PERMISSION_DENIED_ERROR: number;};
variable FileError
var FileError: { new (code: number): FileError; NOT_FOUND_ERR: number; SECURITY_ERR: number; ABORT_ERR: number; NOT_READABLE_ERR: number; ENCODING_ERR: number; NO_MODIFICATION_ALLOWED_ERR: number; INVALID_STATE_ERR: number; SYNTAX_ERR: number; INVALID_MODIFICATION_ERR: number; QUOTA_EXCEEDED_ERR: number; TYPE_MISMATCH_ERR: number; PATH_EXISTS_ERR: number;};
variable FileReader
var FileReader: { new (): FileReader; EMPTY: number; LOADING: number; DONE: number };
variable FileWriter
var FileWriter: { INIT: number; WRITING: number; DONE: number };
variable GoogleMapsAnimation
const GoogleMapsAnimation: { BOUNCE: string; DROP: string };
variable GoogleMapsEvent
const GoogleMapsEvent: { MAP_CLICK: string; MAP_LONG_CLICK: string; MY_LOCATION_CHANGE: string; MY_LOCATION_BUTTON_CLICK: string; INDOOR_BUILDING_FOCUSED: string; INDOOR_LEVEL_ACTIVATED: string; CAMERA_CHANGE: string; CAMERA_IDLE: string; MAP_READY: string; MAP_LOADED: string; MAP_WILL_MOVE: string; MAP_CLOSE: string; MARKER_CLICK: string; OVERLAY_CLICK: string; INFO_CLICK: string; MARKER_DRAG: string; MARKER_DRAG_START: string; MARKER_DRAG_END: string;};
You can listen to these events where appropriate
variable GoogleMapsMapTypeId
const GoogleMapsMapTypeId: { HYBRID: string; NONE: string; NORMAL: string; ROADMAP: string; SATELLITE: string; TERAIN: string;};
Functions
function Cordova
Cordova: ( opts?: CordovaOptions) => ( target: Object, methodName: string, descriptor: TypedPropertyDescriptor<any>) => { value: (...args: any[]) => any };
Wrap a stub function in a call to a Cordova plugin, checking if both Cordova and the required plugin are installed.
function CordovaFiniteObservable
CordovaFiniteObservable: ( opts?: CordovaFiniteObservableOptions) => ( target: Object, methodName: string, descriptor: TypedPropertyDescriptor<any>) => { value: (...args: any[]) => Observable<any> };
Wraps method that returns an observable that can be completed. Provided opts.resultFinalPredicate dictates when the observable completes.
function CordovaFunctionOverride
CordovaFunctionOverride: ( opts?: any) => ( target: Object, methodName: string, descriptor: TypedPropertyDescriptor<any>) => { value: (...args: any[]) => Observable<any> };
Wrap a stub function in a call to a Cordova plugin, checking if both Cordova and the required plugin are installed.
function CordovaInstance
CordovaInstance: ( opts?: any) => (target: Object, methodName: string) => { value: (...args: any[]) => any };
Wrap an instance method
function CordovaProperty
CordovaProperty: (target: any, key: string) => void;
Before calling the original method, ensure Cordova and the plugin are installed.
function cordovaWarn
cordovaWarn: (pluginName: string, method: string) => void;
Parameter pluginName
Parameter method
function getPlugin
getPlugin: (pluginRef: string) => any;
Parameter pluginRef
Returns
{null|*}
function getPromise
getPromise: (cb: any) => any;
function InstanceProperty
InstanceProperty: (target: any, key: string) => void;
Parameter target
Parameter key
function Plugin
Plugin: (config: PluginConfig) => (cls: any) => any;
Class decorator specifying Plugin metadata. Required for all plugins.
@Plugin({pluginName: 'MyPlugin',plugin: 'cordova-plugin-myplugin',pluginRef: 'window.myplugin'})export class MyPlugin {// Plugin wrappers, properties, and functions go here ...}
function pluginWarn
pluginWarn: (pluginObj: any, method?: string) => void;
Parameter pluginObj
Parameter method
function wrap
wrap: ( pluginObj: any, methodName: string, opts?: CordovaOptions) => (...args: any[]) => any;
Parameter pluginObj
Parameter methodName
Parameter opts
Returns
{function(...[any]): (undefined|*|Observable|*|*)}
Classes
class ActionSheet
class ActionSheet {}
Action Sheet The ActionSheet plugin shows a native list of options the user can choose from.
Requires Cordova plugin:
cordova-plugin-actionsheet
. For more info, please see the [ActionSheet plugin docs](https://github.com/EddyVerbruggen/cordova-plugin-actionsheet).import { ActionSheet } from 'ionic-native';let buttonLabels = ['Share via Facebook', 'Share via Twitter'];ActionSheet.show({'title': 'What do you want with this image?','buttonLabels': buttonLabels,'addCancelButtonWithLabel': 'Cancel','addDestructiveButtonWithLabel' : 'Delete'}).then((buttonIndex: number) => {console.log('Button pressed: ' + buttonIndex);});ActionSheetOptions
method hide
static hide: (options?: any) => Promise<any>;
Progamtically hide the native ActionSheet
Returns
{Promise} Returns a Promise that resolves when the actionsheet is closed
method show
static show: (options?: ActionSheetOptions) => Promise<any>;
Show a native ActionSheet component. See below for options.
Parameter options
Options See table below
Returns
{Promise} Returns a Promise that resolves with the index of the button pressed (1 based, so 1, 2, 3, etc.)
class AdMob
class AdMob {}
AdMob Plugin for Google Ads, including AdMob / DFP (doubleclick for publisher) and mediations to other Ad networks.
import { AdMob } from 'ionic-native';ionViewDidLoad() {AdMob.onAdDismiss().subscribe(() => { console.log('User dismissed ad'); });}onClick() {AdMob.prepareInterstitial('YOUR_ADID').then(() => { AdMob.showInterstitial(); });}AdMobOptions AdMobAdExtras
property AD_POSITION
static AD_POSITION: { NO_CHANGE: number; TOP_LEFT: number; TOP_CENTER: number; TOP_RIGHT: number; LEFT: number; CENTER: number; RIGHT: number; BOTTOM_LEFT: number; BOTTOM_CENTER: number; BOTTOM_RIGHT: number; POS_XY: number;};
method createBanner
static createBanner: (adIdOrOptions: string | AdMobOptions) => Promise<any>;
Create a banner
Parameter adIdOrOptions
Ad ID or Options
Returns
{Promise} Returns a Promise that resolves when the banner is created
method getAdSettings
static getAdSettings: () => Promise<any>;
Get user ad settings
Returns
{Promise} Returns a promise that resolves with the ad settings
method hideBanner
static hideBanner: () => void;
Hide the banner, remove it from screen, but can show it later
method onAdDismiss
static onAdDismiss: () => Observable<any>;
Triggered when dismiss the Ad and back to your App
Returns
{Observable}
method onAdFailLoad
static onAdFailLoad: () => Observable<any>;
Triggered when failed to receive Ad
Returns
{Observable}
method onAdLeaveApp
static onAdLeaveApp: () => Observable<any>;
Triggered when user click the Ad, and will jump out of your App
Returns
{Observable}
method onAdLoaded
static onAdLoaded: () => Observable<any>;
Triggered when Ad received
Returns
{Observable}
method onAdPresent
static onAdPresent: () => Observable<any>;
Triggered when Ad will be showed on screen
Returns
{Observable}
method prepareInterstitial
static prepareInterstitial: ( adIdOrOptions: string | AdMobOptions) => Promise<any>;
Prepare interstitial banner
Parameter adIdOrOptions
Ad ID or Options
Returns
{Promise} Returns a Promise that resolves when interstitial is prepared
method prepareRewardVideoAd
static prepareRewardVideoAd: ( adIdOrOptions: string | AdMobOptions) => Promise<any>;
Prepare a reward video ad
Parameter adIdOrOptions
Ad ID or Options
Returns
{Promise} Returns a Promise that resolves when the ad is prepared
method removeBanner
static removeBanner: () => void;
Destroy the banner, remove it from screen.
method setOptions
static setOptions: (options: AdMobOptions) => Promise<any>;
Sets the values for configuration and targeting
Parameter options
Options
Returns
{Promise} Returns a Promise that resolves when the options have been set
method showBanner
static showBanner: (position: number) => void;
Show banner at position
Parameter position
Position. Use
AdMob.AD_POSITION
to set values.
method showBannerAtXY
static showBannerAtXY: (x: number, y: number) => void;
Show banner at custom position
Parameter x
Offset from screen left.
Parameter y
Offset from screen top.
method showInterstitial
static showInterstitial: () => void;
Show interstitial ad when it's ready
method showRewardVideoAd
static showRewardVideoAd: () => void;
Show a reward video ad
class Alipay
class Alipay {}
Alipay This plugin is used for Alipay APP support. Integrated with the latest SDK.
Requires Cordova plugin:
cordova-alipay-base
. For more info, please see the [Alipay plugin docs](https://github.com/xueron/cordova-alipay-base).import { Alipay } from 'ionic-native';// Should get from server side with sign.let alipayOrder = {...};Alipay.pay(alipayOrder).then(result => {console.log(result); // Success}).catch(error => {console.log(error); // Failed});AlipayOrder
method pay
static pay: (order: AlipayOrder) => Promise<any>;
Open Alipay to perform App pay
Parameter order
alipay options
Returns
{Promise} Returns a Promise that resolves with the success return, or rejects with an error.
class AndroidFingerprintAuth
class AndroidFingerprintAuth {}
Android Fingerprint Auth This plugin will open a native dialog fragment prompting the user to authenticate using their fingerprint. If the device has a secure lockscreen (pattern, PIN, or password), the user may opt to authenticate using that method as a backup.
import { AndroidFingerprintAuth } from 'ionic-native';AndroidFingerprintAuth.isAvailable().then((result)=> {if(result.isAvailable){// it is availableAndroidFingerprintAuth.encrypt({ clientId: "myAppName", username: "myUsername", password: "myPassword" }).then(result => {if (result.withFingerprint) {console.log("Successfully encrypted credentials.");console.log("Encrypted credentials: " + result.token);} else if (result.withBackup) {console.log('Successfully authenticated with backup password!');} else console.log('Didn\'t authenticate!');}).catch(error => {if (error === "Cancelled") {console.log("Fingerprint authentication cancelled");} else console.error(error)});} else {// fingerprint auth isn't available}}).catch(error => console.error(error));AndroidFingerprintAuthOptions
method decrypt
static decrypt: ( options: AndroidFingerprintAuthOptions) => Promise<{ withFingerprint: boolean; withBackup: boolean; password: string;}>;
Opens a native dialog fragment to use the device hardware fingerprint scanner to authenticate against fingerprints registered for the device.
Parameter options
Options
Returns
{Promise}
method delete
static delete: (options: { clientId: string; username: string;}) => Promise<{ deleted: boolean }>;
Delete the cipher used for encryption and decryption by username
Returns
{Promise} Returns a Promise that resolves if the cipher was successfully deleted
method encrypt
static encrypt: ( options: AndroidFingerprintAuthOptions) => Promise<{ withFingerprint: boolean; withBackup: boolean; token: string }>;
Opens a native dialog fragment to use the device hardware fingerprint scanner to authenticate against fingerprints registered for the device.
Parameter options
Options
Returns
{Promise}
method isAvailable
static isAvailable: () => Promise<{ isAvailable: boolean }>;
Check if service is available
Returns
{Promise} Returns a Promise that resolves if fingerprint auth is available on the device
class AppAvailability
class AppAvailability {}
App Availability This plugin allows you to check if an app is installed on the user's device. It requires an URI Scheme (e.g. twitter://) on iOS or a Package Name (e.g com.twitter.android) on Android.
Requires Cordova plugin: cordova-plugin-appavailability. For more info, please see the [AppAvailability plugin docs](https://github.com/ohh2ahh/AppAvailability).
import { AppAvailability, Device } from 'ionic-native';let app;if (Device.platform === 'iOS') {app = 'twitter://';} else if (Device.platform === 'Android') {app = 'com.twitter.android';}AppAvailability.check(app).then((yes: string) => console.log(app + ' is available'),(no: string) => console.log(app + ' is NOT available'));
method check
static check: (app: string) => Promise<boolean>;
Checks if an app is available on device
Parameter app
Package name on android, or URI scheme on iOS
Returns
{Promise}
class Appodeal
class Appodeal {}
Appodeal Plugin to serve ads through native Appodeal SDKs
import { Appodeal } from 'ionic-native';let appKey = '<your app key>';Appodeal.initialize(appKey, Appodeal.AD_TYPES.REWARDED_VIDEO);Appodeal.show(Appodeal.AD_TYPES.REWARDED_VIDEO);
property AD_TYPES
static readonly AD_TYPES: { INTERSTITIAL: number; SKIPPABLE_VIDEO: number; BANNER: number; BANNER_BOTTOM: number; BANNER_TOP: number; REWARDED_VIDEO: number; NON_SKIPPABLE_VIDEO: number;};
method cache
static cache: (adType: number) => void;
forcefully cache an ad by type
Parameter adType
method confirm
static confirm: (adType: number) => void;
confirm use of ads of specified type
Parameter adType
method disableLocationPermissionCheck
static disableLocationPermissionCheck: () => void;
disable Location permissions for Appodeal SDK
method disableNetwork
static disableNetwork: (network?: string, adType?: number) => void;
Parameter network
Parameter adType
method disableNetworkType
static disableNetworkType: (network?: string, adType?: number) => void;
Parameter network
Parameter adType
method disableWriteExternalStoragePermissionCheck
static disableWriteExternalStoragePermissionCheck: () => void;
disable Storage permissions for Appodeal SDK
method enableBannerCallbacks
static enableBannerCallbacks: (enabled: boolean) => void;
enable event listeners
Parameter enabled
method enableInterstitialCallbacks
static enableInterstitialCallbacks: (enabled: boolean) => void;
enable event listeners
Parameter enabled
method enableNonSkippableVideoCallbacks
static enableNonSkippableVideoCallbacks: (enabled: boolean) => void;
enable event listeners
Parameter enabled
method enableRewardedVideoCallbacks
static enableRewardedVideoCallbacks: (enabled: boolean) => void;
enable event listeners
Parameter enabled
method enableSkippableVideoCallbacks
static enableSkippableVideoCallbacks: (enabled: boolean) => void;
enable event listeners
Parameter enabled
method getVersion
static getVersion: () => Promise<any>;
get version of Appdeal SDK
method hide
static hide: (adType: number) => void;
hide ad of specified type
Parameter adType
method initialize
static initialize: (appKey: string, adType: number) => void;
initialize Appodeal SDK
Parameter appKey
Parameter adType
method isInitialized
static isInitialized: () => Promise<any>;
check if SDK has been initialized
Returns
{Promise}
method isLoaded
static isLoaded: (adType: number) => Promise<any>;
check if ad of specified type has been loaded
Parameter adType
Returns
{Promise}
method isPrecache
static isPrecache: (adType: number) => Promise<any>;
check if ad of specified
Parameter adType
Returns
{Promise}
method onBannerClicked
static onBannerClicked: () => Observable<any>;
method onBannerFailedToLoad
static onBannerFailedToLoad: () => Observable<any>;
method onBannerLoaded
static onBannerLoaded: () => Observable<any>;
method onBannerShown
static onBannerShown: () => Observable<any>;
method onInterstitialClicked
static onInterstitialClicked: () => Observable<any>;
method onInterstitialClosed
static onInterstitialClosed: () => Observable<any>;
method onInterstitialFailedToLoad
static onInterstitialFailedToLoad: () => Observable<any>;
method onInterstitialLoaded
static onInterstitialLoaded: () => Observable<any>;
******************* event Observables * *******************
method onInterstitialShown
static onInterstitialShown: () => Observable<any>;
method onNonSkippableVideoClosed
static onNonSkippableVideoClosed: () => Observable<any>;
method onNonSkippableVideoFailedToLoad
static onNonSkippableVideoFailedToLoad: () => Observable<any>;
method onNonSkippableVideoFinished
static onNonSkippableVideoFinished: () => Observable<any>;
method onNonSkippableVideoLoaded
static onNonSkippableVideoLoaded: () => Observable<any>;
method onNonSkippableVideoShown
static onNonSkippableVideoShown: () => Observable<any>;
method onRewardedVideoClosed
static onRewardedVideoClosed: () => Observable<any>;
method onRewardedVideoFailedToLoad
static onRewardedVideoFailedToLoad: () => Observable<any>;
method onRewardedVideoFinished
static onRewardedVideoFinished: () => Observable<any>;
method onRewardedVideoLoaded
static onRewardedVideoLoaded: () => Observable<any>;
method onRewardedVideoShown
static onRewardedVideoShown: () => Observable<any>;
method onSkippableVideoClosed
static onSkippableVideoClosed: () => Observable<any>;
method onSkippableVideoFailedToLoad
static onSkippableVideoFailedToLoad: () => Observable<any>;
method onSkippableVideoFinished
static onSkippableVideoFinished: () => Observable<any>;
method onSkippableVideoLoaded
static onSkippableVideoLoaded: () => Observable<any>;
method onSkippableVideoShown
static onSkippableVideoShown: () => Observable<any>;
method resetUUID
static resetUUID: () => void;
reset device ID
method set728x90Banners
static set728x90Banners: (value: any) => void;
Parameter value
method setAge
static setAge: (age: any) => void;
et Age preference in Appodeal for current user
Parameter age
method setAlcohol
static setAlcohol: (alcohol: any) => void;
set Alcohol preference in Appodeal for current user
Parameter alcohol
method setAutoCache
static setAutoCache: (adType: number, autoCache: any) => void;
Parameter adType
Parameter autoCache
method setBannerAnimation
static setBannerAnimation: (enabled: boolean) => void;
enable or disable banner animations
Parameter enabled
method setBannerBackground
static setBannerBackground: (enabled: boolean) => void;
enable or disable banner backgrounds
Parameter enabled
method setBirthday
static setBirthday: (birthday: any) => void;
set Birthday preference in Appodeal for current user
Parameter birthday
method setCustomBooleanRule
static setCustomBooleanRule: (name: string, value: boolean) => void;
Parameter name
name of rule
Parameter value
method setCustomDoubleRule
static setCustomDoubleRule: (name: string, value: number) => void;
set rule with float value
Parameter name
Parameter value
method setCustomIntegerRule
static setCustomIntegerRule: (name: string, value: number) => void;
Parameter name
name of rule
Parameter value
method setCustomStringRule
static setCustomStringRule: (name: string, value: string) => void;
set rule with string value
Parameter name
name of rule
Parameter value
method setEmail
static setEmail: (email: any) => void;
set Email preference in Appodeal for current user
Parameter email
method setGender
static setGender: (gender: any) => void;
set Gender preference in Appodeal for current user
Parameter gender
method setInterests
static setInterests: (interests: any) => void;
set Interests preference in Appodeal for current user
Parameter interests
method setLogging
static setLogging: (logging: boolean) => void;
enable or disable logging
Parameter logging
method setOccupation
static setOccupation: (occupation: any) => void;
set Occupation preference in Appodeal for current user
Parameter occupation
method setOnLoadedTriggerBoth
static setOnLoadedTriggerBoth: (set: boolean) => void;
Parameter set
method setRelation
static setRelation: (relation: any) => void;
set Relation preference in Appodeal for current user
Parameter relation
method setSmartBanners
static setSmartBanners: (enabled: boolean) => void;
enable or disable Smart Banners
Parameter enabled
method setSmoking
static setSmoking: (smoking: any) => void;
set Smoking preference in Appodeal for current user
Parameter smoking
method setTesting
static setTesting: (testing: boolean) => void;
enable or disable testing mode
Parameter testing
method setUserId
static setUserId: (id: any) => void;
set ID preference in Appodeal for current user
Parameter id
method show
static show: (adType: number) => Promise<any>;
show ad of specified type
Parameter adType
Returns
{Promise}
method showWithPlacement
static showWithPlacement: (adType: number, placement: any) => Promise<any>;
show ad of specified type with placement options
Parameter adType
Parameter placement
Returns
{Promise}
class AppPreferences
class AppPreferences {}
AppPreferences This plugin allows you to read and write app preferences
import { AppPreferences } from 'ionic-native';AppPreferences.fetch('key').then((res) => { console.log(res); });
method clearAll
static clearAll: () => Promise<any>;
Clear preferences
{Promise} Returns a promise
method cloudSync
static cloudSync: () => Object;
Return cloud synchronized configuration context Currently supports Windows and iOS/macOS
Returns
{Object} Custom object, bound to that suite
method defaults
static defaults: () => Object;
Return default configuration context Currently supports Windows and iOS/macOS
Returns
{Object} Custom Object, bound to that suite
method fetch
static fetch: (dict: string, key?: string) => Promise<any>;
Get a preference value
Parameter dict
Dictionary for key (OPTIONAL)
Parameter key
Key {Promise} Returns a promise
method iosSuite
static iosSuite: (suiteName: string) => Object;
method remove
static remove: (dict: string, key?: string) => Promise<any>;
Remove value from preferences
Parameter dict
Dictionary for key (OPTIONAL)
Parameter key
Key {Promise} Returns a promise
method show
static show: () => Promise<any>;
Show native preferences interface
{Promise} Returns a promise
method store
static store: (dict: string, key: string, value?: string) => Promise<any>;
Set a preference value
Parameter dict
Dictionary for key (OPTIONAL)
Parameter key
Key
Parameter value
Value {Promise} Returns a promise
method suite
static suite: (suiteName: string) => Object;
Return named configuration context In iOS you'll get a suite configuration, on Android — named file Supports: Android, iOS
Parameter suiteName
suite name
Returns
{Object} Custom object, bound to that suite
method watch
static watch: (subscribe: boolean) => Observable<any>;
Show native preferences interface
Parameter subscribe
true value to subscribe, false - unsubscribe {Observable} Returns an observable
class AppRate
class AppRate {}
App Rate The AppRate plugin makes it easy to prompt the user to rate your app, either now, later, or never.
Requires Cordova plugin: cordova-plugin-apprate. For more info, please see the [AppRate plugin docs](https://github.com/pushandplay/cordova-plugin-apprate).
import { AppRate } from 'ionic-native';AppRate.preferences.storeAppURL = {ios: '<my_app_id>',android: 'market://details?id=<package_name>',windows: 'ms-windows-store://review/?ProductId=<Store_ID>'};AppRate.promptForRating(false);AppRatePreferences AppRateStoreAppUrls AppRateCallbacks
property preferences
static preferences: AppRatePreferences;
Configure various settings for the Rating View. See table below for options
method promptForRating
static promptForRating: (immediately: boolean) => void;
Prompts the user for rating
Parameter immediately
Show the rating prompt immediately.
class AppUpdate
class AppUpdate {}
AppUpdate This plugin does self-update for android
You should first host an XML file on your server with the following data in it:
<update><version>302048</version><name>APK Name</name><url>https://your-remote-api.com/YourApp.apk</url></update>Then use the following code:
import { AppUpdate } from 'ionic-native';let updateUrl = 'http://your-remote-api.com/update.xml';AppUpdate.checkAppUpdate(updateUrl);The plugin will compare the app version and update it automatically if the API has a newer version to install.
method checkAppUpdate
static checkAppUpdate: (updateUrl: string) => Promise<any>;
Check and update
Parameter updateUrl
update api url {Promise} Returns a promise that resolves when something happens
class AppVersion
class AppVersion {}
App Version Reads the version of your app from the target build settings.
Requires Cordova plugin:
cordova-plugin-app-version
. For more info, please see the [Cordova App Version docs](https://github.com/whiteoctober/cordova-plugin-app-version).import { AppVersion } from 'ionic-native';AppVersion.getAppName();AppVersion.getPackageName();AppVersion.getVersionCode();AppVersion.getVersionNumber();
method getAppName
static getAppName: () => Promise<any>;
Returns the name of the app
Returns
{Promise}
method getPackageName
static getPackageName: () => Promise<any>;
Returns the package name of the app
Returns
{Promise}
method getVersionCode
static getVersionCode: () => Promise<any>;
Returns the build identifier of the app
Returns
{Promise}
method getVersionNumber
static getVersionNumber: () => Promise<any>;
Returns the version of the app
Returns
{Promise}
class BackgroundFetch
class BackgroundFetch {}
BackgroundFetch iOS Background Fetch Implementation. See: https://developer.apple.com/reference/uikit/uiapplication#1657399 iOS Background Fetch is basically an API which wakes up your app about every 15 minutes (during the user's prime-time hours) and provides your app exactly 30s of background running-time. This plugin will execute your provided callbackFn whenever a background-fetch event occurs. There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible value of UIApplicationBackgroundFetchIntervalMinimum -- iOS determines the rate automatically based upon device usage and time-of-day (ie: fetch-rate is about ~15min during prime-time hours; less frequently when the user is presumed to be sleeping, at 3am for example). For more detail, please see https://github.com/transistorsoft/cordova-plugin-background-fetch
import { BackgroundFetch } from 'ionic-native';// When device is ready :platform.ready().then(() => {let config = {stopOnTerminate: false, // Set true to cease background-fetch from operating after user "closes" the app. Defaults to true.};BackgroundFetch.configure(() => {console.log('[js] BackgroundFetch initiated');// perform some ajax request to server hereYou MUST called #finish so that native-side can signal completion of the background-thread to the os.BackgroundFetch.finish();}, (error) => {console.log('- BackgroundFetch failed', error);}, config);});// Start the background-fetch API. Your callbackFn provided to #configure will be executed each time a background-fetch event occurs. NOTE the #configure method automatically calls #start. You do not have to call this method after you #configure the pluginBackgroundFetch.start();// Stop the background-fetch API from firing fetch events. Your callbackFn provided to #configure will no longer be executed.BackgroundFetch.stop();BackgroundFetchConfig
method configure
static configure: ( callbackFn: Function, errorCallback: Function, config: BackgroundFetchConfig) => any;
Configures the plugin's fetch callbackFn
Parameter callbackFn
This callback will fire each time an iOS background-fetch event occurs (typically every 15 min).
Parameter errorCallback
The failureFn will be called if the device doesn't support background-fetch.
Parameter config
Configuration for plugin Location object, which tries to mimic w3c Coordinates interface. See http://dev.w3.org/geo/api/spec-source.html#coordinates_interface Callback to be executed every time a geolocation is recorded in the background.
method finish
static finish: () => void;
You MUST call this method in your fetch callbackFn provided to #configure in order to signal to iOS that your fetch action is complete. iOS provides only 30s of background-time for a fetch-event -- if you exceed this 30s, iOS will kill your app.
method start
static start: () => Promise<any>;
Start the background-fetch API. Your callbackFn provided to #configure will be executed each time a background-fetch event occurs. NOTE the #configure method automatically calls #start. You do not have to call this method after you #configure the plugin
Returns
{Promise}
method stop
static stop: () => Promise<any>;
Stop the background-fetch API from firing fetch events. Your callbackFn provided to #configure will no longer be executed.
Returns
{Promise}
class BackgroundGeolocation
class BackgroundGeolocation {}
BackgroundGeolocation This plugin provides foreground and background geolocation with battery-saving "circular region monitoring" and "stop detection". For more detail, please see https://github.com/mauron85/cordova-plugin-background-geolocation
import { BackgroundGeolocation } from 'ionic-native';// When device is ready :platform.ready().then(() => {// IMPORTANT: BackgroundGeolocation must be called within app.ts and or before Geolocation. Otherwise the platform will not ask you for background tracking permission.// BackgroundGeolocation is highly configurable. See platform specific configuration optionslet config = {desiredAccuracy: 10,stationaryRadius: 20,distanceFilter: 30,debug: true, // enable this hear sounds for background-geolocation life-cycle.stopOnTerminate: false, // enable this to clear background location settings when the app terminates};BackgroundGeolocation.configure((location) => {console.log('[js] BackgroundGeolocation callback: ' + location.latitude + ',' + location.longitude);// IMPORTANT: You must execute the finish method here to inform the native plugin that you're finished,// and the background-task may be completed. You must do this regardless if your HTTP request is successful or not.// IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.BackgroundGeolocation.finish(); // FOR IOS ONLY}, (error) => {console.log('BackgroundGeolocation error');}, config);// Turn ON the background-geolocation system. The user will be tracked whenever they suspend the app.BackgroundGeolocation.start();})// If you wish to turn OFF background-tracking, call the #stop method.BackgroundGeolocation.stop();BackgroundGeolocationResponse BackgroundGeolocationConfig
property Accuracy
static Accuracy: any;
Desired accuracy in meters. Possible values [0, 10, 100, 1000].
The lower the number, the more power devoted to GeoLocation resulting in higher accuracy readings.
1000 results in lowest power drain and least accurate readings.
Possible values: HIGH: 0
MEDIUM: 10
LOW: 100
PASSIVE: 1000
enum {number}
property LocationProvider
static LocationProvider: any;
Set location service provider
See Also
https://github.com/mauron85/cordova-plugin-background-geolocation/wiki/Android-providers
Possible values: ANDROID_DISTANCE_FILTER_PROVIDER: 0,
ANDROID_ACTIVITY_PROVIDER: 1
{number}
property Mode
static Mode: any;
Used in the switchMode function
Possible values: BACKGROUND: 0 FOREGROUND: 1
{number}
method changePace
static changePace: (isMoving: boolean) => Promise<any>;
Force the plugin to enter "moving" or "stationary" state
Parameter isMoving
Returns
{Promise}
method configure
static configure: (options: BackgroundGeolocationConfig) => Observable<any>;
Configure the plugin.
Parameter options
options An object of type Config {Observable}
method deleteAllLocations
static deleteAllLocations: () => Promise<any>;
Delete all stored locations.
Returns
{Promise}
method deleteLocation
static deleteLocation: (locationId: number) => Promise<any>;
Delete stored location by given locationId.
Parameter locationId
Returns
{Promise}
method finish
static finish: () => Promise<any>;
Inform the native plugin that you're finished, the background-task may be completed
Returns
{Promise}
method getLocations
static getLocations: () => Promise<any>;
Method will return all stored locations. Locations are stored when: - config.stopOnTerminate is false and main activity was killed by the system or - option.debug is true
Returns
{Promise}
method getLogEntries
static getLogEntries: (limit: number) => Promise<any>;
Return all logged events. Useful for plugin debugging. Parameter limit limits number of returned entries.
Parameter limit
Limits the number of entries
Returns
{Promise}
See Also
https://github.com/mauron85/cordova-plugin-background-geolocation/tree/v2.2.1#debugging for more information.
method getStationaryLocation
static getStationaryLocation: () => Promise<BackgroundGeolocationResponse>;
Returns current stationaryLocation if available. null if not
Returns
{Promise}
method getValidLocations
static getValidLocations: () => Promise<any>;
Method will return locations, which has not been yet posted to server. NOTE: Locations does contain locationId.
Returns
{Promise}
method isLocationEnabled
static isLocationEnabled: () => Promise<number>;
Check if location is enabled on the device
Returns
{Promise} Returns a promise with int argument that takes values 0, 1 (true).
method onStationary
static onStationary: () => Promise<any>;
Add a stationary-region listener. Whenever the devices enters "stationary-mode", your #success callback will be executed with #location param containing #radius of region
Returns
{Promise}
method setConfig
static setConfig: (options: BackgroundGeolocationConfig) => Promise<any>;
Setup configuration
Parameter options
Returns
{Promise}
method showAppSettings
static showAppSettings: () => void;
Display app settings to change permissions
method showLocationSettings
static showLocationSettings: () => void;
Display device location settings
method start
static start: () => Promise<any>;
Turn ON the background-geolocation system. The user will be tracked whenever they suspend the app.
Returns
{Promise}
method stop
static stop: () => Promise<any>;
Turn OFF background-tracking
Returns
{Promise}
method stopWatchingLocationMode
static stopWatchingLocationMode: () => Promise<any>;
Stop watching for location mode changes.
Returns
{Promise}
method switchMode
static switchMode: (modeId: number) => Promise<any>;
Normally plugin will handle switching between BACKGROUND and FOREGROUND mode itself. Calling switchMode you can override plugin behavior and force plugin to switch into other mode.
In FOREGROUND mode plugin uses iOS local manager to receive locations and behavior is affected by option.desiredAccuracy and option.distanceFilter. In BACKGROUND mode plugin uses significant changes and region monitoring to receive locations and uses option.stationaryRadius only.
BackgroundGeolocation.Mode.FOREGROUND BackgroundGeolocation.Mode.BACKGROUND
*
Parameter modeId
Returns
{Promise}
method watchLocationMode
static watchLocationMode: () => Promise<boolean>;
Method can be used to detect user changes in location services settings. If user enable or disable location services then success callback will be executed. In case or error (SettingNotFoundException) fail callback will be executed.
Returns
{Promise}
class BackgroundMode
class BackgroundMode {}
Background Mode Cordova plugin to prevent the app from going to sleep while in background. Requires Cordova plugin: cordova-plugin-background-mode. For more info about plugin, vist: https://github.com/katzer/cordova-plugin-background-mode
import { BackgroundMode } from 'ionic-native';BackgroundMode.enable();BackgroundModeConfiguration
method configure
static configure: (options?: BackgroundModeConfiguration) => Promise<any>;
Modify the displayed information. Available only for Android platform.
Parameter options
Any options you want to update. See table below.
method disable
static disable: () => Promise<any>;
Disable the background mode. Once the background mode has been disabled, the app will be paused when in background.
method enable
static enable: () => void;
Enable the background mode. Once called, prevents the app from being paused while in background.
method excludeFromTaskList
static excludeFromTaskList: () => void;
Exclude the app from the recent task list works on Android 5.0+.
method isActive
static isActive: () => boolean;
Can be used to get the information if the background mode is active.
Returns
{boolean} returns a boolean that indicates if the background mode is active.
method isEnabled
static isEnabled: () => boolean;
Checks if background mode is enabled or not.
Returns
{boolean} returns a boolean that indicates if the background mode is enabled.
method isScreenOff
static isScreenOff: () => Promise<boolean>;
The method works async instead of isActive() or isEnabled().
method moveToBackground
static moveToBackground: () => void;
Android allows to programmatically move from foreground to background.
method moveToForeground
static moveToForeground: () => void;
Android allows to programmatically move from background to foreground.
method on
static on: (event: string) => Observable<any>;
Listen for events that the plugin fires. Available events are
enable
,disable
,activate
,deactivate
andfailure
.Parameter event
Event name
Returns
{Observable}
method overrideBackButton
static overrideBackButton: () => void;
Override the back button on Android to go to background instead of closing the app.
method setDefaults
static setDefaults: (options?: BackgroundModeConfiguration) => Promise<any>;
Override the default title, ticker and text. Available only for Android platform.
Parameter options
List of option to configure. See table below
method unlock
static unlock: () => void;
Turn screen on and show app even locked
method wakeUp
static wakeUp: () => void;
Turn screen on
class Backlight
class Backlight {}
Backlight This plugin adds turning on/off the device backlight.
import { Backlight } from 'ionic-native';// Turn backlight onBacklight.on().then(() => console.log('backlight on'));// Turn backlight offBacklight.off().then(() => console.log('backlight off'));Modifiers
@beta
class Badge
class Badge {}
Badge The essential purpose of badge numbers is to enable an application to inform its users that it has something for them — for example, unread messages — when the application isn’t running in the foreground.
Requires Cordova plugin: cordova-plugin-badge. For more info, please see the [Badge plugin docs](https://github.com/katzer/cordova-plugin-badge).
import { Badge } from 'ionic-native';Badge.set(10);Badge.increase(1);Badge.clear();
method clear
static clear: () => Promise<boolean>;
Clear the badge of the app icon.
Returns
{Promise}
method decrease
static decrease: (decreaseBy: number) => Promise<any>;
Decrease the badge number.
Parameter decreaseBy
Count to subtract from the current badge number
Returns
{Promise}
method get
static get: () => Promise<any>;
Get the badge of the app icon.
Returns
{Promise}
method hasPermission
static hasPermission: () => Promise<any>;
Determine if the app has permission to show badges.
Returns
{Promise}
method increase
static increase: (increaseBy: number) => Promise<any>;
Increase the badge number.
Parameter increaseBy
Count to add to the current badge number
Returns
{Promise}
method registerPermission
static registerPermission: () => Promise<any>;
Register permission to set badge notifications
Returns
{Promise}
method set
static set: (badgeNumber: number) => Promise<any>;
Set the badge of the app icon.
Parameter badgeNumber
The new badge number.
Returns
{Promise}
class BarcodeScanner
class BarcodeScanner {}
Barcode Scanner The Barcode Scanner Plugin opens a camera view and automatically scans a barcode, returning the data back to you.
Requires Cordova plugin:
phonegap-plugin-barcodescanner
. For more info, please see the [BarcodeScanner plugin docs](https://github.com/phonegap/phonegap-plugin-barcodescanner).import { BarcodeScanner } from 'ionic-native';BarcodeScanner.scan().then((barcodeData) => {// Success! Barcode data is here}, (err) => {// An error occurred});BarcodeScannerOptions
property Encode
static Encode: any;
method encode
static encode: (type: string, data: any) => Promise<any>;
Encodes data into a barcode. NOTE: not well supported on Android
Parameter type
Type of encoding
Parameter data
Data to encode
Returns
{Promise}
method scan
static scan: (options?: BarcodeScannerOptions) => Promise<any>;
Open the barcode scanner.
Parameter options
Optional options to pass to the scanner
Returns
{Promise} Returns a Promise that resolves with scanner data, or rejects with an error.
class Base64ToGallery
class Base64ToGallery {}
Base64 To Gallery This plugin allows you to save base64 data as a png image into the device
import { Base64ToGallery } from 'ionic-native';Base64ToGallery.base64ToGallery(base64Data, 'img_').then(res => console.log('Saved image to gallery ', res),err => console.log('Error saving image to gallery ', err));
method base64ToGallery
static base64ToGallery: ( data: string, options?: { prefix?: string; mediaScanner?: boolean }) => Promise<any>;
Converts a base64 string to an image file in the device gallery
Parameter data
The actual base64 string that you want to save
Parameter options
(optional) An object with properties: prefix: string, mediaScanner: boolean. Prefix will be prepended to the filename. If true, mediaScanner runs Media Scanner on Android and saves to Camera Roll on iOS; if false, saves to Library folder on iOS.
Returns
{Promise} returns a promise that resolves when the image is saved.
class BatteryStatus
class BatteryStatus {}
Battery Status Requires Cordova plugin: cordova-plugin-batterystatus. For more info, please see the [BatteryStatus plugin docs](https://github.com/apache/cordova-plugin-battery-status).
import { BatteryStatus } from 'ionic-native';// watch change in battery statuslet subscription = BatteryStatus.onChange().subscribe((status: StatusObject) => {console.log(status.level, status.isPlugged);});// stop watchsubscription.unsubscribe();BatteryStatusResponse
method onChange
static onChange: () => Observable<BatteryStatusResponse>;
Watch the change in battery level
Returns
{Observable} Returns an observable that pushes a status object
method onCritical
static onCritical: () => Observable<BatteryStatusResponse>;
Watch when the battery level goes to critial
Returns
{Observable} Returns an observable that pushes a status object
method onLow
static onLow: () => Observable<BatteryStatusResponse>;
Watch when the battery level goes low
Returns
{Observable} Returns an observable that pushes a status object
class BLE
class BLE {}
BLE This plugin enables communication between a phone and Bluetooth Low Energy (BLE) peripherals.
The plugin provides a simple JavaScript API for iOS and Android.
- Scan for peripherals - Connect to a peripheral - Read the value of a characteristic - Write new value to a characteristic - Get notified when characteristic's value changes
Advertising information is returned when scanning for peripherals. Service, characteristic, and property info is returned when connecting to a peripheral. All access is via service and characteristic UUIDs. The plugin manages handles internally.
Simultaneous connections to multiple peripherals are supported.
## Peripheral Data
Peripheral Data is passed to the success callback when scanning and connecting. Limited data is passed when scanning.
{"name": "Battery Demo","id": "20:FF:D0:FF:D1:C0","advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121],"rssi": -55}After connecting, the peripheral object also includes service, characteristic and descriptor information.
{"name": "Battery Demo","id": "20:FF:D0:FF:D1:C0","advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121],"rssi": -55,"services": ["1800","1801","180f"],"characteristics": [{"service": "1800","characteristic": "2a00","properties": ["Read"]},{"service": "1800","characteristic": "2a01","properties": ["Read"]},{"service": "1801","characteristic": "2a05","properties": ["Read"]},{"service": "180f","characteristic": "2a19","properties": ["Read"],"descriptors": [{"uuid": "2901"},{"uuid": "2904"}]}]}## Advertising Data Bluetooth advertising data is returned in when scanning for devices. The format format varies depending on your platform. On Android advertising data will be the raw advertising bytes. iOS does not allow access to raw advertising data, so a dictionary of data is returned.
The advertising information for both Android and iOS appears to be a combination of advertising data and scan response data.
### Android
{"name": "demo","id": "00:1A:7D:DA:71:13","advertising": ArrayBuffer,"rssi": -37}Convert the advertising info to a Uint8Array for processing.
var adData = new Uint8Array(peripheral.advertising)
### iOS
Note that iOS uses the string value of the constants for the [Advertisement Data Retrieval Keys](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManagerDelegate_Protocol/index.html#//apple_ref/doc/constant_group/Advertisement_Data_Retrieval_Keys). This will likely change in the future.
{"name": "demo","id": "D8479A4F-7517-BCD3-91B5-3302B2F81802","advertising": {"kCBAdvDataChannel": 37,"kCBAdvDataServiceData": {"FED8": {"byteLength": 7 // data not shown}},"kCBAdvDataLocalName": "demo","kCBAdvDataServiceUUIDs": ["FED8"],"kCBAdvDataManufacturerData": {"byteLength": 7 // data not shown},"kCBAdvDataTxPowerLevel": 32,"kCBAdvDataIsConnectable": true},"rssi": -53}## Typed Arrays
This plugin uses typed Arrays or ArrayBuffers for sending and receiving data.
This means that you need convert your data to ArrayBuffers before sending and from ArrayBuffers when receiving.
// ASCII onlyfunction stringToBytes(string) {var array = new Uint8Array(string.length);for (var i = 0, l = string.length; i < l; i++) {array[i] = string.charCodeAt(i);}return array.buffer;}// ASCII onlyfunction bytesToString(buffer) {return String.fromCharCode.apply(null, new Uint8Array(buffer));}You can read more about typed arrays in these articles on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) and [HTML5 Rocks](http://www.html5rocks.com/en/tutorials/webgl/typed_arrays/).
## UUIDs
UUIDs are always strings and not numbers. Some 16-bit UUIDs, such as '2220' look like integers, but they're not. (The integer 2220 is 0x8AC in hex.) This isn't a problem with 128 bit UUIDs since they look like strings 82b9e6e1-593a-456f-be9b-9215160ebcac. All 16-bit UUIDs should also be passed to methods as strings.
method connect
static connect: (deviceId: string) => Observable<any>;
Connect to a peripheral.
BLE.connect('12:34:56:78:9A:BC').subscribe(peripheralData => {console.log(peripheralData);},peripheralData => {console.log('disconnected');});Parameter deviceId
UUID or MAC address of the peripheral Returns an Observable that notifies of connect/disconnect.
method disconnect
static disconnect: (deviceId: string) => Promise<any>;
Disconnect from a peripheral.
BLE.disconnect('12:34:56:78:9A:BC').then(() => {console.log('Disconnected');});Parameter deviceId
UUID or MAC address of the peripheral Returns a Promise
method enable
static enable: () => Promise<any>;
Enable Bluetooth on the device (Android only).
Returns
{Promise}
method isConnected
static isConnected: (deviceId: string) => Promise<any>;
Report the connection status.
BLE.isConnected('FFCA0B09-CB1D-4DC0-A1EF-31AFD3EDFB53').then(() => { console.log('connected'); },() => { console.log('not connected'); });Parameter deviceId
UUID or MAC address of the peripheral
Returns
{Promise}
method isEnabled
static isEnabled: () => Promise<void>;
Report if bluetooth is enabled.
Returns
{Promise} Returns a Promise that resolves if Bluetooth is enabled, and rejects if disabled.
method read
static read: ( deviceId: string, serviceUUID: string, characteristicUUID: string) => Promise<any>;
Read the value of a characteristic.
Parameter deviceId
UUID or MAC address of the peripheral
Parameter serviceUUID
UUID of the BLE service
Parameter characteristicUUID
UUID of the BLE characteristic Returns a Promise
method scan
static scan: (services: string[], seconds: number) => Observable<any>;
Scan and discover BLE peripherals for the specified amount of time.
BLE.scan([], 5).subscribe(device => {console.log(JSON.stringify(device));});Parameter services
List of service UUIDs to discover, or
[]
to find all devicesParameter seconds
Number of seconds to run discovery
Returns
{Observable} Returns an Observable that notifies of each peripheral that is discovered during the specified time.
method showBluetoothSettings
static showBluetoothSettings: () => Promise<any>;
Open System Bluetooth settings (Android only).
Returns
{Promise}
method startNotification
static startNotification: ( deviceId: string, serviceUUID: string, characteristicUUID: string) => Observable<any>;
Register to be notified when the value of a characteristic changes.
BLE.startNotification(device_id, "FF10", "FF11").subscribe(buffer => {console.log(String.fromCharCode.apply(null, new Uint8Array(buffer));});Parameter deviceId
UUID or MAC address of the peripheral
Parameter serviceUUID
UUID of the BLE service
Parameter characteristicUUID
UUID of the BLE characteristic Returns an Observable that notifies of characteristic changes.
method startScan
static startScan: (services: string[]) => Observable<any>;
Scan and discover BLE peripherals until
stopScan
is called.BLE.startScan([]).subscribe(device => {console.log(JSON.stringify(device));});setTimeout(() => {BLE.stopScan();}, 5000);Parameter services
List of service UUIDs to discover, or
[]
to find all devicesReturns
{Observable} Returns an Observable that notifies of each peripheral discovered.
method startScanWithOptions
static startScanWithOptions: ( services: string[], options: { reportDuplicates?: boolean } | any) => Observable<any>;
Scans for BLE devices. This function operates similarly to the
startScan
function, but allows you to specify extra options (like allowing duplicate device reports).Parameter services
List of service UUIDs to discover, or
[]
to find all devicesParameter options
Returns
{Observable} Returns an Observable that notifies of each peripheral discovered.
method stopNotification
static stopNotification: ( deviceId: string, serviceUUID: string, characteristicUUID: string) => Promise<any>;
Stop being notified when the value of a characteristic changes.
Parameter deviceId
UUID or MAC address of the peripheral
Parameter serviceUUID
UUID of the BLE service
Parameter characteristicUUID
UUID of the BLE characteristic
Returns
{Promise}
method stopScan
static stopScan: () => Promise<any>;
Stop a scan started by
startScan
.BLE.startScan([]).subscribe(device => {console.log(JSON.stringify(device));});setTimeout(() => {BLE.stopScan().then(() => { console.log('scan stopped'); });}, 5000);returns a Promise.
method write
static write: ( deviceId: string, serviceUUID: string, characteristicUUID: string, value: ArrayBuffer) => Promise<any>;
Write the value of a characteristic.
// send 1 byte to switch a light onvar data = new Uint8Array(1);data[0] = 1;BLE.write(device_id, "FF10", "FF11", data.buffer);// send a 3 byte value with RGB colorvar data = new Uint8Array(3);data[0] = 0xFF; // reddata[0] = 0x00; // greendata[0] = 0xFF; // blueBLE.write(device_id, "ccc0", "ccc1", data.buffer);// send a 32 bit integervar data = new Uint32Array(1);data[0] = counterInput.value;BLE.write(device_id, SERVICE, CHARACTERISTIC, data.buffer);Parameter deviceId
UUID or MAC address of the peripheral
Parameter serviceUUID
UUID of the BLE service
Parameter characteristicUUID
UUID of the BLE characteristic
Parameter value
Data to write to the characteristic, as an ArrayBuffer. Returns a Promise
method writeWithoutResponse
static writeWithoutResponse: ( deviceId: string, serviceUUID: string, characteristicUUID: string, value: ArrayBuffer) => Promise<any>;
Write the value of a characteristic without waiting for confirmation from the peripheral.
Parameter deviceId
UUID or MAC address of the peripheral
Parameter serviceUUID
UUID of the BLE service
Parameter characteristicUUID
UUID of the BLE characteristic
Parameter value
Data to write to the characteristic, as an ArrayBuffer. Returns a Promise
class BluetoothSerial
class BluetoothSerial {}
Bluetooth Serial This plugin enables serial communication over Bluetooth. It was written for communicating between Android or iOS and an Arduino.
import { BluetoothSerial } from 'ionic-native';// Write a stringBluetoothSerial.write("hello world").then(success, failure);// Array of int or bytesBluetoothSerial.write([186, 220, 222]).then(success, failure);// Typed Arrayvar data = new Uint8Array(4);data[0] = 0x41;data[1] = 0x42;data[2] = 0x43;data[3] = 0x44;BluetoothSerial.write(data).then(success, failure);// Array BufferBluetoothSerial.write(data.buffer).then(success, failure);
method available
static available: () => Promise<any>;
Gets the number of bytes of data available
Returns
{Promise} returns a promise that contains the available bytes
method clear
static clear: () => Promise<any>;
Clears data in buffer
Returns
{Promise} returns a promise when completed
method connect
static connect: (macAddress_or_uuid: string) => Observable<any>;
Connect to a Bluetooth device
Parameter macAddress_or_uuid
Identifier of the remote device
Returns
{Observable} Subscribe to connect, unsubscribe to disconnect.
method connectInsecure
static connectInsecure: (macAddress: string) => Observable<any>;
Connect insecurely to a Bluetooth device
Parameter macAddress
Identifier of the remote device
Returns
{Observable} Subscribe to connect, unsubscribe to disconnect.
method disconnect
static disconnect: () => Promise<any>;
Disconnect from the connected device
Returns
{Promise}
method discoverUnpaired
static discoverUnpaired: () => Promise<any>;
Discover unpaired devices
Returns
{Promise} returns a promise
method enable
static enable: () => Promise<any>;
Enable Bluetooth on the device
Returns
{Promise} returns a promise
method isConnected
static isConnected: () => Promise<any>;
Reports the connection status
Returns
{Promise} returns a promise
method isEnabled
static isEnabled: () => Promise<any>;
Reports if bluetooth is enabled
Returns
{Promise} returns a promise
method list
static list: () => Promise<any>;
Lists bonded devices
Returns
{Promise} returns a promise
method read
static read: () => Promise<any>;
Reads data from the buffer
Returns
{Promise} returns a promise with data from the buffer
method readRSSI
static readRSSI: () => Promise<any>;
Reads the RSSI from the connected peripheral
Returns
{Promise} returns a promise
method readUntil
static readUntil: (delimiter: string) => Promise<any>;
Reads data from the buffer until it reaches a delimiter
Parameter delimiter
string that you want to search until
Returns
{Promise} returns a promise
method setDeviceDiscoveredListener
static setDeviceDiscoveredListener: () => Observable<any>;
Subscribe to be notified on Bluetooth device discovery. Discovery process must be initiated with the
discoverUnpaired
function.Returns
{Observable} Returns an observable
method setDiscoverable
static setDiscoverable: (discoverableDuration: number) => void;
Makes the device discoverable by other devices
Parameter discoverableDuration
Desired number of seconds device should be discoverable for
method setName
static setName: (newName: string) => void;
Sets the human readable device name that is broadcasted to other devices
Parameter newName
Desired name of device
method showBluetoothSettings
static showBluetoothSettings: () => Promise<any>;
Show the Bluetooth settings on the device
Returns
{Promise} returns a promise
method subscribe
static subscribe: (delimiter: string) => Observable<any>;
Subscribe to be notified when data is received
Parameter delimiter
the string you want to watch for
Returns
{Observable} returns an observable.
method subscribeRawData
static subscribeRawData: () => Observable<any>;
Subscribe to be notified when data is received
Returns
{Observable} returns an observable
method write
static write: (data: any) => Promise<any>;
Writes data to the serial port
Parameter data
ArrayBuffer of data
Returns
{Promise} returns a promise when data has been written
class Brightness
class Brightness {}
Brightness The Brightness plugin let you control the display brightness of your device.
Requires Cordova plugin:
cordova-plugin-brightness
. For more info, please see the [Brightness plugin docs](https://github.com/mgcrea/cordova-plugin-brightness).import { Brightness } from 'ionic-native';let brightnessValue: number = 0.8;Brightness.setBrightness(brightnessValue);
method getBrightness
static getBrightness: () => Promise<any>;
Reads the current brightness of the device display.
Returns
{Promise} Returns a Promise that resolves with the brightness value of the device display (floating number between 0 and 1).
method setBrightness
static setBrightness: (value: number) => Promise<any>;
Sets the brightness of the display.
Parameter Floating
number between 0 and 1 in which case 1 means 100% brightness and 0 means 0% brightness.
Returns
{Promise} Returns a Promise that resolves if setting brightness was successful.
method setKeepScreenOn
static setKeepScreenOn: (value: boolean) => void;
Keeps the screen on. Prevents the device from setting the screen to sleep.
class Broadcaster
class Broadcaster {}
Broadcaster This plugin adds exchanging events between native code and your app.
import { Broadcaster } from 'ionic-native';// Listen to events from NativeBroadcaster.addEventListener('eventName').then((event) => console.log(event));// Send event to NativeBroadcaster.fireNativeEvent('eventName', {}).then(() => console.log('success'));
method addEventListener
static addEventListener: (eventName: string) => Observable<any>;
This function listen to an event sent from the native code
Parameter eventName
{Observable} Returns an observable to watch when an event is received
method fireNativeEvent
static fireNativeEvent: (eventName: string, eventData: any) => Promise<any>;
This function sends data to the native code
Parameter eventName
Parameter eventData
{Promise} Returns a promise that resolves when an event is successfully fired
class BrowserTab
class BrowserTab {}
BrowserTab This plugin provides an interface to in-app browser tabs that exist on some mobile platforms, specifically [Custom Tabs](http://developer.android.com/tools/support-library/features.html#custom-tabs) on Android (including the [Chrome Custom Tabs](https://developer.chrome.com/multidevice/android/customtabs) implementation), and [SFSafariViewController](https://developer.apple.com/library/ios/documentation/SafariServices/Reference/SFSafariViewController_Ref/) on iOS.
import { BrowserTab } from 'ionic-native';BrowserTab.isAvailable().then((isAvailable: boolean) => {if (isAvailable) {BrowserTab.openUrl('https://ionic.io');} else {// open url with InAppBrowser instead}});
method close
static close: () => Promise<any>;
Closes browser tab {Promise} Returns a promise that resolves when close was finished
method isAvailable
static isAvailable: () => Promise<any>;
Check if BrowserTab option is available {Promise} Returns a promise that resolves when check is successful and returns true or false
method openUrl
static openUrl: (url: string) => Promise<any>;
Opens the provided URL using a browser tab
Parameter url
The URL you want to open {Promise} Returns a promise that resolves when check open was successful
class Calendar
class Calendar {}
Calendar This plugin allows you to add events to the Calendar of the mobile device.
Requires Cordova plugin:
cordova-plugin-calendar
. For more info, please see the [Calendar plugin docs](https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin).import {Calendar} from 'ionic-native';Calendar.createCalendar('MyCalendar').then((msg) => { console.log(msg); },(err) => { console.log(err); });CalendarOptions
method createCalendar
static createCalendar: (nameOrOptions: string | any) => Promise<any>;
Create a calendar. (iOS only)
Parameter nameOrOptions
either a string name or a options object. If string, provide the calendar name. IF an object, provide a calendar name as a string and a calendar color in hex format as a string
Returns
{Promise} Returns a Promise
method createEvent
static createEvent: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date) => Promise<any>;
Silently create an event.
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date
Returns
{Promise} Returns a Promise
method createEventInteractively
static createEventInteractively: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date) => Promise<any>;
Interactively create an event.
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date
Returns
{Promise} Returns a Promise
method createEventInteractivelyWithOptions
static createEventInteractivelyWithOptions: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date, options?: CalendarOptions) => Promise<any>;
Interactively create an event with additional options.
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date
Parameter options
Additional options, see
getCalendarOptions
Returns
{Promise}
method createEventWithOptions
static createEventWithOptions: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date, options?: CalendarOptions) => Promise<any>;
Silently create an event with additional options.
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date
Parameter options
Additional options, see
getCalendarOptions
Returns
{Promise} Returns a Promise
method deleteCalendar
static deleteCalendar: (name: string) => Promise<any>;
Delete a calendar. (iOS only)
Parameter name
Name of the calendar to delete.
Returns
{Promise} Returns a Promise
method deleteEvent
static deleteEvent: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date) => Promise<any>;
Delete an event.
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date Returns a Promise
method deleteEventFromNamedCalendar
static deleteEventFromNamedCalendar: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date, calendarName?: string) => Promise<any>;
Delete an event from the specified Calendar. (iOS only)
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date
Parameter calendarName
Returns a Promise
method findAllEventsInNamedCalendar
static findAllEventsInNamedCalendar: (calendarName: string) => Promise<any>;
Get a list of all future events in the specified calendar. (iOS only)
Returns
{Promise} Returns a Promise that resolves with the list of events, or rejects with an error.
method findEvent
static findEvent: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date) => Promise<any>;
Find an event.
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date
Returns
{Promise}
method findEventWithOptions
static findEventWithOptions: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date, options?: CalendarOptions) => Promise<any>;
Find an event with additional options.
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date
Parameter options
Additional options, see
getCalendarOptions
Returns
{Promise} Returns a Promise that resolves with the event, or rejects with an error.
method getCalendarOptions
static getCalendarOptions: () => CalendarOptions;
Returns the default calendar options.
{CalendarOptions} Returns an object with the default calendar options
method hasReadPermission
static hasReadPermission: () => Promise<boolean>;
Check if we have read permission
Returns
{Promise}
method hasReadWritePermission
static hasReadWritePermission: () => Promise<boolean>;
This function checks if we have permission to read/write from/to the calendar. The promise will resolve with
true
when: - You're running on iOS, or - You're targetting API level lower than 23, or - You're using Android < 6, or - You've already granted permissionIf this returns false, you should call the
requestReadWritePermission
functionReturns
{Promise}
method hasWritePermission
static hasWritePermission: () => Promise<boolean>;
Check if we have write permission
Returns
{Promise}
method listCalendars
static listCalendars: () => Promise<any>;
Get a list of all calendars.
Returns
{Promise} A Promise that resolves with the list of calendars, or rejects with an error.
method listEventsInRange
static listEventsInRange: (startDate: Date, endDate: Date) => Promise<any>;
Find a list of events within the specified date range. (Android only)
Parameter startDate
The start date
Parameter endDate
The end date
Returns
{Promise} Returns a Promise that resolves with the list of events, or rejects with an error.
method modifyEvent
static modifyEvent: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date, newTitle?: string, newLocation?: string, newNotes?: string, newStartDate?: Date, newEndDate?: Date) => Promise<any>;
Modify an event. (iOS only)
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date
Parameter newTitle
The new event title
Parameter newLocation
The new event location
Parameter newNotes
The new event notes
Parameter newStartDate
The new event start date
Parameter newEndDate
The new event end date Returns a Promise
method modifyEventWithOptions
static modifyEventWithOptions: ( title?: string, location?: string, notes?: string, startDate?: Date, endDate?: Date, newTitle?: string, newLocation?: string, newNotes?: string, newStartDate?: Date, newEndDate?: Date, filterOptions?: CalendarOptions, newOptions?: CalendarOptions) => Promise<any>;
Modify an event with additional options. (iOS only)
Parameter title
The event title
Parameter location
The event location
Parameter notes
The event notes
Parameter startDate
The event start date
Parameter endDate
The event end date
Parameter newTitle
The new event title
Parameter newLocation
The new event location
Parameter newNotes
The new event notes
Parameter newStartDate
The new event start date
Parameter newEndDate
The new event end date
Parameter filterOptions
Event Options, see
getCalendarOptions
Parameter newOptions
New event options, see
getCalendarOptions
Returns a Promise
method openCalendar
static openCalendar: (date: Date) => Promise<any>;
Open the calendar at the specified date.
Parameter date
The date you want to open the calendar on {Promise} Promise returns a promise
method requestReadPermission
static requestReadPermission: () => Promise<any>;
Request read permission
Returns
{Promise}
method requestReadWritePermission
static requestReadWritePermission: () => Promise<any>;
Requests read/write permissions
Returns
{Promise}
method requestWritePermission
static requestWritePermission: () => Promise<any>;
Request write permission
Returns
{Promise}
class CallNumber
class CallNumber {}
CallNumber Call a number directly from your Cordova/Ionic application.
import {CallNumber} from 'ionic-native';CallNumber.callNumber(18001010101, true).then(() => console.log('Launched dialer!')).catch(() => console.log('Error launching dialer'));
method callNumber
static callNumber: ( numberToCall: string, bypassAppChooser: boolean) => Promise<any>;
Calls a phone number
Parameter numberToCall
The phone number to call as a string
Parameter bypassAppChooser
Set to true to bypass the app chooser and go directly to dialer {Promise}
class Camera
class Camera {}
Camera Take a photo or capture video.
Requires and the Cordova plugin:
cordova-plugin-camera
. For more info, please see the [Cordova Camera Plugin Docs](https://github.com/apache/cordova-plugin-camera).import { Camera } from 'ionic-native';Camera.getPicture(options).then((imageData) => {// imageData is either a base64 encoded string or a file URI// If it's base64:let base64Image = 'data:image/jpeg;base64,' + imageData;}, (err) => {// Handle error});CameraOptions CameraPopoverOptions
property DestinationType
static DestinationType: { DATA_URL: number; FILE_URI: number; NATIVE_URI: number;};
{number}
property Direction
static Direction: { BACK: number; FRONT: number };
{number}
property EncodingType
static EncodingType: { JPEG: number; PNG: number };
{number}
property MediaType
static MediaType: { PICTURE: number; VIDEO: number; ALLMEDIA: number };
{number}
property PictureSourceType
static PictureSourceType: { PHOTOLIBRARY: number; CAMERA: number; SAVEDPHOTOALBUM: number;};
{number}
property PopoverArrowDirection
static PopoverArrowDirection: { ARROW_UP: number; ARROW_DOWN: number; ARROW_LEFT: number; ARROW_RIGHT: number; ARROW_ANY: number;};
Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover. {number}
method cleanup
static cleanup: () => Promise<any>;
Remove intermediate image files that are kept in temporary storage after calling camera.getPicture. Applies only when the value of Camera.sourceType equals Camera.PictureSourceType.CAMERA and the Camera.destinationType equals Camera.DestinationType.FILE_URI.
Returns
{Promise}
method getPicture
static getPicture: (options?: CameraOptions) => Promise<any>;
Take a picture or video, or load one from the library.
Parameter options
optional. Options that you want to pass to the camera. Encoding type, quality, etc. Platform-specific quirks are described in the [Cordova plugin docs](https://github.com/apache/cordova-plugin-camera#cameraoptions-errata-).
Returns
{Promise} Returns a Promise that resolves with Base64 encoding of the image data, or the image file URI, depending on cameraOptions, otherwise rejects with an error.
class CameraPreview
class CameraPreview {}
CameraPreview Showing camera preview in HTML
For more info, please see the [Cordova Camera Preview Plugin Docs](https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview).
import { CameraPreview, CameraPreviewRect } from 'ionic-native';// camera options (Size and location)let cameraRect: CameraPreviewRect = {x: 100,y: 100,width: 200,height: 200};// start cameraCameraPreview.startCamera(cameraRect, // position and size of preview'front', // default cameratrue, // tap to take picturefalse, // disable dragfalse, // keep preview in front. Set to true (back of the screen) to apply overlaying elements1 // set the preview alpha);// Set the handler to run every time we take a pictureCameraPreview.setOnPictureTakenHandler().subscribe((result) => {console.log(result);// do something with the result});// take a pictureCameraPreview.takePicture({maxWidth: 640,maxHeight: 640});// Switch cameraCameraPreview.switchCamera();// set color effect to negativeCameraPreview.setColorEffect('negative');// Stop the camera previewCameraPreview.stopCamera();CameraPreviewRect CameraPreviewSize
Modifiers
@beta
method disable
static disable: () => void;
Disables the camera preview
method hide
static hide: () => void;
Hide the camera preview box.
method setColorEffect
static setColorEffect: (effect: string) => void;
Set camera color effect.
method setOnPictureTakenHandler
static setOnPictureTakenHandler: () => Observable<any>;
Register a callback function that receives the original picture and the image captured from the preview box.
Returns
{Observable}
method show
static show: () => void;
Show the camera preview box.
method startCamera
static startCamera: ( rect: CameraPreviewRect, defaultCamera: string, tapEnabled: boolean, dragEnabled: boolean, toBack: boolean, alpha: number) => void;
Starts the camera preview instance.
Parameter position
and size of the preview window - {x: number, y: number, width: number, height: number}
Parameter which
camera to use - 'front' | 'back'
Parameter enable
tap to take picture
Parameter enable
preview box drag across the screen
Parameter send
preview box to the back of the webview
Parameter alpha
of the preview box
method stopCamera
static stopCamera: () => void;
Stops the camera preview instance.
method switchCamera
static switchCamera: () => void;
Switch from the rear camera and front camera, if available.
method takePicture
static takePicture: (size?: CameraPreviewSize) => void;
Take the picture, the parameter size is optional
Parameter optional
size of the picture to take
class CardIO
class CardIO {}
CardIO
import { CardIO } from 'ionic-native';CardIO.canScan().then((res: boolean) => {if(res){let options = {requireExpiry: true,requireCCV: false,requirePostalCode: false};CardIO.scan(options);}});CardIOOptions CardIOResponse
method canScan
static canScan: () => Promise<boolean>;
Check whether card scanning is currently available. (May vary by device, OS version, network connectivity, etc.)
Returns
{Promise}
method scan
static scan: (options?: CardIOOptions) => Promise<CardIOResponse>;
Scan a credit card with card.io.
Parameter options
Options for configuring the plugin
Returns
{Promise}
method version
static version: () => Promise<string>;
Retrieve the version of the card.io library. Useful when contacting support.
Returns
{Promise}
class Clipboard
class Clipboard {}
Clipboard Clipboard management plugin for Cordova that supports iOS, Android, and Windows Phone 8.
Requires Cordova plugin: https://github.com/VersoSolutions/CordovaClipboard For more info, please see the [Clipboard plugin docs](https://github.com/VersoSolutions/CordovaClipboard.git).
import { Clipboard } from 'ionic-native';Clipboard.copy('Hello world');Clipboard.paste().then((resolve: string) => {alert(resolve);},(reject: string) => {alert('Error: ' + reject);}););
method copy
static copy: (text: string) => Promise<any>;
Copies the given text
Parameter text
Text that gets copied on the system clipboard
Returns
{Promise} Returns a promise after the text has been copied
method paste
static paste: () => Promise<any>;
Pastes the text stored in clipboard
Returns
{Promise} Returns a promise after the text has been pasted
class CodePush
class CodePush {}
CodePush CodePush plugin for Cordova by Microsoft that supports iOS and Android.
For more info, please see https://github.com/ksachdeva/ionic2-code-push-example
import { CodePush } from 'ionic-native';// note - mostly error & completed methods of observable will not fire// as syncStatus will contain the current state of the updateCodePush.sync().subscribe((syncStatus) => console.log(syncStatus));const downloadProgress = (progress) => { console.log(`Downloaded ${progress.receivedBytes} of ${progress.totalBytes}`); }CodePush.sync({}, downloadProgress).subscribe((syncStatus) => console.log(syncStatus));
method checkForUpdate
static checkForUpdate: (deploymentKey?: string) => Promise<IRemotePackage>;
Checks with the CodePush server if an update package is available for download.
Parameter querySuccess
Callback invoked in case of a successful response from the server. The callback takes one RemotePackage parameter. A non-null package is a valid update. A null package means the application is up to date for the current native application version.
Parameter queryError
Optional callback invoked in case of an error.
Parameter deploymentKey
Optional deployment key that overrides the config.xml setting.
Returns
{Promise}
method getCurrentPackage
static getCurrentPackage: () => Promise<ILocalPackage>;
Get the current package information.
Parameter packageSuccess
Callback invoked with the currently deployed package information.
Parameter packageError
Optional callback invoked in case of an error.
Returns
{Promise}
method getPendingPackage
static getPendingPackage: () => Promise<ILocalPackage>;
Gets the pending package information, if any. A pending package is one that has been installed but the application still runs the old code. This happends only after a package has been installed using ON_NEXT_RESTART or ON_NEXT_RESUME mode, but the application was not restarted/resumed yet.
Returns
{Promise}
method notifyApplicationReady
static notifyApplicationReady: () => Promise<void>;
Notifies the plugin that the update operation succeeded and that the application is ready. Calling this function is required on the first run after an update. On every subsequent application run, calling this function is a noop. If using sync API, calling this function is not required since sync calls it internally.
Parameter notifySucceeded
Optional callback invoked if the plugin was successfully notified.
Parameter notifyFailed
Optional callback invoked in case of an error during notifying the plugin.
Returns
{Promise}
method restartApplication
static restartApplication: () => Promise<void>;
Reloads the application. If there is a pending update package installed using ON_NEXT_RESTART or ON_NEXT_RESUME modes, the update will be immediately visible to the user. Otherwise, calling this function will simply reload the current version of the application.
Returns
{Promise}
method sync
static sync: ( syncOptions?: SyncOptions, downloadProgress?: SuccessCallback<DownloadProgress>) => Observable<SyncStatus>;
Convenience method for installing updates in one method call. This method is provided for simplicity, and its behavior can be replicated by using window.codePush.checkForUpdate(), RemotePackage's download() and LocalPackage's install() methods.
The algorithm of this method is the following: - Checks for an update on the CodePush server. - If an update is available - If the update is mandatory and the alertMessage is set in options, the user will be informed that the application will be updated to the latest version. The update package will then be downloaded and applied. - If the update is not mandatory and the confirmMessage is set in options, the user will be asked if they want to update to the latest version. If they decline, the syncCallback will be invoked with SyncStatus.UPDATE_IGNORED. - Otherwise, the update package will be downloaded and applied with no user interaction. - If no update is available on the server, or if a previously rolled back update is available and the ignoreFailedUpdates is set to true, the syncCallback will be invoked with the SyncStatus.UP_TO_DATE. - If an error occurs during checking for update, downloading or installing it, the syncCallback will be invoked with the SyncStatus.ERROR.
Parameter syncCallback
Optional callback to be called with the status of the sync operation.
Parameter syncOptions
Optional SyncOptions parameter configuring the behavior of the sync operation.
Parameter downloadProgress
Optional callback invoked during the download process. It is called several times with one DownloadProgress parameter.
Returns
{Observable}
class Contact
class Contact implements IContactProperties {}
constructor
constructor();
property addresses
addresses: IContactAddress[];
property birthday
birthday: Date;
property categories
categories: IContactField[];
property displayName
displayName: string;
property emails
emails: IContactField[];
property id
id: string;
property ims
ims: IContactField[];
property name
name: IContactName;
property nickname
nickname: string;
property note
note: string;
property organizations
organizations: IContactOrganization[];
property phoneNumbers
phoneNumbers: IContactField[];
property photos
photos: IContactField[];
property urls
urls: IContactField[];
method clone
clone: () => Contact;
method remove
remove: () => Promise<any>;
method save
save: () => Promise<any>;
class ContactAddress
class ContactAddress implements IContactAddress {}
constructor
constructor( pref?: boolean, type?: string, formatted?: string, streetAddress?: string, locality?: string, region?: string, postalCode?: string, country?: string);
property country
country: string;
property formatted
formatted: string;
property locality
locality: string;
property postalCode
postalCode: string;
property pref
pref: boolean;
property region
region: string;
property streetAddress
streetAddress: string;
property type
type: string;
class ContactField
class ContactField implements IContactField {}
constructor
constructor(type?: string, value?: string, pref?: boolean);
property pref
pref: boolean;
property type
type: string;
property value
value: string;
class ContactFindOptions
class ContactFindOptions implements IContactFindOptions {}
constructor
constructor( filter?: string, multiple?: boolean, desiredFields?: string[], hasPhoneNumber?: boolean);
property desiredFields
desiredFields: string[];
property filter
filter: string;
property hasPhoneNumber
hasPhoneNumber: boolean;
property multiple
multiple: boolean;
class ContactName
class ContactName implements IContactName {}
constructor
constructor( formatted?: string, familyName?: string, givenName?: string, middleName?: string, honorificPrefix?: string, honorificSuffix?: string);
property familyName
familyName: string;
property formatted
formatted: string;
property givenName
givenName: string;
property honorificPrefix
honorificPrefix: string;
property honorificSuffix
honorificSuffix: string;
property middleName
middleName: string;
class ContactOrganization
class ContactOrganization implements IContactOrganization {}
constructor
constructor( type?: string, name?: string, department?: string, title?: string, pref?: boolean);
property department
department: string;
property name
name: string;
property pref
pref: boolean;
property title
title: string;
property type
type: string;
class Contacts
class Contacts {}
Contacts Access and manage Contacts on the device.
import { Contacts, Contact, ContactField, ContactName } from 'ionic-native';let contact: Contact = Contacts.create();contact.name = new ContactName(null, 'Smith', 'John');contact.phoneNumbers = [new ContactField('mobile', '6471234567')];contact.save().then(() => console.log('Contact saved!', contact),(error: any) => console.error('Error saving contact.', error));IContactProperties IContactError IContactName IContactField IContactAddress IContactOrganization IContactFindOptions
method create
static create: () => Contact;
Create a single contact.
Returns
{Contact} Returns a Contact object
method find
static find: ( fields: ContactFieldType[], options?: IContactFindOptions) => Promise<Contact[]>;
Search for contacts in the Contacts list.
Parameter fields
Contact fields to be used as a search qualifier
Parameter options
Optional options for the query
Returns
{Promise<Contact[]>} Returns a Promise that resolves with the search results (an array of Contact objects)
method pickContact
static pickContact: () => Promise<Contact>;
Select a single Contact.
Returns
{Promise} Returns a Promise that resolves with the selected Contact
class CouchbaseLite
class CouchbaseLite {}
Couchbase Lite Plugin to install Couchbase Lite in your PhoneGap app on iOS or Android
import { CouchbaseLite } from 'ionic-native';CouchbaseLite.getURL().then((url: any) => console.log(url)).catch((error: any) => console.log(error));
method getURL
static getURL: () => Promise<any>;
Get the database url {Promise} Returns a promise that resolves with the local database url
class Crop
class Crop {}
Crop Crops images
import {Crop} from 'ionic-native';...Crop.crop('path/to/image.jpg', {quality: 75}).then(newImage => console.log("new image path is: " + newImage),error => console.error("Error cropping image", error));
method crop
static crop: ( pathToImage: string, options?: { quality: number }) => Promise<string>;
Crops an image
Parameter pathToImage
Parameter options
Returns
{Promise} Returns a promise that resolves with the new image path, or rejects if failed to crop.
class DatePicker
class DatePicker {}
Date Picker The DatePicker plugin allows the user to fetch date or time using native dialogs.
import { DatePicker } from 'ionic-native';DatePicker.show({date: new Date(),mode: 'date'}).then(date => console.log('Got date: ', date),err => console.log('Error occurred while getting date: ', err));DatePickerOptions
property ANDROID_THEMES
static ANDROID_THEMES: { THEME_TRADITIONAL: number; THEME_HOLO_DARK: number; THEME_HOLO_LIGHT: number; THEME_DEVICE_DEFAULT_DARK: number; THEME_DEVICE_DEFAULT_LIGHT: number;};
method show
static show: (options: DatePickerOptions) => Promise<Date>;
Shows the date and/or time picker dialog(s)
Parameter options
Options for the date picker.
Returns
{Promise} Returns a promise that resolves with the picked date and/or time, or rejects with an error.
class DBMeter
class DBMeter {}
DB Meter This plugin defines a global DBMeter object, which permits to get the decibel values from the microphone.
import { DBMeter } from 'ionic-native';// Start listeninglet subscription = DBMeter.start().subscribe(data => console.log(data));// Check if we are listeningDBMeter.isListening().then((isListening: boolean) => console.log(isListening));// Stop listeningsubscription.unsubscribe();// Delete DBMeter instance from memoryDBMeter.delete().then(() => console.log('Deleted DB Meter instance'),error => console.log('Error occurred while deleting DB Meter instance'));
method delete
static delete: () => Promise<any>;
Delete the DB Meter instance
Returns
{Promise} Returns a promise that will resolve if the instance has been deleted, and rejects if errors occur.
method isListening
static isListening: () => Promise<boolean>;
Check if the DB Meter is listening
Returns
{Promise} Returns a promise that resolves with a boolean that tells us whether the DB meter is listening
method start
static start: () => Observable<any>;
Starts listening
Returns
{Observable} Returns an observable. Subscribe to start listening. Unsubscribe to stop listening.
method stop
static stop: () => Promise<any>;
Stops listening
class Deeplinks
class Deeplinks {}
Ionic Deeplinks This plugin handles deeplinks on iOS and Android for both custom URL scheme links and Universal App Links.
import { Deeplinks } from 'ionic-native';Deeplinks.route({'/about-us': AboutPage,'/universal-links-test': AboutPage,'/products/:productId': ProductPage}).subscribe((match) => {// match.$route - the route we matched, which is the matched entry from the arguments to route()// match.$args - the args passed in the link// match.$link - the full link dataconsole.log('Successfully matched route', match);}, (nomatch) => {// nomatch.$link - the full link dataconsole.error('Got a deeplink that didn\'t match', nomatch);});Alternatively, if you're using Ionic 2, there's a convenience method that takes a reference to a
NavController
and handles the actual navigation for you:Deeplinks.routeWithNavController(this.navController, {'/about-us': AboutPage,'/products/:productId': ProductPage}).subscribe((match) => {// match.$route - the route we matched, which is the matched entry from the arguments to route()// match.$args - the args passed in the link// match.$link - the full link dataconsole.log('Successfully matched route', match);}, (nomatch) => {// nomatch.$link - the full link dataconsole.error('Got a deeplink that didn\'t match', nomatch);});See the [Ionic 2 Deeplinks Demo](https://github.com/driftyco/ionic2-deeplinks-demo/blob/master/app/app.ts) for an example of how to retrieve the
NavController
reference at runtime.DeeplinkMatch
method route
static route: (paths: any) => Observable<DeeplinkMatch>;
Define a set of paths to match against incoming deeplinks.
Parameter Define
a set of paths to match against incoming deeplinks. paths takes an object of the form { 'path': data }. If a deeplink matches the path, the resulting path-data pair will be returned in the promise result which you can then use to navigate in the app as you see fit.
Returns
{Observable} Returns an Observable that is called each time a deeplink comes through, and errors if a deeplink comes through that does not match a given path.
method routeWithNavController
static routeWithNavController: ( navController: any, paths: any) => Observable<DeeplinkMatch>;
This is a convenience version of
route
that takes a reference to a NavController from Ionic 2, or a custom class that conforms to this protocol:NavController.push = function(View, Params){}
This handler will automatically navigate when a route matches. If you need finer-grained control over the behavior of a matching deeplink, use the plain
route
method.Parameter Define
a set of paths to match against incoming deeplinks. paths takes an object of the form { 'path': data }. If a deeplink matches the path, the resulting path-data pair will be returned in the promise result which you can then use to navigate in the app as you see fit.
Returns
{Observable} Returns an Observable that resolves each time a deeplink comes through, and errors if a deeplink comes through that does not match a given path.
class Device
class Device {}
Device Access information about the underlying device and platform.
import { Device } from 'ionic-native';console.log('Device UUID is: ' + Device.uuid);
property cordova
static cordova: string;
Get the version of Cordova running on the device.
property isVirtual
static isVirtual: boolean;
Whether the device is running on a simulator.
property manufacturer
static manufacturer: string;
Get the device's manufacturer.
property model
static model: string;
The device.model returns the name of the device's model or product. The value is set by the device manufacturer and may be different across versions of the same product.
property platform
static platform: string;
Get the device's operating system name.
property serial
static serial: string;
Get the device hardware serial number.
property uuid
static uuid: string;
Get the device's Universally Unique Identifier (UUID).
property version
static version: string;
Get the operating system version.
class DeviceAccounts
class DeviceAccounts {}
method get
static get: () => Promise<any>;
Gets all accounts registered on the Android Device
Returns
{Promise}
method getByType
static getByType: (type: string) => Promise<any>;
Get all accounts registered on Android device for requested type
Returns
{Promise}
method getEmail
static getEmail: () => Promise<any>;
Get the first email registered on Android device
Returns
{Promise}
method getEmails
static getEmails: () => Promise<any>;
Get all emails registered on Android device (accounts with 'com.google' type)
Returns
{Promise}
class DeviceFeedback
class DeviceFeedback {}
DeviceFeedback
Plugin that lets you provide haptic or acoustic feedback on Android devices.
import { DeviceFeedback } from 'ionic-native';DeviceFeedback.acoustic();DeviceFeedback.haptic(0);DeviceFeedback.isFeedbackEnabled().then((feedback) => {console.log(feedback);// {// acoustic: true,// haptic: true// }});
method acoustic
static acoustic: () => void;
Provide sound feedback to user, nevertheless respect user's settings and current active device profile as native feedback do.
method haptic
static haptic: (type: number) => void;
Provide vibrate feedback to user, nevertheless respect user's tactile feedback setting as native feedback do.
Parameter type
Specify type of vibration feedback. 0 for long press, 1 for virtual key, or 3 for keyboard tap.
method isFeedbackEnabled
static isFeedbackEnabled: () => Promise<{ haptic: boolean; acoustic: boolean }>;
Check if haptic and acoustic feedback is enabled by user settings.
Returns
{Promise}
class DeviceMotion
class DeviceMotion {}
Device Motion Requires Cordova plugin:
cordova-plugin-device-motion
. For more info, please see the [Device Motion docs](https://github.com/apache/cordova-plugin-device-motion).import { DeviceMotion, DeviceMotionAccelerationData } from 'ionic-native';// Get the device current accelerationDeviceMotion.getCurrentAcceleration().then((acceleration: DeviceMotionAccelerationData) => console.log(acceleration),(error: any) => console.log(error));// Watch device accelerationvar subscription = DeviceMotion.watchAcceleration().subscribe((acceleration: DeviceMotionAccelerationData) => {console.log(acceleration);});// Stop watchsubscription.unsubscribe();DeviceMotionAccelerationData DeviceMotionAccelerometerOptions
method getCurrentAcceleration
static getCurrentAcceleration: () => Promise<DeviceMotionAccelerationData>;
Get the current acceleration along the x, y, and z axes.
Returns
{Promise} Returns object with x, y, z, and timestamp properties
method watchAcceleration
static watchAcceleration: ( options?: DeviceMotionAccelerometerOptions) => Observable<DeviceMotionAccelerationData>;
Watch the device acceleration. Clear the watch by unsubscribing from the observable.
Parameter options
list of options for the accelerometer.
Returns
{Observable} Observable returns an observable that you can subscribe to
class DeviceOrientation
class DeviceOrientation {}
Device Orientation Requires Cordova plugin:
cordova-plugin-device-orientation
. For more info, please see the [Device Orientation docs](https://github.com/apache/cordova-plugin-device-orientation).// DeviceOrientationCompassHeading is an interface for compassimport { DeviceOrientation, DeviceOrientationCompassHeading } from 'ionic-native';// Get the device current compass headingDeviceOrientation.getCurrentHeading().then((data: DeviceOrientationCompassHeading) => console.log(data),(error: any) => console.log(error));// Watch the device compass heading changevar subscription = DeviceOrientation.watchHeading().subscribe((data: DeviceOrientationCompassHeading) => console.log(data));// Stop watching heading changesubscription.unsubscribe();DeviceOrientationCompassOptions DeviceOrientationCompassHeading
method getCurrentHeading
static getCurrentHeading: () => Promise<DeviceOrientationCompassHeading>;
Get the current compass heading.
Returns
{Promise}
method watchHeading
static watchHeading: ( options?: DeviceOrientationCompassOptions) => Observable<DeviceOrientationCompassHeading>;
Get the device current heading at a regular interval
Stop the watch by unsubscribing from the observable
Parameter options
Options for compass. Frequency and Filter. Optional
Returns
{Observable} Returns an observable that contains the compass heading
class Diagnostic
class Diagnostic {}
Diagnostic Checks whether device hardware features are enabled or available to the app, e.g. camera, GPS, wifi
import { Diagnostic } from 'ionic-native';let successCallback = (isAvailable) => { console.log('Is available? ' + isAvailable); };let errorCallback = (e) => console.error(e);Diagnostic.isCameraAvailable().then(successCallback).catch(errorCallback);Diagnostic.isBluetoothAvailable().then(successCallback, errorCallback);Diagnostic.getBluetoothState().then((state) => {if (state == Diagnostic.bluetoothStates.POWERED_ON){// do something} else {// do something else}}).catch(e => console.error(e));
property bluetoothState
static bluetoothState: { UNKNOWN: string; RESETTING: string; UNSUPPORTED: string; UNAUTHORIZED: string; POWERED_OFF: string; POWERED_ON: string; POWERING_OFF: string; POWERING_ON: string;};
property locationAuthorizationMode
static locationAuthorizationMode: { ALWAYS: string; WHEN_IN_USE: string };
property locationMode
static locationMode: { HIGH_ACCURACY: string; DEVICE_ONLY: string; BATTERY_SAVING: string; LOCATION_OFF: string;};
property NFCState
static NFCState: { UNKNOWN: string; POWERED_OFF: string; POWERED_ON: string; POWERING_ON: string; POWERING_OFF: string;};
property permission
static permission: { READ_CALENDAR: string; WRITE_CALENDAR: string; CAMERA: string; READ_CONTACTS: string; WRITE_CONTACTS: string; GET_ACCOUNTS: string; ACCESS_FINE_LOCATION: string; ACCESS_COARSE_LOCATION: string; RECORD_AUDIO: string; READ_PHONE_STATE: string; CALL_PHONE: string; ADD_VOICEMAIL: string; USE_SIP: string; PROCESS_OUTGOING_CALLS: string; READ_CALL_LOG: string; WRITE_CALL_LOG: string; SEND_SMS: string; RECEIVE_SMS: string; READ_SMS: string; RECEIVE_WAP_PUSH: string; RECEIVE_MMS: string; WRITE_EXTERNAL_STORAGE: string; READ_EXTERNAL_STORAGE: string; BODY_SENSORS: string;};
property permissionGroups
static permissionGroups: { CALENDAR: string[]; CAMERA: string[]; CONTACTS: string[]; LOCATION: string[]; MICROPHONE: string[]; PHONE: string[]; SENSORS: string[]; SMS: string[]; STORAGE: string[];};
property permissionStatus
static permissionStatus: { GRANTED: string; DENIED: string; NOT_REQUESTED: string; DENIED_ALWAYS: string; RESTRICTED: string; GRANTED_WHEN_IN_USE: string;};
method getBackgroundRefreshStatus
static getBackgroundRefreshStatus: () => Promise<any>;
Returns the background refresh authorization status for the application.
Returns
{Promise}
method getBluetoothState
static getBluetoothState: () => Promise<any>;
Returns the state of Bluetooth on the device.
Returns
{Promise}
method getCalendarAuthorizationStatus
static getCalendarAuthorizationStatus: () => Promise<any>;
Returns the calendar authorization status for the application.
Notes for Android: - This is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will always return
GRANTED
status as permissions are already granted at installation time.Notes for iOS: - This relates to Calendar Events (not Calendar Reminders)
Returns
{Promise}
method getCameraAuthorizationStatus
static getCameraAuthorizationStatus: () => Promise<any>;
Returns the camera authorization status for the application.
Returns
{Promise}
method getCameraRollAuthorizationStatus
static getCameraRollAuthorizationStatus: () => Promise<boolean>;
Returns the authorization status for the application to use the Camera Roll in Photos app.
Returns
{Promise}
method getContactsAuthorizationStatus
static getContactsAuthorizationStatus: () => Promise<any>;
Returns the contacts authorization status for the application.
Returns
{Promise}
method getExternalSdCardDetails
static getExternalSdCardDetails: () => Promise<any>;
Returns details of external SD card(s): absolute path, is writable, free space.
The intention of this method is to return the location and details of removable external SD cards. This differs from the "external directories" returned by cordova-plugin-file which return mount points relating to non-removable (internal) storage.
Learn more about this method [here](https://github.com/dpa99c/cordova-diagnostic-plugin#getexternalsdcarddetails)
Returns
{Promise}
method getExternalStorageAuthorizationStatus
static getExternalStorageAuthorizationStatus: () => Promise<any>;
CReturns the external storage authorization status for the application.
Returns
{Promise}
method getLocationAuthorizationStatus
static getLocationAuthorizationStatus: () => Promise<any>;
Returns the location authorization status for the application.
Returns
{Promise}
method getLocationMode
static getLocationMode: () => Promise<any>;
Returns the current location mode setting for the device.
Returns
{Promise}
method getMicrophoneAuthorizationStatus
static getMicrophoneAuthorizationStatus: () => Promise<any>;
Returns the microphone authorization status for the application.
Returns
{Promise}
method getPermissionAuthorizationStatus
static getPermissionAuthorizationStatus: (permission: any) => Promise<any>;
Returns the current authorisation status for a given permission. Note: this is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will always return GRANTED status as permissions are already granted at installation time.
Parameter permission
Returns
{Promise}
method getPermissionsAuthorizationStatus
static getPermissionsAuthorizationStatus: (permissions: any[]) => Promise<any>;
Returns the current authorisation status for multiple permissions. Note: this is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will always return GRANTED status as permissions are already granted at installation time.
Parameter permissions
Returns
{Promise}
method getRemindersAuthorizationStatus
static getRemindersAuthorizationStatus: () => Promise<any>;
Returns the reminders authorization status for the application.
Returns
{Promise}
method getRemoteNotificationTypes
static getRemoteNotificationTypes: () => Promise<any>;
Indicates the current setting of notification types for the app in the Settings app. Note: on iOS 8+, if "Allow Notifications" switch is OFF, all types will be returned as disabled.
Returns
{Promise}
method hasBluetoothLEPeripheralSupport
static hasBluetoothLEPeripheralSupport: () => Promise<boolean>;
Checks if the device supports Bluetooth Low Energy (LE) Peripheral mode.
Returns
{Promise}
method hasBluetoothLESupport
static hasBluetoothLESupport: () => Promise<boolean>;
Checks if the device has Bluetooth Low Energy (LE) capabilities.
Returns
{Promise}
method hasBluetoothSupport
static hasBluetoothSupport: () => Promise<boolean>;
Checks if the device has Bluetooth capabilities.
Returns
{Promise}
method isBackgroundRefreshAuthorized
static isBackgroundRefreshAuthorized: () => Promise<boolean>;
Checks if the application is authorized for background refresh.
Returns
{Promise}
method isBluetoothAvailable
static isBluetoothAvailable: () => Promise<any>;
Checks if the device has Bluetooth capabilities and if so that Bluetooth is switched on (same on Android, iOS and Windows 10 Mobile) On Android this requires permission <uses-permission android:name="android.permission.BLUETOOTH" />
Returns
{Promise}
method isBluetoothEnabled
static isBluetoothEnabled: () => Promise<boolean>;
Checks if the device setting for Bluetooth is switched on. This requires
BLUETOOTH
permission on AndroidReturns
{Promise}
method isCalendarAuthorized
static isCalendarAuthorized: () => Promise<boolean>;
Checks if the application is authorized to use the calendar.
Notes for Android: - This is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will always return TRUE as permissions are already granted at installation time.
Notes for iOS: - This relates to Calendar Events (not Calendar Reminders)
Returns
{Promise}
method isCameraAuthorized
static isCameraAuthorized: () => Promise<any>;
Checks if the application is authorized to use the camera. Note for Android: this is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will always return TRUE as permissions are already granted at installation time.
Returns
{Promise}
method isCameraAvailable
static isCameraAvailable: () => Promise<any>;
Checks if the device has a camera. On Android this returns true if the device has a camera. On iOS this returns true if both the device has a camera AND the application is authorized to use it. On Windows 10 Mobile this returns true if both the device has a rear-facing camera AND the application is authorized to use it.
Returns
{Promise}
method isCameraPresent
static isCameraPresent: () => Promise<any>;
Checks if camera hardware is present on device.
Returns
{Promise}
method isCameraRollAuthorized
static isCameraRollAuthorized: () => Promise<boolean>;
Checks if the application is authorized to use the Camera Roll in Photos app.
Returns
{Promise}
method isContactsAuthorized
static isContactsAuthorized: () => Promise<boolean>;
Checks if the application is authorized to use contacts (address book).
Returns
{Promise}
method isExternalStorageAuthorized
static isExternalStorageAuthorized: () => Promise<boolean>;
Checks if the application is authorized to use external storage.
Returns
{Promise}
method isGpsLocationAvailable
static isGpsLocationAvailable: () => Promise<boolean>;
Checks if high-accuracy locations are available to the app from GPS hardware. Returns true if Location mode is enabled and is set to "Device only" or "High accuracy" AND if the app is authorised to use location.
Returns
{Promise}
method isGpsLocationEnabled
static isGpsLocationEnabled: () => Promise<any>;
Checks if location mode is set to return high-accuracy locations from GPS hardware. Returns true if Location mode is enabled and is set to either: - Device only = GPS hardware only (high accuracy) - High accuracy = GPS hardware, network triangulation and Wifi network IDs (high and low accuracy)
Returns
{Promise}
method isLocationAuthorized
static isLocationAuthorized: () => Promise<any>;
Checks if the application is authorized to use location. Note for Android: this is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will always return GRANTED status as permissions are already granted at installation time.
Returns
{Promise}
method isLocationAvailable
static isLocationAvailable: () => Promise<any>;
Checks if app is able to access device location.
Returns
{Promise}
method isLocationEnabled
static isLocationEnabled: () => Promise<boolean>;
Returns true if the device setting for location is on. On Android this returns true if Location Mode is switched on. On iOS this returns true if Location Services is switched on.
Returns
{Promise}
method isMicrophoneAuthorized
static isMicrophoneAuthorized: () => Promise<boolean>;
Checks if the application is authorized to use the microphone.
Returns
{Promise}
method isMotionAvailable
static isMotionAvailable: () => Promise<boolean>;
Checks if motion tracking is available on the current device. {Promise}
method isMotionRequestOutcomeAvailable
static isMotionRequestOutcomeAvailable: () => Promise<boolean>;
Checks if it's possible to determine the outcome of a motion authorization request on the current device. There's no direct way to determine if authorization was granted or denied, so the Pedometer API must be used to indirectly determine this: therefore, if the device supports motion tracking but not Pedometer Event Tracking, the outcome of requesting motion detection cannot be determined.
{Promise}
method isNetworkLocationAvailable
static isNetworkLocationAvailable: () => Promise<any>;
Checks if low-accuracy locations are available to the app from network triangulation/WiFi access points. Returns true if Location mode is enabled and is set to "Battery saving" or "High accuracy" AND if the app is authorised to use location.
Returns
{Promise}
method isNetworkLocationEnabled
static isNetworkLocationEnabled: () => Promise<any>;
Checks if location mode is set to return low-accuracy locations from network triangulation/WiFi access points. Returns true if Location mode is enabled and is set to either: - Battery saving = network triangulation and Wifi network IDs (low accuracy) - High accuracy = GPS hardware, network triangulation and Wifi network IDs (high and low accuracy)
Returns
{Promise}
method isNFCAvailable
static isNFCAvailable: () => Promise<boolean>;
Checks if NFC is available to the app. Returns true if the device has NFC capabilities AND if NFC setting is switched on. Note: this operation does not require NFC permission in the manifest.
Returns
{Promise}
method isNFCEnabled
static isNFCEnabled: () => Promise<boolean>;
Checks if the device setting for NFC is switched on. Note: this operation does not require NFC permission in the manifest.
Returns
{Promise}
method isNFCPresent
static isNFCPresent: () => Promise<boolean>;
Checks if NFC hardware is present on device.
Returns
{Promise}
method isRegisteredForRemoteNotifications
static isRegisteredForRemoteNotifications: () => Promise<boolean>;
Indicates if the app is registered for remote (push) notifications on the device.
Returns
{Promise}
method isRemindersAuthorized
static isRemindersAuthorized: () => Promise<boolean>;
Checks if the application is authorized to use reminders.
Returns
{Promise}
method isRemoteNotificationsEnabled
static isRemoteNotificationsEnabled: () => Promise<boolean>;
Checks if remote (push) notifications are enabled.
Returns
{Promise}
method isRequestingPermission
static isRequestingPermission: () => boolean;
Indicates if the plugin is currently requesting a runtime permission via the native API. Note that only one request can be made concurrently because the native API cannot handle concurrent requests, so the plugin will invoke the error callback if attempting to make more than one simultaneous request. Multiple permission requests should be grouped into a single call since the native API is setup to handle batch requests of multiple permission groups.
Returns
{boolean}
method isWifiAvailable
static isWifiAvailable: () => Promise<any>;
Checks if Wifi is connected/enabled. On iOS this returns true if the device is connected to a network by WiFi. On Android and Windows 10 Mobile this returns true if the WiFi setting is set to enabled. On Android this requires permission.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Returns
{Promise}
method isWifiEnabled
static isWifiEnabled: () => Promise<boolean>;
Returns true if the WiFi setting is set to enabled, and is the same as
isWifiAvailable()
Returns
{Promise}
method registerBluetoothStateChangeHandler
static registerBluetoothStateChangeHandler: (handler: Function) => void;
Registers a function to be called when a change in Bluetooth state occurs.
Parameter handler
method registerLocationStateChangeHandler
static registerLocationStateChangeHandler: (handler: Function) => void;
Registers a function to be called when a change in Location state occurs.
Parameter handler
method registerNFCStateChangeHandler
registerNFCStateChangeHandler: (handler: Function) => void;
Registers a function to be called when a change in NFC state occurs. Pass in a falsey value to de-register the currently registered function.
Parameter hander
callback function to be called when NFC state changes
Returns
{Promise}
method registerPermissionRequestCompleteHandler
static registerPermissionRequestCompleteHandler: (handler: Function) => void;
Registers a function to be called when a runtime permission request has completed. Pass in a falsey value to de-register the currently registered function.
Parameter handler
method requestAndCheckMotionAuthorization
static requestAndCheckMotionAuthorization: () => Promise<any>;
Requests and checks motion authorization for the application: there is no way to independently request only or check only, so both must be done in one operation.
Learn more about this method [here](https://github.com/dpa99c/cordova-diagnostic-plugin#requestandcheckmotionauthorization)
{Promise}
method requestBluetoothAuthorization
static requestBluetoothAuthorization: () => Promise<any>;
Requests Bluetooth authorization for the application.
Learn more about this method [here](https://github.com/dpa99c/cordova-diagnostic-plugin#requestbluetoothauthorization) {Promise}
method requestCalendarAuthorization
static requestCalendarAuthorization: () => Promise<any>;
Requests calendar authorization for the application.
Notes for iOS: - Should only be called if authorization status is NOT_DETERMINED. Calling it when in any other state will have no effect and just return the current authorization status. - This relates to Calendar Events (not Calendar Reminders)
Notes for Android: - This is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will have no effect as the permissions are already granted at installation time. - This requests permission for
READ_CALENDAR
run-time permission - Required permissions must be added toAndroidManifest.xml
as appropriate - see Android permissions:READ_CALENDAR
,WRITE_CALENDAR
Returns
{Promise}
method requestCameraAuthorization
static requestCameraAuthorization: () => Promise<any>;
Requests camera authorization for the application.
Returns
{Promise}
method requestCameraRollAuthorization
static requestCameraRollAuthorization: () => Promise<any>;
Requests camera roll authorization for the application. Should only be called if authorization status is NOT_REQUESTED. Calling it when in any other state will have no effect.
Returns
{Promise}
method requestContactsAuthorization
static requestContactsAuthorization: () => Promise<any>;
Requests contacts authorization for the application.
Returns
{Promise}
method requestExternalStorageAuthorization
static requestExternalStorageAuthorization: () => Promise<any>;
Requests external storage authorization for the application.
Returns
{Promise}
method requestLocationAuthorization
static requestLocationAuthorization: (mode?: string) => Promise<any>;
Returns the location authorization status for the application. Note for Android: this is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will always return GRANTED status as permissions are already granted at installation time.
mode - (iOS-only / optional) location authorization mode: "always" or "when_in_use". If not specified, defaults to "when_in_use".
Returns
{Promise}
method requestMicrophoneAuthorization
static requestMicrophoneAuthorization: () => Promise<any>;
Requests microphone authorization for the application.
Returns
{Promise}
method requestRemindersAuthorization
static requestRemindersAuthorization: () => Promise<any>;
Requests reminders authorization for the application.
Returns
{Promise}
method requestRuntimePermission
static requestRuntimePermission: (permission: any) => Promise<any>;
Requests app to be granted authorisation for a runtime permission. Note: this is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will have no effect as the permissions are already granted at installation time.
Parameter permission
Returns
{Promise}
method requestRuntimePermissions
static requestRuntimePermissions: (permissions: any[]) => Promise<any>;
Requests app to be granted authorisation for multiple runtime permissions. Note: this is intended for Android 6 / API 23 and above. Calling on Android 5 / API 22 and below will always return GRANTED status as permissions are already granted at installation time.
Parameter permissions
Returns
{Promise}
method setBluetoothState
static setBluetoothState: (state: boolean) => Promise<any>;
Enables/disables Bluetooth on the device. Requires
BLUETOOTH
andBLUETOOTH_ADMIN
permissions on AndroidParameter state
Returns
{Promise}
method setWifiState
static setWifiState: (state: boolean) => Promise<any>;
Enables/disables WiFi on the device. Requires
ACCESS_WIFI_STATE
andCHANGE_WIFI_STATE
permissions on AndroidParameter state
Returns
{Promise}
method switchToBluetoothSettings
static switchToBluetoothSettings: () => void;
Displays Bluetooth settings to allow user to enable Bluetooth.
method switchToLocationSettings
static switchToLocationSettings: () => void;
Displays the device location settings to allow user to enable location services/change location mode.
method switchToMobileDataSettings
static switchToMobileDataSettings: () => void;
Displays mobile settings to allow user to enable mobile data.
method switchToNFCSettings
switchToNFCSettings: () => void;
Displays NFC settings to allow user to enable NFC.
method switchToSettings
static switchToSettings: () => Promise<any>;
Opens settings page for this app. On Android, this opens the "App Info" page in the Settings app. On iOS, this opens the app settings page in the Settings app. This works only on iOS 8+ - iOS 7 and below will invoke the errorCallback.
Returns
{Promise}
method switchToWifiSettings
static switchToWifiSettings: () => void;
Displays WiFi settings to allow user to enable WiFi.
method switchToWirelessSettings
switchToWirelessSettings: () => void;
Switches to the wireless settings page in the Settings app. Allows configuration of wireless controls such as Wi-Fi, Bluetooth and Mobile networks.
class Dialogs
class Dialogs {}
Dialogs This plugin gives you ability to access and customize the device native dialogs.
Requires Cordova plugin:
cordova-plugin-dialogs
. For more info, please see the [Dialogs plugin docs](https://github.com/apache/cordova-plugin-dialogs).import { Dialogs } from 'ionic-native';DialogsPromptCallback
method alert
static alert: ( message: any, title?: string, buttonName?: string) => Promise<any>;
Shows a custom alert or dialog box.
Parameter message
Dialog message.
Parameter title
Dialog title. (Optional, defaults to Alert)
Parameter buttonName
Button name. (Optional, defaults to OK)
Returns
{Promise} Returns a blank promise once the user has dismissed the alert.
method beep
static beep: (times: number) => void;
The device plays a beep sound.
Parameter times
The number of times to repeat the beep.
method confirm
static confirm: ( message: any, title?: string, buttonLabels?: Array<string>) => Promise<number>;
Displays a customizable confirmation dialog box.
Parameter message
Dialog message.
Parameter title
Dialog title. (Optional, defaults to Confirm)
Parameter buttonLabels
Array of strings specifying button labels. (Optional, defaults to [OK,Cancel])
Returns
{Promise} Returns a promise that resolves the button index that was clicked. Note that the index use one-based indexing.
method prompt
static prompt: ( message?: string, title?: string, buttonLabels?: Array<string>, defaultText?: string) => Promise<DialogsPromptCallback>;
Displays a native dialog box that is more customizable than the browser's prompt function.
Parameter message
Dialog message.
Parameter title
Dialog title. (Optional, defaults to Prompt)
Parameter buttonLabels
Array of strings specifying button labels. (Optional, defaults to ["OK","Cancel"])
Parameter defaultText
Default textbox input value. (Optional, Default: empty string)
Returns
{Promise} Returns a promise that resolves an object with the button index clicked and the text entered
class EmailComposer
class EmailComposer {}
Email Composer
Requires Cordova plugin: cordova-plugin-email-composer. For more info, please see the [Email Composer plugin docs](https://github.com/hypery2k/cordova-email-plugin).
DISCLAIMER: This plugin is experiencing issues with the latest versions of Cordova. Use at your own risk. Functionality is not guaranteed. Please stay tuned for a more stable version. A good alternative to this plugin is the social sharing plugin.
import { EmailComposer } from 'ionic-native';EmailComposer.isAvailable().then((available: boolean) =>{if(available) {//Now we know we can send}});let email = {to: 'max@mustermann.de',cc: 'erika@mustermann.de',bcc: ['john@doe.com', 'jane@doe.com'],attachments: ['file://img/logo.png','res://icon.png','base64:icon.png//iVBORw0KGgoAAAANSUhEUg...','file://README.pdf'],subject: 'Cordova Icons',body: 'How are you? Nice greetings from Leipzig',isHtml: true};// Send a text message using default optionsEmailComposer.open(email);EmailComposerOptions
Modifiers
@beta
method addAlias
static addAlias: (alias: string, packageName: string) => void;
Adds a new mail app alias.
Parameter alias
The alias name
Parameter packageName
The package name
method isAvailable
static isAvailable: (app?: string) => Promise<any>;
Verifies if sending emails is supported on the device.
Parameter app
An optional app id or uri scheme.
Returns
{Promise} Resolves if available, rejects if not available
method open
static open: (options: EmailComposerOptions, scope?: any) => Promise<any>;
Displays the email composer pre-filled with data.
Parameter options
Email
Parameter scope
An optional scope for the promise
Returns
{Promise} Resolves promise when the EmailComposer has been opened
class EstimoteBeacons
class EstimoteBeacons {}
EstimoteBeacons
This plugin enables communication between a phone and Estimote Beacons peripherals.
EstimoteBeaconRegion
property BeaconColorBlueberryPie
static BeaconColorBlueberryPie: number;
Beacon colour
property BeaconColorCandyFloss
static BeaconColorCandyFloss: number;
Beacon colour
property BeaconColorIcyMarshmallow
static BeaconColorIcyMarshmallow: number;
Beacon colour
property BeaconColorLemonTart
static BeaconColorLemonTart: number;
Beacon colour
property BeaconColorLiquoriceSwirl
static BeaconColorLiquoriceSwirl: number;
Beacon colour
property BeaconColorMintCocktail
static BeaconColorMintCocktail: number;
Beacon colour
property BeaconColorSweetBeetroot
static BeaconColorSweetBeetroot: number;
Beacon colour.
property BeaconColorTransparent
static BeaconColorTransparent: number;
Beacon colour
property BeaconColorUnknown
static BeaconColorUnknown: number;
Beacon colour
property BeaconColorVanillaJello
static BeaconColorVanillaJello: number;
Beacon colour
property BeaconColorWhite
static BeaconColorWhite: number;
Beacon colour
property ProximityFar
static ProximityFar: number;
Proximity value
property ProximityImmediate
static ProximityImmediate: number;
Proximity value
property ProximityNear
static ProximityNear: number;
Proximity value
property ProximityUnknown
static ProximityUnknown: number;
Proximity value
property RegionStateInside
static RegionStateInside: string;
Region state
property RegionStateOutside
static RegionStateOutside: string;
Region state
property RegionStateUnknown
static RegionStateUnknown: string;
Region state
method authorizationStatus
static authorizationStatus: () => Promise<any>;
Get the current location authorization status. Implemented on iOS 8+. Does nothing on other platforms.
EstimoteBeacons.authorizationStatus().then((result) => { console.log('Location authorization status: ' + result); },(errorMessage) => { console.log('Error: ' + errorMessage); });Returns
{Promise}
See Also
method connectToBeacon
static connectToBeacon: (beacon: any) => Promise<any>;
Connect to Estimote Beacon. Available on Android.
EstimoteBeacons.connectToBeacon(FF:0F:F0:00:F0:00);EstimoteBeacons.connectToBeacon({proximityUUID: '000000FF-F00F-0FF0-F000-000FF0F00000',major: 1,minor: 1});Parameter beacon
Beacon to connect to.
Returns
{Promise}
method disconnectConnectedBeacon
static disconnectConnectedBeacon: () => Promise<any>;
Disconnect from connected Estimote Beacon. Available on Android.
EstimoteBeacons.disconnectConnectedBeacon();Returns
{Promise}
method enableAnalytics
static enableAnalytics: (enable: boolean) => Promise<any>;
Enable analytics.
Parameter enable
Boolean value to turn analytics on or off (mandatory).
Returns
{Promise}
See Also
- EstimoteBeacons.enableAnalytics(true).then(() => { console.log('Analytics enabled'); });
method isAnalyticsEnabled
static isAnalyticsEnabled: () => Promise<any>;
Test if analytics is enabled.
Returns
{Promise}
See Also
- EstimoteBeacons.isAnalyticsEnabled().then((enabled) => { console.log('Analytics enabled: ' + enabled); });
method isAuthorized
static isAuthorized: () => Promise<any>;
Test if App ID and App Token is set.
Returns
{Promise}
See Also
- EstimoteBeacons.isAuthorized().then((isAuthorized) => { console.log('App ID and App Token is set: ' + isAuthorized); });
method requestAlwaysAuthorization
static requestAlwaysAuthorization: () => Promise<any>;
Ask the user for permission to use location services whenever the app is running. You need to call this function or requestWhenInUseAuthorization on iOS 8+. Does nothing on other platforms.
EstimoteBeacons.requestAlwaysAuthorization().then(() => { console.log('on success'); },() => { console.log('on error'); });Returns
{Promise}
See Also
method requestWhenInUseAuthorization
static requestWhenInUseAuthorization: () => Promise<any>;
Ask the user for permission to use location services while the app is in the foreground. You need to call this function or requestAlwaysAuthorization on iOS 8+. Does nothing on other platforms.
EstimoteBeacons.requestWhenInUseAuthorization().then(() => { console.log('on success'); },() => { console.log('on error'); });Returns
{Promise}
See Also
method setupAppIDAndAppToken
static setupAppIDAndAppToken: (appID: string, appToken: string) => Promise<any>;
Set App ID and App Token.
Parameter appID
The App ID (mandatory).
Parameter appToken
The App Token (mandatory).
Returns
{Promise}
See Also
- EstimoteBeacons.setupAppIDAndAppToken('MyAppID', 'MyAppToken').then(() => { console.log('AppID and AppToken configured!'); });
method startAdvertisingAsBeacon
static startAdvertisingAsBeacon: ( uuid: string, major: number, minor: number, regionId: string) => Promise<any>;
Start advertising as a beacon.
EstimoteBeacons.startAdvertisingAsBeacon('B9407F30-F5F8-466E-AFF9-25556B57FE6D', 1, 1, 'MyRegion').then(() => { console.log('Beacon started'); });setTimeout(() => {EstimoteBeacons.stopAdvertisingAsBeacon().then((result) => { console.log('Beacon stopped'); });}, 5000);Parameter uuid
UUID string the beacon should advertise (mandatory).
Parameter major
Major value to advertise (mandatory).
Parameter minor
Minor value to advertise (mandatory).
Parameter regionId
Identifier of the region used to advertise (mandatory).
Returns
{Promise}
method startEstimoteBeaconDiscovery
static startEstimoteBeaconDiscovery: () => Observable<any>;
Start scanning for all nearby beacons using CoreBluetooth (no region object is used). Available on iOS.
EstimoteBeacons.startEstimoteBeaconDiscovery().subscribe(beacons => {console.log(JSON.stringify(beacons));});setTimeout(() => {EstimoteBeacons.stopEstimoteBeaconDiscovery().then(() => { console.log('scan stopped'); });}, 5000);Returns
{Observable} Returns an Observable that notifies of each beacon discovered.
method startMonitoringForRegion
static startMonitoringForRegion: ( region: EstimoteBeaconRegion, notifyEntryStateOnDisplay: boolean) => Observable<any>;
Start monitoring beacons. Available on iOS and Android.
let region: EstimoteBeaconRegion = {} // Empty region matches all beacons.EstimoteBeacons.startMonitoringForRegion(region).subscribe(state => {console.log('Region state: ' + JSON.stringify(state));});Parameter region
Dictionary with region properties (mandatory).
Parameter notifyEntryStateOnDisplay
Set to true to detect if you are inside a region when the user turns display on, see iOS documentation for further details (optional, defaults to false, iOS only).
Returns
{Observable} Returns an Observable that notifies of each region state discovered.
method startRangingBeaconsInRegion
static startRangingBeaconsInRegion: ( region: EstimoteBeaconRegion) => Observable<any>;
Start ranging beacons. Available on iOS and Android.
let region: EstimoteBeaconRegion = {} // Empty region matches all beacons.EstimoteBeacons.startRangingBeaconsInRegion(region).subscribe(info => {console.log(JSON.stringify(info));});setTimeout(() => {EstimoteBeacons.stopRangingBeaconsInRegion(region).then(() => { console.log('scan stopped'); });}, 5000);Parameter region
Dictionary with region properties (mandatory).
Returns
{Observable} Returns an Observable that notifies of each beacon discovered.
method startRangingSecureBeaconsInRegion
static startRangingSecureBeaconsInRegion: ( region: EstimoteBeaconRegion) => Observable<any>;
Start ranging secure beacons. Available on iOS. This function has the same parameters/behaviour as EstimoteBeacons.startRangingBeaconsInRegion. To use secure beacons set the App ID and App Token using EstimoteBeacons.setupAppIDAndAppToken.
Returns
{Observable}
method startSecureMonitoringForRegion
static startSecureMonitoringForRegion: ( region: EstimoteBeaconRegion, notifyEntryStateOnDisplay: boolean) => Observable<any>;
Start monitoring secure beacons. Available on iOS. This function has the same parameters/behaviour as EstimoteBeacons.startMonitoringForRegion. To use secure beacons set the App ID and App Token using EstimoteBeacons.setupAppIDAndAppToken.
Parameter region
Region
Parameter notifyEntryStateOnDisplay
Returns
{Observable}
See Also
method stopAdvertisingAsBeacon
static stopAdvertisingAsBeacon: () => Promise<any>;
Stop advertising as a beacon.
EstimoteBeacons.startAdvertisingAsBeacon('B9407F30-F5F8-466E-AFF9-25556B57FE6D', 1, 1, 'MyRegion').then(() => { console.log('Beacon started'); });setTimeout(() => {EstimoteBeacons.stopAdvertisingAsBeacon().then((result) => { console.log('Beacon stopped'); });}, 5000);Returns
{Promise}
method stopEstimoteBeaconDiscovery
static stopEstimoteBeaconDiscovery: () => Promise<any>;
Stop CoreBluetooth scan. Available on iOS.
EstimoteBeacons.startEstimoteBeaconDiscovery().subscribe(beacons => {console.log(JSON.stringify(beacons));});setTimeout(() => {EstimoteBeacons.stopEstimoteBeaconDiscovery().then(() => { console.log('scan stopped'); });}, 5000);Returns
{Promise}
method stopMonitoringForRegion
static stopMonitoringForRegion: (region: EstimoteBeaconRegion) => Promise<any>;
Stop monitoring beacons. Available on iOS and Android.
let region: EstimoteBeaconRegion = {} // Empty region matches all beacons.EstimoteBeacons.stopMonitoringForRegion(region).then(() => { console.log('monitoring is stopped'); });Parameter region
Dictionary with region properties (mandatory).
Returns
{Promise}
method stopRangingBeaconsInRegion
static stopRangingBeaconsInRegion: ( region: EstimoteBeaconRegion) => Promise<any>;
Stop ranging beacons. Available on iOS and Android.
let region: EstimoteBeaconRegion = {} // Empty region matches all beacons.EstimoteBeacons.startRangingBeaconsInRegion(region).subscribe(info => {console.log(JSON.stringify(info));});setTimeout(() => {EstimoteBeacons.stopRangingBeaconsInRegion(region).then(() => { console.log('scan stopped'); });}, 5000);Parameter region
Dictionary with region properties (mandatory).
Returns
{Promise}
method stopRangingSecureBeaconsInRegion
static stopRangingSecureBeaconsInRegion: ( region: EstimoteBeaconRegion) => Promise<any>;
Stop ranging secure beacons. Available on iOS. This function has the same parameters/behaviour as EstimoteBeacons.stopRangingBeaconsInRegion.
Returns
{Promise}
method stopSecureMonitoringForRegion
static stopSecureMonitoringForRegion: ( region: EstimoteBeaconRegion) => Promise<any>;
Stop monitoring secure beacons. Available on iOS. This function has the same parameters/behaviour as EstimoteBeacons.stopMonitoringForRegion.
Parameter region
Region
Returns
{Promise}
method writeConnectedMajor
static writeConnectedMajor: (major: number) => Promise<any>;
Write major to connected Estimote Beacon. Available on Android.
``` // Example that writes 1 EstimoteBeacons.writeConnectedMajor(1);
Parameter major
number to write as new major
Returns
{Promise}
method writeConnectedMinor
static writeConnectedMinor: (minor: number) => Promise<any>;
Write minor to connected Estimote Beacon. Available on Android.
``` // Example that writes 1 EstimoteBeacons.writeConnectedMinor(1);
Parameter minor
number to write as new minor
Returns
{Promise}
method writeConnectedProximityUUID
static writeConnectedProximityUUID: (uuid: any) => Promise<any>;
Write proximity UUID to connected Estimote Beacon. Available on Android.
``` // Example that writes constant ESTIMOTE_PROXIMITY_UUID EstimoteBeacons.writeConnectedProximityUUID(ESTIMOTE_PROXIMITY_UUID);
Parameter uuid
String to write as new UUID
Returns
{Promise}
class Facebook
class Facebook {}
Facebook Use the Facebook Connect plugin to obtain access to the native FB application on iOS and Android.
Requires Cordova plugin:
cordova-plugin-facebook4
. For more info, please see the [Facebook Connect](https://github.com/jeduan/cordova-plugin-facebook4).#### Installation
To use the FB plugin, you first have to create a new Facebook App inside of the Facebook developer portal at [https://developers.facebook.com/apps](https://developers.facebook.com/apps).
[![fb-getstarted-1](/img/docs/native/Facebook/1.png)](https://developers.facebook.com/apps/)
Retrieve the
App ID
andApp Name
.[![fb-getstarted-2](/img/docs/native/Facebook/2.png)](https://developers.facebook.com/apps/)
Then type in the following command in your Terminal, where APP_ID and APP_NAME are the values from the Facebook Developer portal.
ionic plugin add cordova-plugin-facebook4 --save --variable APP_ID="123456789" --variable APP_NAME="myApplication"After, you'll need to add the native platforms you'll be using to your app in the Facebook Developer portal under your app's Settings:
[![fb-getstarted-3](/img/docs/native/Facebook/3.png)](https://developers.facebook.com/apps/)
Click
'Add Platform'
.[![fb-getstarted-4](/img/docs/native/Facebook/4.png)](https://developers.facebook.com/apps/)
At this point you'll need to open your project's [
config.xml
](https://cordova.apache.org/docs/en/latest/config_ref/index.html) file, found in the root directory of your project.Take note of the
id
for the next step:<widget id="com.mycompany.testapp" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">You can also edit the
id
to whatever you'd like it to be.#### iOS Install Under 'Bundle ID', add the
id
from yourconfig.xml
file:[![fb-getstarted-5](/img/docs/native/Facebook/5.png)](https://developers.facebook.com/apps/)
#### Android Install Under 'Google Play Package Name', add the
id
from yourconfig.xml
file:[![fb-getstarted-6](/img/docs/native/Facebook/6.png)](https://developers.facebook.com/apps/)
And that's it! You can now make calls to Facebook using the plugin.
## Events
App events allow you to understand the makeup of users engaging with your app, measure the performance of your Facebook mobile app ads, and reach specific sets of your users with Facebook mobile app ads.
- [iOS] [https://developers.facebook.com/docs/ios/app-events](https://developers.facebook.com/docs/ios/app-events) - [Android] [https://developers.facebook.com/docs/android/app-events](https://developers.facebook.com/docs/android/app-events) - [JS] Does not have an Events API, so the plugin functions are empty and will return an automatic success
Activation events are automatically tracked for you in the plugin.
Events are listed on the [insights page](https://www.facebook.com/insights/).
For tracking events, see
logEvent
andlogPurchase
.import { Facebook } from 'ionic-native';
method api
static api: (requestPath: string, permissions: string[]) => Promise<any>;
Make a call to Facebook Graph API. Can take additional permissions beyond those granted on login.
For more information see:
Calling the Graph API - https://developers.facebook.com/docs/javascript/reference/FB.api Graph Explorer - https://developers.facebook.com/tools/explorer Graph API - https://developers.facebook.com/docs/graph-api
Parameter requestPath
Graph API endpoint you want to call
Parameter permissions
List of [permissions](https://developers.facebook.com/docs/facebook-login/permissions) for this request.
Returns
{Promise} Returns a Promise that resolves with the result of the request, or rejects with an error
method appInvite
static appInvite: (options: { url: string; picture: string }) => Promise<any>;
Open App Invite dialog. Does not require login.
For more information see:
the App Invites Overview - https://developers.facebook.com/docs/app-invites/overview the App Links docs - https://developers.facebook.com/docs/applinks
Parameter options
An object containing an [App Link](https://developers.facebook.com/docs/applinks) URL to your app and an optional image URL. url: [App Link](https://developers.facebook.com/docs/applinks) to your app picture: image to be displayed in the App Invite dialog
Returns
{Promise} Returns a Promise that resolves with the result data, or rejects with an error
method browserInit
static browserInit: (appId: number, version?: string) => Promise<any>;
Browser wrapper
Parameter appId
Your Facebook AppID from their dashboard
Parameter version
The version of API you may want to use. Optional
Returns
{Promise}
method getAccessToken
static getAccessToken: () => Promise<string>;
Get a Facebook access token for using Facebook services.
Returns
{Promise} Returns a Promise that resolves with an access token, or rejects with an error
method getLoginStatus
static getLoginStatus: () => Promise<any>;
Determine if a user is logged in to Facebook and has authenticated your app. There are three possible states for a user:
1) the user is logged into Facebook and has authenticated your application (connected) 2) the user is logged into Facebook but has not authenticated your application (not_authorized) 3) the user is either not logged into Facebook or explicitly logged out of your application so it doesn't attempt to connect to Facebook and thus, we don't know if they've authenticated your application or not (unknown)
Resolves with a response like:
{authResponse: {userID: "12345678912345",accessToken: "kgkh3g42kh4g23kh4g2kh34g2kg4k2h4gkh3g4k2h4gk23h4gk2h34gk234gk2h34AndSoOn",session_Key: true,expiresIn: "5183738",sig: "..."},status: "connected"}For more information see the [Facebook docs](https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus)
Returns
{Promise} Returns a Promise that resolves with a status, or rejects with an error
method logEvent
static logEvent: ( name: string, params?: Object, valueToSum?: number) => Promise<any>;
Log an event. For more information see the Events section above.
Parameter name
Name of the event
Parameter params
An object containing extra data to log with the event
Parameter valueToSum
any value to be added to added to a sum on each event
Returns
{Promise}
method login
static login: (permissions: string[]) => Promise<FacebookLoginResponse>;
Login to Facebook to authenticate this app.
{status: "connected",authResponse: {session_key: true,accessToken: "kgkh3g42kh4g23kh4g2kh34g2kg4k2h4gkh3g4k2h4gk23h4gk2h34gk234gk2h34AndSoOn",expiresIn: 5183979,sig: "...",secret: "...",userID: "634565435"}}Parameter permissions
List of [permissions](https://developers.facebook.com/docs/facebook-login/permissions) this app has upon logging in.
Returns
{Promise} Returns a Promise that resolves with a status object if login succeeds, and rejects if login fails.
method logout
static logout: () => Promise<any>;
Logout of Facebook.
For more info see the [Facebook docs](https://developers.facebook.com/docs/reference/javascript/FB.logout)
Returns
{Promise} Returns a Promise that resolves on a successful logout, and rejects if logout fails.
method logPurchase
static logPurchase: (value: number, currency: string) => Promise<any>;
Log a purchase. For more information see the Events section above.
Parameter value
Value of the purchase.
Parameter currency
The currency, as an [ISO 4217 currency code](http://en.wikipedia.org/wiki/ISO_4217)
Returns
{Promise}
method showDialog
static showDialog: (options: any) => Promise<any>;
Show one of various Facebook dialogs. Example of options for a Share dialog:
{method: "share",href: "http://example.com",caption: "Such caption, very feed.",description: "Much description",picture: 'http://example.com/image.png'}For more options see the [Cordova plugin docs](https://github.com/jeduan/cordova-plugin-facebook4#show-a-dialog) and the [Facebook docs](https://developers.facebook.com/docs/javascript/reference/FB.ui)
Parameter options
The dialog options
Returns
{Promise} Returns a Promise that resolves with success data, or rejects with an error
class File
class File {}
File This plugin implements a File API allowing read/write access to files residing on the device.
The File class implements static convenience functions to access files and directories.
Example:
import { File } from 'ionic-native';const dataDirectory: string = File.dataDirectory;File.checkDir(dataDirectory, 'mydir').then(_ => console.log('yay')).catch(err => console.log('boooh'));This plugin is based on several specs, including : The HTML5 File API http://www.w3.org/TR/FileAPI/ The (now-defunct) Directories and System extensions Latest: http://www.w3.org/TR/2012/WD-file-system-api-20120417/ Although most of the plugin code was written when an earlier spec was current: http://www.w3.org/TR/2011/WD-file-system-api-20110419/ It also implements the FileWriter spec : http://dev.w3.org/2009/dap/file-system/file-writer.html
property applicationDirectory
static applicationDirectory: string;
Read-only directory where the application is installed.
property applicationStorageDirectory
static applicationStorageDirectory: string;
Read-only directory where the application is installed.
property cacheDirectory
static cacheDirectory: string;
Cached files that should survive app restarts. Apps should not rely on the OS to delete files in here.
property cordovaFileError
static cordovaFileError: {};
property dataDirectory
static dataDirectory: string;
Where to put app-specific data files.
property documentsDirectory
static documentsDirectory: string;
iOS: Files private to the app, but that are meaningful to other applications (e.g. Office files)
property externalApplicationStorageDirectory
static externalApplicationStorageDirectory: string;
Android: the application space on external storage.
property externalCacheDirectory
static externalCacheDirectory: string;
Android: the application cache on external storage.
property externalDataDirectory
static externalDataDirectory: string;
Android: Where to put app-specific data files on external storage.
property externalRootDirectory
static externalRootDirectory: string;
Android: the external storage (SD card) root.
property sharedDirectory
static sharedDirectory: string;
BlackBerry10: Files globally available to all apps
property syncedDataDirectory
static syncedDataDirectory: string;
iOS: Holds app-specific files that should be synced (e.g. to iCloud).
property tempDirectory
static tempDirectory: string;
iOS: Temp directory that the OS can clear at will.
method checkDir
static checkDir: (path: string, dir: string) => Promise<boolean>;
Check if a directory exists in a certain path, directory.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter dir
Name of directory to check
Returns
{Promise} Returns a Promise that resolves to true if the directory exists or rejects with an error.
method checkFile
static checkFile: (path: string, file: string) => Promise<boolean>;
Check if a file exists in a certain path, directory.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter file
Name of file to check
Returns
{Promise} Returns a Promise that resolves with a boolean or rejects with an error.
method copyDir
static copyDir: ( path: string, dirName: string, newPath: string, newDirName: string) => Promise<Entry>;
Copy a directory in various methods. If destination directory exists, will fail to copy.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter dirName
Name of directory to copy
Parameter newPath
Base FileSystem of new location
Parameter newDirName
New name of directory to copy to (leave blank to remain the same)
Returns
{Promise} Returns a Promise that resolves to the new Entry object or rejects with an error.
method copyFile
static copyFile: ( path: string, fileName: string, newPath: string, newFileName: string) => Promise<Entry>;
Copy a file in various methods. If file exists, will fail to copy.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter fileName
Name of file to copy
Parameter newPath
Base FileSystem of new location
Parameter newFileName
New name of file to copy to (leave blank to remain the same)
Returns
{Promise} Returns a Promise that resolves to an Entry or rejects with an error.
method createDir
static createDir: ( path: string, dirName: string, replace: boolean) => Promise<DirectoryEntry>;
Creates a new directory in the specific path. The replace boolean value determines whether to replace an existing directory with the same name. If an existing directory exists and the replace value is false, the promise will fail and return an error.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter dirName
Name of directory to create
Parameter replace
If true, replaces file with same name. If false returns error
Returns
{Promise} Returns a Promise that resolves with a DirectoryEntry or rejects with an error.
method createFile
static createFile: ( path: string, fileName: string, replace: boolean) => Promise<FileEntry>;
Creates a new file in the specific path. The replace boolean value determines whether to replace an existing file with the same name. If an existing file exists and the replace value is false, the promise will fail and return an error.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter fileName
Name of file to create
Parameter replace
If true, replaces file with same name. If false returns error
Returns
{Promise} Returns a Promise that resolves to a FileEntry or rejects with an error.
method getDirectory
static getDirectory: ( directoryEntry: DirectoryEntry, directoryName: string, flags: Flags) => Promise<DirectoryEntry>;
Get a directory
Parameter directoryEntry
Directory entry, obtained by resolveDirectoryUrl method
Parameter directoryName
Directory name
Parameter flags
Options
Returns
{Promise}
method getFile
static getFile: ( directoryEntry: DirectoryEntry, fileName: string, flags: Flags) => Promise<FileEntry>;
Get a file
Parameter directoryEntry
Directory entry, obtained by resolveDirectoryUrl method
Parameter fileName
File name
Parameter flags
Options
Returns
{Promise}
method getFreeDiskSpace
static getFreeDiskSpace: () => Promise<number>;
Get free disk space in Bytes
Returns
{Promise} Returns a promise that resolves with the remaining free disk space in Bytes
method listDir
static listDir: (path: string, dirName: string) => Promise<Entry[]>;
List files and directory from a given path.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter dirName
Name of directory
Returns
{Promise<Entry[]>} Returns a Promise that resolves to an array of Entry objects or rejects with an error.
method moveDir
static moveDir: ( path: string, dirName: string, newPath: string, newDirName: string) => Promise<DirectoryEntry | Entry>;
Move a directory to a given path.
Parameter path
The source path to the directory
Parameter dirName
The source directory name
Parameter newPath
The destionation path to the directory
Parameter newDirName
The destination directory name
Returns
{Promise<DirectoryEntry|Entry>} Returns a Promise that resolves to the new DirectoryEntry object or rejects with an error.
method moveFile
static moveFile: ( path: string, fileName: string, newPath: string, newFileName: string) => Promise<Entry>;
Move a file to a given path.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter fileName
Name of file to move
Parameter newPath
Base FileSystem of new location
Parameter newFileName
New name of file to move to (leave blank to remain the same)
Returns
{Promise} Returns a Promise that resolves to the new Entry or rejects with an error.
method readAsArrayBuffer
static readAsArrayBuffer: (path: string, file: string) => Promise<ArrayBuffer>;
Read file and return data as an ArrayBuffer.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter file
Name of file, relative to path.
Returns
{Promise} Returns a Promise that resolves with the contents of the file as ArrayBuffer or rejects with an error.
method readAsBinaryString
static readAsBinaryString: (path: string, file: string) => Promise<string>;
Read file and return data as a binary data.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter file
Name of file, relative to path.
Returns
{Promise} Returns a Promise that resolves with the contents of the file as string rejects with an error.
method readAsDataURL
static readAsDataURL: (path: string, file: string) => Promise<string>;
Read file and return data as a base64 encoded data url. A data url is of the form: data:[][;base64],
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter file
Name of file, relative to path.
Returns
{Promise} Returns a Promise that resolves with the contents of the file as data URL or rejects with an error.
method readAsText
static readAsText: (path: string, file: string) => Promise<string>;
Read the contents of a file as text.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter file
Name of file, relative to path.
Returns
{Promise} Returns a Promise that resolves with the contents of the file as string or rejects with an error.
method removeDir
static removeDir: (path: string, dirName: string) => Promise<RemoveResult>;
Remove a directory at a given path.
Parameter path
The path to the directory
Parameter dirName
The directory name
Returns
{Promise} Returns a Promise that resolves to a RemoveResult or rejects with an error.
method removeFile
static removeFile: (path: string, fileName: string) => Promise<RemoveResult>;
Removes a file from a desired location.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter fileName
Name of file to remove
Returns
{Promise} Returns a Promise that resolves to a RemoveResult or rejects with an error.
method removeRecursively
static removeRecursively: ( path: string, dirName: string) => Promise<RemoveResult>;
Removes all files and the directory from a desired location.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter dirName
Name of directory
Returns
{Promise} Returns a Promise that resolves with a RemoveResult or rejects with an error.
method resolveDirectoryUrl
static resolveDirectoryUrl: (directoryUrl: string) => Promise<DirectoryEntry>;
Resolves a local directory url
Parameter directoryUrl
directory system url
Returns
{Promise}
method resolveLocalFilesystemUrl
static resolveLocalFilesystemUrl: (fileUrl: string) => Promise<Entry>;
Resolves a local file system URL
Parameter fileUrl
file system url
Returns
{Promise}
method writeExistingFile
static writeExistingFile: ( path: string, fileName: string, text: string | Blob) => Promise<void>;
Write to an existing file.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter fileName
path relative to base path
Parameter text
content or blob to write
Returns
{Promise} Returns a Promise that resolves or rejects with an error.
method writeFile
static writeFile: ( path: string, fileName: string, text: string | Blob | ArrayBuffer, options?: WriteOptions) => Promise<any>;
Write a new file to the desired location.
Parameter path
Base FileSystem. Please refer to the iOS and Android filesystems above
Parameter fileName
path relative to base path
Parameter text
content or blob to write
Parameter options
replace file if set to true. See WriteOptions for more information.
Returns
{Promise} Returns a Promise that resolves to updated file entry or rejects with an error.
class FileChooser
class FileChooser {}
FileChooser
Opens the file picker on Android for the user to select a file, returns a file URI.
import {FileChooser} from 'ionic-native';FileChooser.open().then(uri => console.log(uri)).catch(e => console.log(e));
method open
static open: () => Promise<string>;
Open a file
Returns
{Promise}
class FileOpener
class FileOpener {}
FileOpener This plugin will open a file on your device file system with its default application.
import {FileOpener} from 'ionic-native';
method appIsInstalled
static appIsInstalled: (packageId: string) => Promise<any>;
Check if an app is already installed
Parameter packageId
Package ID
Returns
{Promise}
method open
static open: (filePath: string, fileMIMEType: string) => Promise<any>;
Open an file
Parameter filePath
File Path
Parameter fileMIMEType
File MIME Type
Returns
{Promise}
method uninstall
static uninstall: (packageId: string) => Promise<any>;
Uninstalls a package
Parameter packageId
Package ID
Returns
{Promise}
class FilePath
class FilePath {}
FilePath
This plugin allows you to resolve the native filesystem path for Android content URIs and is based on code in the aFileChooser library.
import {FilePath} from 'ionic-native';FilePath.resolveNativePath(path).then(filePath => console.log(filePath)).catch(err => console.log(err));
method resolveNativePath
static resolveNativePath: (path: string) => Promise<string>;
Resolve native path for given content URL/path.
Parameter path
Content URL/path.
Returns
{Promise}
class FingerprintAIO
class FingerprintAIO {}
FingerprintAIO Use simple fingerprint authentication on Android and iOS. Requires Cordova plugin: cordova-plugin-fingerprint-aio. For more info about plugin, vist: https://github.com/NiklasMerz/cordova-plugin-fingerprint-aio
import { FingerprintAIO } from 'ionic-native';FingerprintAIO.show({clientId: "Fingerprint-Demo",clientSecret: "password", //Only necessary for AndroiddisableBackup:true //Only for Android(optional)}).then((result: any) => console.log(any)).catch((error: any) => console.log(error));FingerprintOptions
Modifiers
@beta
method isAvailable
static isAvailable: () => Promise<any>;
Check if fingerprint authentication is available {Promise} Returns a promise with result
method show
static show: (options: FingerprintOptions) => Promise<any>;
Show authentication dialogue
Parameter options
options for platform specific fingerprint API {Promise} Returns a promise that resolves when authentication was successfull
class Firebase
class Firebase {}
Firebase This plugin brings push notifications, analytics, event tracking, crash reporting and more from Google Firebase to your Cordova project! Android and iOS supported (including iOS 10).
import { Firebase } from 'ionic-native';Firebase.getToken().then(token => console.log(`The token is ${token}`)) // save the token server-side and use it to push notifications to this device.catch(error => console.error('Error getting token', error));Firebase.onTokenRefresh().subscribe((token: string) => console.log(`Got a new token ${token}`));
method activateFetched
static activateFetched: () => Promise<any>;
Activate the Remote Config fetched config {Promise}
method fetch
static fetch: (cacheExpirationSeconds?: number) => Promise<any>;
Fetch Remote Config parameter values for your app
Parameter cacheExpirationSeconds
{Promise}
method getBadgeNumber
static getBadgeNumber: () => Promise<any>;
Get icon badge number {Promise}
method getByteArray
static getByteArray: (key: string, namespace?: string) => Promise<any>;
Retrieve a Remote Config byte array
Parameter key
Parameter namespace
{Promise}
method getInfo
static getInfo: () => Promise<any>;
Get the current state of the FirebaseRemoteConfig singleton object {Promise}
method getToken
static getToken: () => Promise<any>;
Get the device token {Promise}
method getValue
static getValue: (key: string, namespace?: string) => Promise<any>;
Retrieve a Remote Config value
Parameter key
Parameter namespace
{Promise}
method grantPermission
static grantPermission: () => Promise<any>;
Grant permission to recieve push notifications {Promise}
method hasPermission
static hasPermission: () => Promise<any>;
Check permission to recieve push notifications {Promise}
method logEvent
static logEvent: (type: string, data: any) => Promise<any>;
Log an event using Analytics
Parameter type
Parameter data
{Promise}
method onNotificationOpen
static onNotificationOpen: () => Observable<any>;
Get notified when the user opens a notification {Observable}
method onTokenRefresh
static onTokenRefresh: () => Observable<any>;
Get notified when a token is refreshed {Observable}
method setBadgeNumber
static setBadgeNumber: (badgeNumber: number) => Promise<any>;
Set icon badge number. Set to 0 to clear the badge.
Parameter badgeNumber
{Promise}
method setConfigSettings
static setConfigSettings: (settings: any) => Promise<any>;
Change the settings for the FirebaseRemoteConfig object's operations
Parameter settings
{Promise}
method setDefaults
static setDefaults: (defaults: any, namespace: string) => Promise<any>;
Set defaults in the Remote Config
Parameter defaults
Parameter namespace
{Promise}
method setScreenName
static setScreenName: (name: string) => Promise<any>;
Set the name of the current screen in Analytics
Parameter name
Screen name {Promise}
method setUserId
static setUserId: (userId: string) => Promise<any>;
Set a user id for use in Analytics
Parameter userId
{Promise}
method setUserProperty
static setUserProperty: (name: string, value: string) => Promise<any>;
Set a user property for use in Analytics
Parameter name
Parameter value
{Promise}
method subscribe
static subscribe: (topic: string) => Promise<any>;
Subscribe to a topic
Parameter topic
{Promise}
method unsubscribe
static unsubscribe: (topic: string) => Promise<any>;
Unsubscribe from a topic
Parameter topic
{Promise}
class Flashlight
class Flashlight {}
Flashlight This plugin allows you to switch the flashlight / torch of the device on and off.
Requires Cordova plugin:
cordova-plugin-flashlight
. For more info, please see the [Flashlight plugin docs](https://github.com/EddyVerbruggen/Flashlight-PhoneGap-Plugin).import { Flashlight } from 'ionic-native';
method available
static available: () => Promise<boolean>;
Checks if the flashlight is available
Returns
{Promise} Returns a promise that resolves with a boolean stating if the flashlight is available.
method isSwitchedOn
static isSwitchedOn: () => boolean;
Checks if the flashlight is turned on.
Returns
{boolean}
method switchOff
static switchOff: () => Promise<boolean>;
Switches the flashlight off
Returns
{Promise}
method switchOn
static switchOn: () => Promise<boolean>;
Switches the flashlight on
Returns
{Promise}
method toggle
static toggle: () => Promise<any>;
Toggles the flashlight
Returns
{Promise}
class Geocoder
class Geocoder {}
method geocode
static geocode: (request: GeocoderRequest) => Promise<GeocoderResult[] | any>;
Converts position to address and vice versa
Parameter request
Request object with either an address or a position
Returns
{Promise<GeocoderResult[]>}
class Geofence
class Geofence {}
Geofence Monitors circular geofences around latitude/longitude coordinates, and sends a notification to the user when the boundary of a geofence is crossed. Notifications can be sent when the user enters and/or exits a geofence. Geofences persist after device reboot. Geofences will be monitored even when the app is not running.
import { Geofence } from 'ionic-native';import { Platform } from 'ionic-angular'...constructor(private platform: Platform) {this.platform.ready().then(() => {// initialize the pluginGeofence.initialize().then(// resolved promise does not return a value() => console.log('Geofence Plugin Ready'),(err) => console.log(err))})}private addGeofence() {//options describing geofencelet fence = {id: "69ca1b88-6fbe-4e80-a4d4-ff4d3748acdb", //any unique IDlatitude: 37.285951, //center of geofence radiuslongitude: -121.936650,radius: 100, //radius to edge of geofencetransitionType: 3, //see 'Transition Types' belownotification: { //notification settingsid: 1, //any unique IDtitle: "You crossed a fence", //notification titletext: "You just arrived to Gliwice city center.", //notification bodyopenAppOnClick: true //open app when notification is tapped}}Geofence.addOrUpdate(fence).then(() => console.log('Geofence added'),(err) => console.log('Geofence failed to add'));}### Transition Types ### Transition type specifies whether the geofence should trigger when the user enters and/or leaves the geofence.
#### Supported values #### - 1: Enter - 2: Leave - 3: Both
### Defining a Geofence ### Geofences are defined by an object that is passed to
addOrUpdate()
. Object properties are: - id: Any unique ID for the geofence. This ID is used to remove and update a geofence - latitude: Latitude coordinate of the center of the geofence radius - longitude: Latitude coordinate of the center of the geofence radius - radius: Radius from the center to the edge of the geofence - transitionType: Type of geofence transition to monitor for. See 'Transition Types' above - notification: Object. Options for defining the notification sent when a geofence is crossed - id: Any unique ID - title: Notification title - text: Notification body - openAppOnClick: Boolean. Whether to open the app when the notification is tapped by the user### Troubleshooting ### #### I get compile errors when I run
ionic build ios
orionic run ios
. #### This could be caused by the Cordova project directory in/platforms/ios
not being named correctly. Try runningionic platform rm <platform>
then runionic platform add <platform>
to recreate the platform directories.
property onTrasitionReceived
static onTrasitionReceived: Function;
property TransitionType
static TransitionType: { ENTER: number; EXIT: number; BOTH: number };
method addOrUpdate
static addOrUpdate: (geofences: Object | Array<Object>) => Promise<void>;
Adds a new geofence or array of geofences. For geofence object, see above.
Returns
{Promise}
method getWatched
static getWatched: () => Promise<string>;
Returns an array of geofences currently being monitored.
Returns
{Promise<Array>}
method initialize
static initialize: () => Promise<void>;
Initializes the plugin. User will be prompted to allow the app to use location and notifications.
Returns
{Promise}
method onNotificationClicked
static onNotificationClicked: () => Observable<any>;
Called when the user clicks a geofence notification. iOS and Android only.
Returns
{Observable}
method onTransitionReceived
static onTransitionReceived: () => Observable<any>;
Called when a geofence is crossed in the direction specified by
TransitType
.Returns
{Observable}
method remove
static remove: (geofenceId: string | Array<string>) => Promise<void>;
Removes a geofence or array of geofences.
geofenceID
corresponds to one or more IDs specified when the geofence was created.Returns
{Promise}
method removeAll
static removeAll: () => Promise<void>;
Removes all geofences.
Returns
{Promise}
class Geolocation
class Geolocation {}
Geolocation This plugin provides information about the device's location, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs.
This API is based on the W3C Geolocation API Specification, and only executes on devices that don't already provide an implementation.
import { Geolocation } from 'ionic-native';Geolocation.getCurrentPosition().then((resp) => {// resp.coords.latitude// resp.coords.longitude}).catch((error) => {console.log('Error getting location', error);});let watch = Geolocation.watchPosition();watch.subscribe((data) => {// data can be a set of coordinates, or an error (if an error occurred).// data.coords.latitude// data.coords.longitude});Coordinates Geoposition PositionError GeolocationOptions
method getCurrentPosition
static getCurrentPosition: ( options?: GeolocationOptions) => Promise<Geoposition>;
Get the device's current position.
Parameter options
The [geolocation options](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions).
Returns
{Promise} Returns a Promise that resolves with the [position](https://developer.mozilla.org/en-US/docs/Web/API/Position) of the device, or rejects with an error.
method watchPosition
static watchPosition: (options?: GeolocationOptions) => Observable<Geoposition>;
Watch the current device's position. Clear the watch by unsubscribing from Observable changes.
var subscription = Geolocation.watchPosition().filter((p) => p.coords !== undefined) //Filter Out Errors.subscribe(position => {console.log(position.coords.longitude + ' ' + position.coords.latitude);});// To stop notificationssubscription.unsubscribe();Parameter options
The [geolocation options](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions).
Returns
{Observable} Returns an Observable that notifies with the [position](https://developer.mozilla.org/en-US/docs/Web/API/Position) of the device, or errors.
class Globalization
class Globalization {}
Globalization
import { Globalization } from 'ionic-native';
method dateToString
static dateToString: ( date: Date, options: { formatLength: string; selector: string }) => Promise<{ value: string }>;
Converts date to string
Parameter date
Date you wish to convert
Parameter options
Options for the converted date. Length, selector.
Returns
{Promise<{value: string}>} Returns a promise when the date has been converted.
method getCurrencyPattern
static getCurrencyPattern: ( currencyCode: string) => Promise<{ pattern: string; code: string; fraction: number; rounding: number; decimal: number; grouping: string;}>;
Returns a pattern string to format and parse currency values according to the client's user preferences and ISO 4217 currency code.
Parameter currencyCode
Currency Code.A
Returns
{Promise<{ pattern: string, code: string, fraction: number, rounding: number, decimal: number, grouping: string }>}
method getDateNames
static getDateNames: (options: { type: string; item: string;}) => Promise<{ value: Array<string> }>;
Returns an array of the names of the months or days of the week, depending on the client's user preferences and calendar.
Parameter options
Object with type (narrow or wide) and item (month or days).
Returns
{Promise<{value: Array}>} Returns a promise.
method getDatePattern
static getDatePattern: (options: { formatLength: string; selector: string;}) => Promise<{ pattern: string }>;
Returns a pattern string to format and parse dates according to the client's user preferences.
Parameter options
Object with the format length and selector
Returns
{Promise<{pattern: string}>} Returns a promise.
method getFirstDayOfWeek
static getFirstDayOfWeek: () => Promise<{ value: string }>;
Returns the first day of the week according to the client's user preferences and calendar.
Returns
{Promise<{value: string}>} returns a promise with the value
method getLocaleName
static getLocaleName: () => Promise<{ value: string }>;
Returns the BCP 47 compliant locale identifier string to the successCallback with a properties object as a parameter.
Returns
{Promise<{value: string}>}
method getNumberPattern
static getNumberPattern: (options: { type: string;}) => Promise<{ pattern: string; symbol: string; fraction: number; rounding: number; positive: string; negative: string; decimal: string; grouping: string;}>;
Returns a pattern string to format and parse numbers according to the client's user preferences.
Parameter options
Can be decimal, percent, or currency.
Returns
{Promise<{ pattern: string, symbol: string, fraction: number, rounding: number, positive: string, negative: string, decimal: string, grouping: string }>}
method getPreferredLanguage
static getPreferredLanguage: () => Promise<{ value: string }>;
Returns the BCP-47 compliant language identifier tag to the successCallback with a properties object as a parameter. That object should have a value property with a String value.
Returns
{Promise<{value: string}>}
method isDayLightSavingsTime
static isDayLightSavingsTime: (date: Date) => Promise<{ dst: string }>;
Indicates whether daylight savings time is in effect for a given date using the client's time zone and calendar.
Parameter date
Date to process
Returns
{Promise<{dst: string}>} reutrns a promise with the value
method numberToString
static numberToString: ( numberToConvert: number, options: { type: string }) => Promise<{ value: string }>;
Returns a number formatted as a string according to the client's user preferences.
Parameter numberToConvert
The number to convert
Parameter options
Object with property
type
that can be set to: decimal, percent, or currency.
method stringToDate
static stringToDate: ( dateString: string, options: { formatLength: string; selector: string }) => Promise<{ year: number; month: number; day: number; hour: number; minute: number; second: number; millisecond: number;}>;
Parses a date formatted as a string, according to the client's user preferences and calendar using the time zone of the client, and returns the corresponding date object.
Parameter dateString
Date as a string to be converted
Parameter options
Options for the converted date. Length, selector.
Returns
{Promise<{ year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number }>} Returns a promise when the date has been converted.
method stringToNumber
static stringToNumber: ( stringToConvert: string, options: { type: string }) => Promise<{ value: number | string }>;
Parameter stringToConvert
String you want to conver to a number
Parameter options
The type of number you want to return. Can be decimal, percent, or currency.
Returns
{Promise<{ value: number | string }>} Returns a promise with the value.
class GoogleAnalytics
class GoogleAnalytics {}
Google Analytics This plugin connects to Google's native Universal Analytics SDK Prerequisites: - A Cordova 3.0+ project for iOS and/or Android - A Mobile App property through the Google Analytics Admin Console - (Android) Google Play Services SDK installed via [Android SDK Manager](https://developer.android.com/sdk/installing/adding-packages.html)
import { GoogleAnalytics } from 'ionic-native';GoogleAnalytics.startTrackerWithId('YOUR_TRACKER_ID').then(() => {console.log('Google analytics is ready now');// Tracker is ready// You can now track pages or set additional information such as AppVersion or UserId}).catch(e => console.log('Error starting GoogleAnalytics', e));
method addCustomDimension
static addCustomDimension: (key: number, value: string) => Promise<any>;
Add a Custom Dimension https://developers.google.com/analytics/devguides/platform/customdimsmets
Parameter key
Parameter value
Returns
{Promise}
method addTransaction
static addTransaction: ( id: string, affiliation: string, revenue: number, tax: number, shipping: number, currencyCode: string) => Promise<any>;
Add a Transaction (Ecommerce) https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#addTrans
Parameter id
Parameter affiliation
Parameter revenue
Parameter tax
Parameter shipping
Parameter currencyCode
Returns
{Promise}
method addTransactionItem
static addTransactionItem: ( id: string, name: string, sku: string, category: string, price: number, quantity: number, currencyCode: string) => Promise<any>;
Add a Transaction Item (Ecommerce) https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#addItem
Parameter id
Parameter name
Parameter sku
Parameter category
Parameter price
Parameter quantity
Parameter currencyCode
Returns
{Promise}
method debugMode
static debugMode: () => Promise<any>;
Enable verbose logging
Returns
{Promise}
method enableUncaughtExceptionReporting
static enableUncaughtExceptionReporting: (shouldEnable: boolean) => Promise<any>;
Enable/disable automatic reporting of uncaught exceptions
Parameter shouldEnable
Returns
{Promise}
method setAllowIDFACollection
static setAllowIDFACollection: (allow: boolean) => Promise<any>;
Enabling Advertising Features in Google Analytics allows you to take advantage of Remarketing, Demographics & Interests reports, and more
Parameter allow
Returns
{Promise}
method setAnonymizeIp
static setAnonymizeIp: (anonymize: boolean) => Promise<any>;
Set a anonymize Ip address
Parameter anonymize
Set to true to anonymize the IP Address
Returns
{Promise}
method setAppVersion
static setAppVersion: (appVersion: string) => Promise<any>;
Sets the app version
Parameter appVersion
App version
Returns
{Promise}
method setOptOut
static setOptOut: (optout: boolean) => Promise<any>;
Set OptOut
Parameter optout
Returns
{Promise}
method setUserId
static setUserId: (id: string) => Promise<any>;
Set a UserId https://developers.google.com/analytics/devguides/collection/analyticsjs/user-id
Parameter id
User ID
Returns
{Promise}
method startTrackerWithId
static startTrackerWithId: (id: string, interval?: number) => Promise<any>;
In your 'deviceready' handler, set up your Analytics tracker. https://developers.google.com/analytics/devguides/collection/analyticsjs/
Parameter id
Your Google Analytics Mobile App property
Parameter interval
Optional dispatch period in seconds. Defaults to 30.
Returns
{Promise}
method trackEvent
static trackEvent: ( category: string, action: string, label?: string, value?: number, newSession?: boolean) => Promise<any>;
Track an event https://developers.google.com/analytics/devguides/collection/analyticsjs/events
Parameter category
Parameter action
Parameter label
Parameter value
Parameter newSession
Set to true to create a new session
Returns
{Promise}
method trackException
static trackException: (description: string, fatal: boolean) => Promise<any>;
Track an exception
Parameter description
Parameter fatal
Returns
{Promise}
method trackMetric
static trackMetric: (key: string, value?: any) => Promise<any>;
Track custom metric
Parameter key
Parameter value
Returns
{Promise}
method trackTiming
static trackTiming: ( category: string, intervalInMilliseconds: number, variable: string, label: string) => Promise<any>;
Track User Timing (App Speed)
Parameter category
Parameter intervalInMilliseconds
Parameter variable
Parameter label
Returns
{Promise}
method trackView
static trackView: ( title: string, campaignUrl?: string, newSession?: boolean) => Promise<any>;
Track a screen https://developers.google.com/analytics/devguides/collection/analyticsjs/screens
Parameter title
Screen title
Parameter campaignUrl
Campaign url for measuring referrals
Parameter newSession
Set to true to create a new session
Returns
{Promise}
class GoogleMap
class GoogleMap {}
Google Maps This plugin uses the native Google Maps SDK
import {GoogleMap,GoogleMapsEvent,GoogleMapsLatLng,CameraPosition,GoogleMapsMarkerOptions,GoogleMapsMarker,GoogleMapsMapTypeId} from 'ionic-native';export class MapPage {constructor() {}// Load map only after view is initializengAfterViewInit() {this.loadMap();}loadMap() {// make sure to create following structure in your view.html file// and add a height (for example 100%) to it, else the map won't be visible// <ion-content>// <div #map id="map" style="height:100%;"></div>// </ion-content>// create a new map by passing HTMLElementlet element: HTMLElement = document.getElementById('map');let map = new GoogleMap(element);// create LatLng objectlet ionic: GoogleMapsLatLng = new GoogleMapsLatLng(43.0741904,-89.3809802);// create CameraPositionlet position: CameraPosition = {target: ionic,zoom: 18,tilt: 30};// listen to MAP_READY eventmap.one(GoogleMapsEvent.MAP_READY).then(() => {// move the map's camera to positionmap.moveCamera(position); // works on iOS and Android});// create new markerlet markerOptions: GoogleMapsMarkerOptions = {position: ionic,title: 'Ionic'};map.addMarker(markerOptions).then((marker: GoogleMapsMarker) => {marker.showInfoWindow();});}});}
constructor
constructor(element: string | HTMLElement, options?: any);
method addCircle
addCircle: (options: GoogleMapsCircleOptions) => Promise<GoogleMapsCircle | any>;
Returns
{Promise<GoogleMapsCircle | any>}
method addEventListener
addEventListener: (eventName: string) => Observable<any>;
Adds an event listener.
Returns
{Observable}
method addGroundOverlay
addGroundOverlay: ( options: GoogleMapsGroundOverlayOptions) => Promise<GoogleMapsGroundOverlay | any>;
Returns
{Promise<GoogleMapsGroundOverlay | any>}
method addKmlOverlay
addKmlOverlay: ( options: GoogleMapsKmlOverlayOptions) => Promise<GoogleMapsKmlOverlay | any>;
Returns
{Promise<GoogleMapsKmlOverlay | any>}
method addListenerOnce
addListenerOnce: (eventName: string) => Promise<any>;
Adds an event listener that works once.
Returns
{Promise}
method addMarker
addMarker: (options: GoogleMapsMarkerOptions) => Promise<GoogleMapsMarker | any>;
Returns
{Promise<GoogleMapsMarker | any>}
method addPolygon
addPolygon: ( options: GoogleMapsPolygonOptions) => Promise<GoogleMapsPolygon | any>;
Returns
{Promise<GoogleMapsPolygon | any>}
method addPolyline
addPolyline: ( options: GoogleMapsPolylineOptions) => Promise<GoogleMapsPolyline | any>;
Returns
{Promise<GoogleMapsPolyline | any>}
method addTileOverlay
addTileOverlay: ( options: GoogleMapsTileOverlayOptions) => Promise<GoogleMapsTileOverlay | any>;
Returns
{Promise<GoogleMapsTileOverlay | any>}
method animateCamera
animateCamera: (animateCameraOptions: AnimateCameraOptions) => Promise<any>;
Returns
{Promise}
method clear
clear: () => void;
method closeDialog
closeDialog: () => void;
method empty
empty: () => void;
Clears all stored values
method fromLatLngToPoint
fromLatLngToPoint: (latLng: GoogleMapsLatLng, point: any) => Promise<any>;
Returns
{Promise}
method fromPointToLatLng
fromPointToLatLng: ( point: any, latLng: GoogleMapsLatLng) => Promise<GoogleMapsLatLng>;
Returns
{Promise}
method get
get: (key: string) => any;
Gets a value
Parameter key
method getCameraPosition
getCameraPosition: () => Promise<CameraPosition>;
Get the position of the camera.
Returns
{Promise}
method getLicenseInfo
getLicenseInfo: () => Promise<string>;
method getMyLocation
getMyLocation: (options?: MyLocationOptions) => Promise<MyLocation>;
Get the location of the user.
Returns
{Promise}
method getVisibleRegion
getVisibleRegion: () => Promise<VisibleRegion>;
Get the visible region.
Returns
{Promise}
method isAvailable
static isAvailable: () => Promise<boolean>;
Checks if a map object has been created and is available.
Returns
{Promise}
method moveCamera
moveCamera: (cameraPosition: CameraPosition) => Promise<any>;
Returns
{Promise}
method on
on: (eventName: string) => Observable<any>;
Listen to a map event.
Returns
{Observable}
method one
one: (eventName: string) => Promise<any>;
Listen to a map event only once.
Returns
{Promise}
method panBy
panBy: () => void;
method refreshLayout
refreshLayout: () => void;
method remove
remove: () => void;
method set
set: (key: string, value: any) => void;
Sets a value
Parameter key
Parameter value
method setAllGesturesEnabled
setAllGesturesEnabled: (enabled: boolean) => void;
method setBackgroundColor
setBackgroundColor: (backgroundColor: string) => void;
method setCenter
setCenter: (latLng: GoogleMapsLatLng) => void;
method setClickable
setClickable: (isClickable: boolean) => void;
method setCompassEnabled
setCompassEnabled: (enabled: boolean) => void;
method setDebuggable
setDebuggable: (isDebuggable: boolean) => void;
method setDiv
setDiv: (domNode: HTMLElement) => void;
method setIndoorEnabled
setIndoorEnabled: (enabled: boolean) => void;
method setMapTypeId
setMapTypeId: (mapTypeId: string) => void;
method setMyLocationEnabled
setMyLocationEnabled: (enabled: boolean) => void;
method setOptions
setOptions: (options: any) => void;
method setPadding
setPadding: ( top?: number, right?: number, bottom?: number, left?: number) => void;
method setTilt
setTilt: (tiltLevel: number) => void;
method setTrafficEnabled
setTrafficEnabled: (enabled: boolean) => void;
method setVisible
setVisible: (visible: boolean) => void;
method setZoom
setZoom: (zoomLevel: number) => void;
method showDialog
showDialog: () => void;
method toDataURL
toDataURL: () => Promise<any>;
Returns
{Promise}
class GoogleMapsCircle
class GoogleMapsCircle {}
constructor
constructor(_objectInstance: any);
method addEventListener
addEventListener: (eventName: string) => Observable<any>;
Adds an event listener.
Returns
{Observable}
method addListenerOnce
addListenerOnce: (eventName: string) => Promise<any>;
Adds an event listener that works once.
Returns
{Promise}
method empty
empty: () => void;
Clears all stored values
method get
get: (key: string) => any;
Gets a value
Parameter key
method getCenter
getCenter: () => GoogleMapsLatLng;
method getMap
getMap: () => GoogleMap;
method getRadius
getRadius: () => number;
method getStrokeColor
getStrokeColor: () => string;
method getVisible
getVisible: () => boolean;
method getZIndex
getZIndex: () => number;
method on
on: (eventName: string) => Observable<any>;
Listen to a map event.
Returns
{Observable}
method one
one: (eventName: string) => Promise<any>;
Listen to a map event only once.
Returns
{Promise}
method remove
remove: () => void;
method set
set: (key: string, value: any) => void;
Sets a value
Parameter key
Parameter value
method setCenter
setCenter: (latLng: GoogleMapsLatLng) => void;
method setFillColor
setFillColor: (fillColor: string) => void;
method setRadius
setRadius: (radius: number) => void;
method setStrokeColor
setStrokeColor: (strokeColor: string) => void;
method setStrokeWidth
setStrokeWidth: (strokeWidth: number) => void;
method setVisible
setVisible: (visible: boolean) => void;
method setZIndex
setZIndex: (zIndex: number) => void;
class GoogleMapsGroundOverlay
class GoogleMapsGroundOverlay {}
constructor
constructor(_objectInstance: any);
method addEventListener
addEventListener: (eventName: string) => Observable<any>;
Adds an event listener.
Returns
{Observable}
method addListenerOnce
addListenerOnce: (eventName: string) => Promise<any>;
Adds an event listener that works once.
Returns
{Promise}
method empty
empty: () => void;
Clears all stored values
method get
get: (key: string) => any;
Gets a value
Parameter key
method getBearing
getBearing: () => number;
method getOpacity
getOpacity: () => number;
method getVisible
getVisible: () => boolean;
method on
on: (eventName: string) => Observable<any>;
Listen to a map event.
Returns
{Observable}
method one
one: (eventName: string) => Promise<any>;
Listen to a map event only once.
Returns
{Promise}
method remove
remove: () => void;
method set
set: (key: string, value: any) => void;
Sets a value
Parameter key
Parameter value
method setBearing
setBearing: (bearing: number) => void;
method setImage
setImage: (image: string) => void;
method setOpacity
setOpacity: (opacity: number) => void;
method setVisible
setVisible: (visible: boolean) => void;
class GoogleMapsKmlOverlay
class GoogleMapsKmlOverlay {}
constructor
constructor(_objectInstance: any);
method addEventListener
addEventListener: (eventName: string) => Observable<any>;
Adds an event listener.
Returns
{Observable}
method addListenerOnce
addListenerOnce: (eventName: string) => Promise<any>;
Adds an event listener that works once.
Returns
{Promise}
method empty
empty: () => void;
Clears all stored values
method get
get: (key: string) => any;
Gets a value
Parameter key
method getOverlays
getOverlays: () => Array< GoogleMapsPolyline | GoogleMapsPolygon | GoogleMapsMarker>;
method on
on: (eventName: string) => Observable<any>;
Listen to a map event.
Returns
{Observable}
method one
one: (eventName: string) => Promise<any>;
Listen to a map event only once.
Returns
{Promise}
method remove
remove: () => void;
method set
set: (key: string, value: any) => void;
Sets a value
Parameter key
Parameter value
class GoogleMapsLatLng
class GoogleMapsLatLng {}
constructor
constructor(lat: number, lng: number);
property lat
lat: number;
property lng
lng: number;
method equals
equals: (other: GoogleMapsLatLng) => boolean;
method toString
toString: () => string;
method toUrlValue
toUrlValue: (precision?: number) => string;
class GoogleMapsLatLngBounds
class GoogleMapsLatLngBounds {}
constructor
constructor( southwestOrArrayOfLatLng: GoogleMapsLatLng | GoogleMapsLatLng[], northeast?: GoogleMapsLatLng);
property northeast
northeast: GoogleMapsLatLng;
property southwest
southwest: GoogleMapsLatLng;
property type
type: string;
method contains
contains: (LatLng: GoogleMapsLatLng) => boolean;
method extend
extend: (LatLng: GoogleMapsLatLng) => void;
method getCenter
getCenter: () => GoogleMapsLatLng;
method toString
toString: () => string;
method toUrlValue
toUrlValue: (precision?: number) => string;
class GoogleMapsMarker
class GoogleMapsMarker {}
constructor
constructor(_objectInstance: any);
method addEventListener
addEventListener: (eventName: string) => Observable<any>;
Adds an event listener.
Returns
{Observable}
method addListenerOnce
addListenerOnce: (eventName: string) => Promise<any>;
Adds an event listener that works once.
Returns
{Promise}
method empty
empty: () => void;
Clears all stored values
method get
get: (key: string) => any;
Gets a value
Parameter key
method getHashCode
getHashCode: () => string;
Return the marker hash code. {string} Marker hash code
method getMap
getMap: () => GoogleMap;
Return the map instance. {GoogleMap}
method getOpacity
getOpacity: () => number;
Return the marker opacity. {number} Opacity
method getPosition
getPosition: () => Promise<GoogleMapsLatLng>;
Return the marker position. {Promise}
method getRotation
getRotation: () => number;
Return the marker rotation angle. {number}
method getSnippet
getSnippet: () => string;
Return the snippet strings. {string}
method getTitle
getTitle: () => string;
Return the title strings. {string}
method hideInfoWindow
hideInfoWindow: () => number;
Hide the infoWindow of the marker. {number}
method isDraggable
isDraggable: () => boolean;
Return true if the marker drag is enabled. {boolean}
method isVisible
isVisible: () => boolean;
Return true if the marker is visible
method on
on: (eventName: string) => Observable<any>;
Listen to a map event.
Returns
{Observable}
method one
one: (eventName: string) => Promise<any>;
Listen to a map event only once.
Returns
{Promise}
method remove
remove: () => void;
Remove the marker completely.
method set
set: (key: string, value: any) => void;
Sets a value
Parameter key
Parameter value
method setAnimation
setAnimation: (animation: string) => void;
Specify the animation either
DROP
orBOUNCE
Parameter animation
method setDraggable
setDraggable: (draggable: boolean) => void;
Set true if you allows all users to drag the marker.
Parameter draggable
method setFlat
setFlat: (flat: boolean) => void;
Set true if you want to be flat marker.
Parameter flat
method setIcon
setIcon: (icon: GoogleMapsMarkerIcon) => void;
Change icon url and/or size
Parameter icon
method setIconAnchor
setIconAnchor: (x: number, y: number) => void;
Change the info window anchor. This defaults to 50% from the left of the image and at the bottom of the image.
Parameter x
Parameter y
method setInfoWindowAnchor
setInfoWindowAnchor: (x: number, y: number) => void;
Change the info window anchor. This defaults to 50% from the left of the image and at the top of the image.
Parameter x
Parameter y
method setOpacity
setOpacity: (alpha: number) => void;
Change the marker opacity.
Parameter alpha
Opacity
method setPosition
setPosition: (latLng: GoogleMapsLatLng) => void;
Set the marker position.
Parameter latLng
method setRotation
setRotation: (rotation: number) => void;
Set the marker rotation angle.
Parameter rotation
method setSnippet
setSnippet: (snippet: string) => void;
Change snippet of the infoWindow.
Parameter snippet
method setTitle
setTitle: (title: string) => void;
Change title of the infoWindow.
Parameter title
method setVisible
setVisible: (visible: boolean) => void;
Set false if you want to hide the marker.
Parameter visible
method setZIndex
setZIndex: () => number;
iOS only, Plugin Version >= 1.3.3 Higher zIndex value overlays will be drawn on top of lower zIndex value tile layers and overlays. (You're able to run this on Android, but it will have no effect) {number}
method showInfoWindow
showInfoWindow: () => number;
Show the infoWindow of the marker. {number}
class GoogleMapsPolygon
class GoogleMapsPolygon {}
constructor
constructor(_objectInstance: any);
method addEventListener
addEventListener: (eventName: string) => Observable<any>;
Adds an event listener.
Returns
{Observable}
method addListenerOnce
addListenerOnce: (eventName: string) => Promise<any>;
Adds an event listener that works once.
Returns
{Promise}
method empty
empty: () => void;
Clears all stored values
method get
get: (key: string) => any;
Gets a value
Parameter key
method getFillColor
getFillColor: () => string;
method getGeodesic
getGeodesic: () => boolean;
method getPoints
getPoints: () => Array<GoogleMapsLatLng>;
method getStrokeColor
getStrokeColor: () => string;
method getStrokeWidth
getStrokeWidth: () => number;
method getVisible
getVisible: () => boolean;
method getZIndex
getZIndex: () => boolean;
method on
on: (eventName: string) => Observable<any>;
Listen to a map event.
Returns
{Observable}
method one
one: (eventName: string) => Promise<any>;
Listen to a map event only once.
Returns
{Promise}
method remove
remove: () => void;
method set
set: (key: string, value: any) => void;
Sets a value
Parameter key
Parameter value
method setFillColor
setFillColor: (fillColor: string) => void;
method setGeodesic
setGeodesic: (geodesic: boolean) => void;
method setPoints
setPoints: (points: Array<GoogleMapsLatLng>) => void;
method setStrokeColor
setStrokeColor: (strokeColor: string) => void;
method setStrokeWidth
setStrokeWidth: (strokeWidth: number) => void;
method setVisible
setVisible: (visible: boolean) => void;
method setZIndex
setZIndex: (zIndex: number) => void;
class GoogleMapsPolyline
class GoogleMapsPolyline {}
constructor
constructor(_objectInstance: any);
method addEventListener
addEventListener: (eventName: string) => Observable<any>;
Adds an event listener.
Returns
{Observable}
method addListenerOnce
addListenerOnce: (eventName: string) => Promise<any>;
Adds an event listener that works once.
Returns
{Promise}
method empty
empty: () => void;
Clears all stored values
method get
get: (key: string) => any;
Gets a value
Parameter key
method getCOlor
getCOlor: () => string;
method getGeodesic
getGeodesic: () => boolean;
method getMap
getMap: () => GoogleMap;
method getPoints
getPoints: () => Array<GoogleMapsLatLng>;
method getWidth
getWidth: () => number;
method getZIndex
getZIndex: () => number;
method on
on: (eventName: string) => Observable<any>;
Listen to a map event.
Returns
{Observable}
method one
one: (eventName: string) => Promise<any>;
Listen to a map event only once.
Returns
{Promise}
method remove
remove: () => void;
method set
set: (key: string, value: any) => void;
Sets a value
Parameter key
Parameter value
method setColor
setColor: (color: string) => void;
method setGeoDesic
setGeoDesic: (geoDesic: boolean) => void;
method setPoints
setPoints: (points: Array<GoogleMapsLatLng>) => void;
method setVisible
setVisible: (visible: boolean) => void;
method setWidth
setWidth: (width: number) => void;
method setZIndex
setZIndex: (zIndex: number) => void;
class GoogleMapsTileOverlay
class GoogleMapsTileOverlay {}
constructor
constructor(_objectInstance: any);
method addEventListener
addEventListener: (eventName: string) => Observable<any>;
Adds an event listener.
Returns
{Observable}
method addListenerOnce
addListenerOnce: (eventName: string) => Promise<any>;
Adds an event listener that works once.
Returns
{Promise}
method clearTileCache
clearTileCache: () => void;
method empty
empty: () => void;
Clears all stored values
method get
get: (key: string) => any;
Gets a value
Parameter key
method getFadeIn
getFadeIn: () => boolean;
method getOpacity
getOpacity: () => number;
method getVisible
getVisible: () => boolean;
method getZIndex
getZIndex: () => number;
method on
on: (eventName: string) => Observable<any>;
Listen to a map event.
Returns
{Observable}
method one
one: (eventName: string) => Promise<any>;
Listen to a map event only once.
Returns
{Promise}
method remove
remove: () => void;
method set
set: (key: string, value: any) => void;
Sets a value
Parameter key
Parameter value
method setFadeIn
setFadeIn: (fadeIn: boolean) => void;
method setOpacity
setOpacity: (opacity: number) => void;
method setVisible
setVisible: (visible: boolean) => void;
method setZIndex
setZIndex: (zIndex: number) => void;
class GooglePlus
class GooglePlus {}
Google Plus
import { GooglePlus } from 'ionic-native';GooglePlus.login().then(res => console.log(res)).catch(err => console.error(err));
method disconnect
static disconnect: () => Promise<any>;
This will clear the OAuth2 token, forget which account was used to login, and disconnect that account from the app. This will require the user to allow the app access again next time they sign in. Be aware that this effect is not always instantaneous. It can take time to completely disconnect.
Returns
{Promise}
method login
static login: (options?: any) => Promise<any>;
The login function walks the user through the Google Auth process.
Parameter options
Returns
{Promise}
method logout
static logout: () => Promise<any>;
This will clear the OAuth2 token.
Returns
{Promise}
method trySilentLogin
static trySilentLogin: (options?: any) => Promise<any>;
You can call trySilentLogin to check if they're already signed in to the app and sign them in silently if they are.
Parameter options
Returns
{Promise}
class Gyroscope
class Gyroscope {}
Gyroscope Read Gyroscope sensor data
import { Gyroscope, GyroscopeOrientation, GyroscopeOptions } from 'ionic-native';let options: GyroscopeOptions = {frequency: 1000};Gyroscope.getCurrent(options).then((orientation: GyroscopeOrientation) => {console.log(orientation.x, orientation.y, orientation.z, orientation.timestamp);}).catch()Gyroscope.watch().subscribe((orientation: GyroscopeOrientation) => {console.log(orientation.x, orientation.y, orientation.z, orientation.timestamp);});
method getCurrent
static getCurrent: (options?: GyroscopeOptions) => Promise<GyroscopeOrientation>;
Get current data from gyroscope sensor
Parameter options
(optional) {Promise} Returns a promise that resolves GyroscopeOrientation
method watch
static watch: (options?: GyroscopeOptions) => Observable<GyroscopeOrientation>;
Watching for gyroscope sensor changes
Parameter options
(optional) {Observable} Returns an Observable that resolves GyroscopeOrientation
class HeaderColor
class HeaderColor {}
HeaderColor Cordova plugin to change color of header in multitask view
import { HeaderColor } from 'ionic-native';HeaderColor.tint("#becb29");
method tint
static tint: (color: string) => Promise<any>;
Set a color to the task header
Parameter color
The hex value of the color
Returns
{Promise}
class Health
class Health {}
Health A plugin that abstracts fitness and health repositories like Apple HealthKit or Google Fit.
import { Health } from 'ionic-native';See description at https://github.com/dariosalvi78/cordova-plugin-health for a full list of Datatypes and see examples. HealthQueryOptions HealthQueryOptionsAggregated HealthStoreOptions HealthData
method isAuthorized
static isAuthorized: (datatypes: Array<string>) => Promise<any>;
Check if the app has authorization to read/write a set of datatypes. This function is similar to requestAuthorization() and has similar quirks.
Parameter datatypes
a list of data types you want to be granted access to {Promise}
method isAvailable
static isAvailable: () => Promise<boolean>;
Tells if either Google Fit or HealthKit are available.
{Promise}
method promptInstallFit
static promptInstallFit: () => Promise<any>;
Checks if recent Google Play Services and Google Fit are installed. If the play services are not installed, or are obsolete, it will show a pop-up suggesting to download them. If Google Fit is not installed, it will open the Play Store at the location of the Google Fit app. The plugin does not wait until the missing packages are installed, it will return immediately. If both Play Services and Google Fit are available, this function just returns without any visible effect.
This function is only available on Android.
{Promise}
method query
static query: (queryOptions: HealthQueryOptions) => Promise<HealthData>;
Gets all the data points of a certain data type within a certain time window. Warning: if the time span is big, it can generate long arrays!
Quirks of query()
In iOS, the amount of datapoints is limited to 1000 by default. You can override this by adding a limit: xxx to your query object. In iOS, datapoints are ordered in an descending fashion (from newer to older). You can revert this behaviour by adding ascending: true to your query object. In Android, it is possible to query for "raw" steps or to select those as filtered by the Google Fit app. In the latter case the query object must contain the field filtered: true. In Google Fit, calories.basal is returned as an average per day, and usually is not available in all days. In Google Fit, calories.active is computed by subtracting the basal calories from the total. As basal energy expenditure, an average is computed from the week before endDate. While Google Fit calculates basal and active calories automatically, HealthKit needs an explicit input from some app. When querying for activities, Google Fit is able to determine some activities automatically (still, walking, running, biking, in vehicle), while HealthKit only relies on the input of the user or of some external app. When querying for activities, calories and distance are also provided in HealthKit (units are kcal and meters) and never in Google Fit. When querying for nutrition, Google Fit always returns all the nutrition elements it has, while HealthKit returns only those that are stored as correlation. To be sure to get all stored the quantities (regardless of they are stored as correlation or not), it's better to query single nutrients. nutrition.vitamin_a is given in micrograms in HealthKit and International Unit in Google Fit. Automatic conversion is not trivial and depends on the actual substance.
Parameter queryOptions
{Promise}
method queryAggregated
static queryAggregated: ( queryOptionsAggregated: HealthQueryOptionsAggregated) => Promise<HealthData>;
Gets aggregated data in a certain time window. Usually the sum is returned for the given quantity.
Quirks of queryAggregated() In Android, to query for steps as filtered by the Google Fit app, the flag filtered: true must be added into the query object. When querying for activities, calories and distance are provided when available in HealthKit and never in Google Fit. In Android, the start and end dates returned are the date of the first and the last available samples. If no samples are found, start and end may not be set. When bucketing, buckets will include the whole hour / day / month / week / year where start and end times fall into. For example, if your start time is 2016-10-21 10:53:34, the first daily bucket will start at 2016-10-21 00:00:00. Weeks start on Monday. When querying for nutrition, HealthKit returns only those that are stored as correlation. To be sure to get all the stored quantities, it's better to query single nutrients. nutrition.vitamin_a is given in micrograms in HealthKit and International Unit in Google Fit.
Parameter queryOptionsAggregated
{Promise}
method requestAuthorization
static requestAuthorization: (datatypes: Array<string>) => Promise<any>;
Requests read and write access to a set of data types. It is recommendable to always explain why the app needs access to the data before asking the user to authorize it. This function must be called before using the query and store functions, even if the authorization has already been given at some point in the past.
Quirks of requestAuthorization()
In Android, it will try to get authorization from the Google Fit APIs. It is necessary that the app's package name and the signing key are registered in the Google API console. In Android, be aware that if the activity is destroyed (e.g. after a rotation) or is put in background, the connection to Google Fit may be lost without any callback. Going through the authorization will ensure that the app is connected again. In Android 6 and over, this function will also ask for some dynamic permissions if needed (e.g. in the case of "distance", it will need access to ACCESS_FINE_LOCATION).
Parameter datatypes
a list of data types you want to be granted access to
{Promise}
method store
static store: (storeOptions: HealthStoreOptions) => Promise<any>;
Stores a data point.
Quirks of store()
Google Fit doesn't allow you to overwrite data points that overlap with others already stored of the same type (see here). At the moment there is no support for update nor delete. In iOS you cannot store the total calories, you need to specify either basal or active. If you use total calories, the active ones will be stored. In Android you can only store active calories, as the basal are estimated automatically. If you store total calories, these will be treated as active. In iOS distance is assumed to be of type WalkingRunning, if you want to explicitly set it to Cycling you need to add the field cycling: true. In iOS storing the sleep activities is not supported at the moment. Storing of nutrients is not supported at the moment.
Parameter storeOptions
{Promise}
class Hotspot
class Hotspot {}
Hotspot
import { Hotspot, Network } from 'ionic-native';Hotspot.scanWifi().then((networks: Array<Network>) => {console.log(networks);});HotspotConnectionInfo HotspotNetwork HotspotNetworkConfig HotspotDevice
Modifiers
@beta
method addWifiNetwork
static addWifiNetwork: ( ssid: string, mode: string, password: string) => Promise<void>;
Add a WiFi network
Parameter ssid
SSID of network
Parameter mode
Authentication mode of (Open, WEP, WPA, WPA_PSK)
Parameter password
Password for network
Returns
{Promise} Promise that adding the WiFi network was successfull, rejected if unsuccessful
method configureHotspot
static configureHotspot: ( ssid: string, mode: string, password: string) => Promise<void>;
Configures hotspot with SSID and Password
Parameter SSID
SSID of your new Access Point
Parameter mode
encryption mode (Open, WEP, WPA, WPA_PSK)
Parameter password
password for your new Access Point
Returns
{Promise} - Promise to call when hotspot is configured, or reject upon failure
method connectToWifi
static connectToWifi: (ssid: string, password: string) => Promise<void>;
Connect to a WiFi network
Parameter ssid
SSID to connect
Parameter password
password to use
Returns
{Promise} Promise that connection to the WiFi network was successfull, rejected if unsuccessful
method connectToWifiAuthEncrypt
static connectToWifiAuthEncrypt: ( ssid: string, password: string, authentication: string, encryption: Array<string>) => Promise<void>;
Connect to a WiFi network
Parameter ssid
SSID to connect
Parameter password
Password to use
Parameter authentication
Authentication modes to use (LEAP, SHARED, OPEN)
Parameter encryption
Encryption modes to use (CCMP, TKIP, WEP104, WEP40)
Returns
{Promise} Promise that connection to the WiFi network was successfull, rejected if unsuccessful
method createHotspot
static createHotspot: ( ssid: string, mode: string, password: string) => Promise<void>;
Configures and starts hotspot with SSID and Password
Parameter SSID
SSID of your new Access Point
Parameter mode
encryption mode (Open, WEP, WPA, WPA_PSK)
Parameter password
password for your new Access Point
Returns
{Promise} - Promise to call once hotspot is started, or reject upon failure
method getAllHotspotDevices
static getAllHotspotDevices: () => Promise<Array<HotspotDevice>>;
Returns
{Promise<Array>}
method getConnectionInfo
static getConnectionInfo: () => Promise<HotspotConnectionInfo>;
Returns
{Promise}
method getMacAddressOfHost
static getMacAddressOfHost: (ip: string) => Promise<string>;
Gets MAC Address associated with IP Address from ARP File
Parameter ip
IP Address that you want the MAC Address of
Returns
{Promise} - A Promise for the MAC Address
method getNetConfig
static getNetConfig: () => Promise<HotspotNetworkConfig>;
Returns
{Promise}
method isAvailable
static isAvailable: () => Promise<boolean>;
Returns
{Promise}
method isConnectedToInternet
static isConnectedToInternet: () => Promise<boolean>;
Returns
{Promise}
method isConnectedToInternetViaWifi
static isConnectedToInternetViaWifi: () => Promise<boolean>;
Returns
{Promise}
method isDnsLive
static isDnsLive: (ip: string) => Promise<boolean>;
Checks if IP is live using DNS
Parameter ip
IP Address you want to test
Returns
{Promise} - A Promise for whether the IP Address is reachable
method isHotspotEnabled
static isHotspotEnabled: () => Promise<void>;
Checks if hotspot is enabled
Returns
{Promise} - Promise that hotspot is enabled, rejected if it is not enabled
method isPortLive
static isPortLive: (ip: string) => Promise<boolean>;
Checks if IP is live using socket And PORT
Parameter ip
IP Address you want to test
Returns
{Promise} - A Promise for whether the IP Address is reachable
method isRooted
static isRooted: () => Promise<boolean>;
Checks if device is rooted
Returns
{Promise} - A Promise for whether the device is rooted
method isWifiDirectSupported
static isWifiDirectSupported: () => Promise<boolean>;
Returns
{Promise}
method isWifiOn
static isWifiOn: () => Promise<boolean>;
Returns
{Promise}
method isWifiSupported
static isWifiSupported: () => Promise<boolean>;
Returns
{Promise}
method pingHost
static pingHost: (ip: string) => Promise<string>;
Returns
{Promise}
method removeWifiNetwork
static removeWifiNetwork: (ssid: string) => Promise<void>;
Remove a WiFi network
Parameter ssid
SSID of network
Returns
{Promise} Promise that removing the WiFi network was successfull, rejected if unsuccessful
method scanWifi
static scanWifi: () => Promise<Array<HotspotNetwork>>;
Returns
{Promise<Array>}
method scanWifiByLevel
static scanWifiByLevel: () => Promise<Array<HotspotNetwork>>;
Returns
{Promise<Array>}
method startHotspot
static startHotspot: () => Promise<boolean>;
Turns on Access Point
Returns
{Promise} - true if AP is started
method startWifiPeriodicallyScan
static startWifiPeriodicallyScan: ( interval: number, duration: number) => Promise<any>;
Returns
{Promise}
method stopHotspot
static stopHotspot: () => Promise<boolean>;
Turns off Access Point
Returns
{Promise} - Promise to turn off the hotspot, true on success, false on failure
method stopWifiPeriodicallyScan
static stopWifiPeriodicallyScan: () => Promise<any>;
Returns
{Promise}
method toggleWifi
static toggleWifi: () => Promise<boolean>;
Returns
{Promise}
class HTTP
class HTTP {}
HTTP Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS and Android.
Advantages over Javascript requests: - Background threading - all requests are done in a background thread - SSL Pinning
import { HTTP } from 'ionic-native';HTTP.get('http://ionic.io', {}, {}).then(data => {console.log(data.status);console.log(data.data); // data received by serverconsole.log(data.headers);}).catch(error => {console.log(error.status);console.log(error.error); // error message as stringconsole.log(error.headers);});HTTPResponse
method acceptAllCerts
static acceptAllCerts: (accept: boolean) => Promise<void>;
Accept all SSL certificates. Or disabled accepting all certificates. Defaults to false.
Parameter accept
Set to true to accept
Returns
{Promise} returns a promise that will resolve on success, and reject on failure
method downloadFile
static downloadFile: ( url: string, body: any, headers: any, filePath: string) => Promise<HTTPResponse>;
Parameter url
The url to send the request to
Parameter body
The body of the request
Parameter headers
The headers to set for this request
Parameter filePath
The path to donwload the file to, including the file name.
Returns
{Promise} returns a promise that resolve on success, and reject on failure
method enableSSLPinning
static enableSSLPinning: (enable: boolean) => Promise<void>;
Enable or disable SSL Pinning. This defaults to false.
To use SSL pinning you must include at least one .cer SSL certificate in your app project. You can pin to your server certificate or to one of the issuing CA certificates. For ios include your certificate in the root level of your bundle (just add the .cer file to your project/target at the root level). For android include your certificate in your project's platforms/android/assets folder. In both cases all .cer files found will be loaded automatically. If you only have a .pem certificate see this stackoverflow answer. You want to convert it to a DER encoded certificate with a .cer extension.
As an alternative, you can store your .cer files in the www/certificates folder.
Parameter enable
Set to true to enable
Returns
{Promise} returns a promise that will resolve on success, and reject on failure
method get
static get: ( url: string, parameters: any, headers: any) => Promise<HTTPResponse>;
Parameter url
The url to send the request to
Parameter parameters
Parameters to send with the request
Parameter headers
The headers to set for this request
Returns
{Promise} returns a promise that resolve on success, and reject on failure
method getBasicAuthHeader
static getBasicAuthHeader: ( username: string, password: string) => { Authorization: string };
This returns an object representing a basic HTTP Authorization header of the form.
Parameter username
Username
Parameter password
Password
Returns
{Object} an object representing a basic HTTP Authorization header of the form {'Authorization': 'Basic base64encodedusernameandpassword'}
method post
static post: (url: string, body: any, headers: any) => Promise<HTTPResponse>;
Make a POST request
Parameter url
The url to send the request to
Parameter body
The body of the request
Parameter headers
The headers to set for this request
Returns
{Promise} returns a promise that resolve on success, and reject on failure
method setHeader
static setHeader: (header: string, value: string) => void;
Set a header for all future requests. Takes a header and a value.
Parameter header
The name of the header
Parameter value
The value of the header
method uploadFile
static uploadFile: ( url: string, body: any, headers: any, filePath: string, name: string) => Promise<HTTPResponse>;
Parameter url
The url to send the request to
Parameter body
The body of the request
Parameter headers
The headers to set for this request
Parameter filePath
The local path of the file to upload
Parameter name
The name of the parameter to pass the file along as
Returns
{Promise} returns a promise that resolve on success, and reject on failure
method useBasicAuth
static useBasicAuth: (username: string, password: string) => void;
This sets up all future requests to use Basic HTTP authentication with the given username and password.
Parameter username
Username
Parameter password
Password
method validateDomainName
static validateDomainName: (validate: boolean) => Promise<void>;
Whether or not to validate the domain name in the certificate. This defaults to true.
Parameter validate
Set to true to validate
Returns
{Promise} returns a promise that will resolve on success, and reject on failure
class Httpd
class Httpd {}
Httpd Embedded httpd for Cordova apps. Light weight HTTP server.
import {Httpd, HttpdOptions} from 'ionic-native';let options: HttpdOptions = {www_root: 'httpd_root', // relative path to app's www directoryport: 80,localhost_only: false};Httpd.startServer(options).subscribe((data) => {console.log('Server is live');});HttpdOptions
method getLocalPath
static getLocalPath: () => Promise<string>;
Get the local path of the running webserver
Returns
{Promise} Returns a promise that resolves with the local path of the web server.
method getUrl
static getUrl: () => Promise<string>;
Gets the URL of the running server
Returns
{Promise} Returns a promise that resolves with the URL of the web server.
method startServer
static startServer: (options?: HttpdOptions) => Observable<string>;
Starts a web server.
Parameter options
Returns
{Observable} Returns an Observable. Subscribe to receive the URL for your web server (if succeeded). Unsubscribe to stop the server.
class IBeacon
class IBeacon {}
IBeacon This plugin provides functions for working with iBeacons.
The plugin's API closely mimics the one exposed through the [CLLocationManager](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/index.html) introduced in iOS 7.
import { IBeacon } from 'ionic-native';// Request permission to use location on iOSIBeacon.requestAlwaysAuthorization();// create a new delegate and register it with the native layerlet delegate = IBeacon.Delegate();// Subscribe to some of the delegate's event handlersdelegate.didRangeBeaconsInRegion().subscribe(data => console.log('didRangeBeaconsInRegion: ', data),error => console.error(););delegate.didStartMonitoringForRegion().subscribe(data => console.log('didStartMonitoringForRegion: ', data),error => console.error(););delegate.didEnterRegion().subscribe(data => {console.log('didEnterRegion: ', data);});let beaconRegion = IBeacon.BeaconRegion('deskBeacon','F7826DA6-ASDF-ASDF-8024-BC5B71E0893E');IBeacon.startMonitoringForRegion(beaconRegion).then(() => console.log('Native layer recieved the request to monitoring'),error => console.error('Native layer failed to begin monitoring: ', error));Beacon BeaconRegion CircularRegion IBeaconPluginResult IBeaconDelegate
method appendToDeviceLog
static appendToDeviceLog: (message: string) => Promise<void>;
Appends the provided [message] to the device logs. Note: If debug logging is turned off, this won't do anything.
Parameter message
The message to append to the device logs.
Returns
{Promise} Returns a promise which is resolved with the log message received by the native layer for appending. The returned message is expected to be equivalent to the one provided in the original call.
method BeaconRegion
static BeaconRegion: ( identifer: string, uuid: string, major?: number, minor?: number, notifyEntryStateOnDisplay?: boolean) => BeaconRegion;
Creates a new BeaconRegion
Parameter identifier
Parameter uuid
The proximity ID of the beacon being targeted. This value must not be blank nor invalid as a UUID.
Parameter major
The major value that you use to identify one or more beacons.
Parameter minor
The minor value that you use to identify a specific beacon.
Parameter notifyEntryStateOnDisplay
Returns
{BeaconRegion} Returns the BeaconRegion that was created
See Also
{CLRegion}
method Delegate
static Delegate: () => IBeaconDelegate;
Instances of this class are delegates between the LocationManager and the code that consumes the messages generated on in the native layer.
Returns
{IBeaconDelegate} An instance of the type .
method disableBluetooth
static disableBluetooth: () => Promise<void>;
Disables Bluetooth using the native Layer. (ANDROID ONLY)
Returns
{Promise} Returns a promise which is resolved when Bluetooth could be enabled. If not, the promise will be rejected with an error.
method disableDebugLogs
static disableDebugLogs: () => Promise<void>;
Disables debug logging in the native layer. Use this method if you want to prevent this plugin from writing to the device logs.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer has set the logging level accordingly.
method disableDebugNotifications
static disableDebugNotifications: () => Promise<void>;
Disables the posting of debug notifications in the native layer. Use this method if you want to prevent the plugin from posting local notifications.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer has set the flag to disabled.
method enableBluetooth
static enableBluetooth: () => Promise<void>;
Enables Bluetooth using the native Layer. (ANDROID ONLY)
Returns
{Promise} Returns a promise which is resolved when Bluetooth could be enabled. If not, the promise will be rejected with an error.
method enableDebugLogs
static enableDebugLogs: () => Promise<void>;
Enables debug logging in the native layer. Use this method if you want a debug the inner workings of this plugin.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer has set the logging level accordingly.
method enableDebugNotifications
static enableDebugNotifications: () => Promise<void>;
Enables the posting of debug notifications in the native layer. Use this method if you want to allow the plugin the posting local notifications. This can be very helpful when debugging how to apps behave when launched into the background.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer has set the flag to enabled.
method getAuthorizationStatus
static getAuthorizationStatus: () => Promise<IBeaconPluginResult>;
Queries the native layer to determine the current authorization in effect.
Returns
{Promise} Returns a promise which is resolved with the requested authorization status.
method getDelegate
static getDelegate: () => IBeaconDelegate;
Returns
{IBeaconDelegate} Returns the IBeaconDelegate
method getMonitoredRegions
static getMonitoredRegions: () => Promise<Region[]>;
Returns
{Promise<Region[]>} Returns a promise which is resolved with an {Array} of {Region} instances that are being monitored by the native layer.
method getRangedRegions
static getRangedRegions: () => Promise<Region[]>;
Returns
{Promise<Region[]>} Returns a promise which is resolved with an {Array} of {Region} instances that are being ranged by the native layer.
method isAdvertising
static isAdvertising: () => Promise<boolean>;
Determines if advertising is currently active, according to the native layer.
Returns
{Promise} Returns a promise which is resolved with a {Boolean} indicating whether advertising is active.
method isAdvertisingAvailable
static isAdvertisingAvailable: () => Promise<boolean>;
Determines if advertising is available or not, according to the native layer.
Returns
{Promise} Returns a promise which is resolved with a {Boolean} indicating whether advertising is available or not.
method isBluetoothEnabled
static isBluetoothEnabled: () => Promise<boolean>;
Determines if bluetooth is switched on, according to the native layer.
Returns
{Promise} Returns a promise which is resolved with a {Boolean} indicating whether bluetooth is active.
method isMonitoringAvailableForClass
static isMonitoringAvailableForClass: (region: Region) => Promise<boolean>;
Determines if region type is supported or not, according to the native layer.
Parameter region
An instance of {Region} which will be checked by the operating system.
Returns
{Promise} Returns a promise which is resolved with a {Boolean} indicating whether the region type is supported or not.
method isRangingAvailable
static isRangingAvailable: () => Promise<boolean>;
Determines if ranging is available or not, according to the native layer.
Returns
{Promise} Returns a promise which is resolved with a {Boolean} indicating whether ranging is available or not.
method onDomDelegateReady
static onDomDelegateReady: () => Promise<void>;
Signals the native layer that the client side is ready to consume messages. Readiness here means that it has a {IBeaconDelegate} set by the consumer javascript code.
The {LocationManager.setDelegate()} will implicitly call this method as well, therefore the only case when you have to call this manually is if you don't wish to specify a {IBeaconDelegate} of yours.
The purpose of this signaling mechanism is to make the events work when the app is being woken up by the Operating System to give it a chance to handle region monitoring events for example.
If you don't set a {IBeaconDelegate} and don't call this method manually, an error message get emitted in the native runtime and the DOM as well after a certain period of time.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer acknowledged the request and started to send events.
method requestAlwaysAuthorization
static requestAlwaysAuthorization: () => Promise<void>;
See the documentation of for further details.
Returns
{Promise} Returns a promise which is resolved when the native layer shows the request dialog.
method requestStateForRegion
static requestStateForRegion: (region: Region) => Promise<void>;
Request state the for specified region. When result is ready didDetermineStateForRegion is triggered. This can be any region, also those which is not currently monitored.
This is done asynchronously and may not be immediately reflected in monitoredRegions.
Parameter region
An instance of {Region} which will be monitored by the operating system.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer acknowledged the dispatch of the request to stop monitoring.
method requestWhenInUseAuthorization
static requestWhenInUseAuthorization: () => Promise<void>;
For iOS 8 and above only. The permission model has changed by Apple in iOS 8, making it necessary for apps to explicitly request permissions via methods like these: requestWhenInUseAuthorization requestAlwaysAuthorization
If you are using this plugin on Android devices only, you will never have to use this, nor
Returns
{Promise} Returns a promise that is resolved when the request dialog is shown.
method setDelegate
static setDelegate: (delegate: IBeaconDelegate) => IBeaconDelegate;
Parameter delegate
An instance of a delegate to register with the native layer.
Returns
{IBeaconDelegate} Returns the IBeaconDelegate
method startAdvertising
static startAdvertising: ( region: Region, measuredPower: number) => Promise<void>;
Start advertising the specified region.
If a region a different identifier is already being advertised for this application, it will be replaced with the new identifier.
This call will accept a valid beacon even when no BlueTooth is available, and will start when BlueTooth is powered on. See {IBeaconDelegate.}
Parameter region
An instance of {Region} which will be advertised by the operating system.
Parameter measuredPower
: Optional parameter, if left empty, the device will use it's own default value.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer acknowledged the dispatch of the advertising request.
method startMonitoringForRegion
static startMonitoringForRegion: (region: BeaconRegion) => Promise<string>;
Start monitoring the specified region.
If a region of the same type with the same identifier is already being monitored for this application, it will be removed from monitoring. For circular regions, the region monitoring service will prioritize regions by their size, favoring smaller regions over larger regions.
This is done asynchronously and may not be immediately reflected in monitoredRegions.
Parameter region
An instance of {Region} which will be monitored by the operating system.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer acknowledged the dispatch of the monitoring request.
method startRangingBeaconsInRegion
static startRangingBeaconsInRegion: (region: BeaconRegion) => Promise<void>;
Start ranging the specified beacon region.
If a region of the same type with the same identifier is already being monitored for this application, it will be removed from monitoring.
This is done asynchronously and may not be immediately reflected in rangedRegions.
Parameter region
An instance of {BeaconRegion} which will be monitored by the operating system.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer acknowledged the dispatch of the monitoring request.
method stopAdvertising
static stopAdvertising: (region: Region) => Promise<void>;
Stop advertising as a beacon.
This is done asynchronously and may not be immediately reflected in isAdvertising.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer acknowledged the dispatch of the request to stop advertising.
method stopMonitoringForRegion
static stopMonitoringForRegion: (region: BeaconRegion) => Promise<void>;
Stop monitoring the specified region. It is valid to call stopMonitoringForRegion: for a region that was registered for monitoring with a different location manager object, during this or previous launches of your application.
This is done asynchronously and may not be immediately reflected in monitoredRegions.
Parameter region
An instance of {Region} which will be monitored by the operating system.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer acknowledged the dispatch of the request to stop monitoring.
method stopRangingBeaconsInRegion
static stopRangingBeaconsInRegion: (region: BeaconRegion) => Promise<void>;
Stop ranging the specified region. It is valid to call stopMonitoringForRegion: for a region that was registered for ranging with a different location manager object, during this or previous launches of your application.
This is done asynchronously and may not be immediately reflected in rangedRegions.
Parameter region
An instance of {BeaconRegion} which will be monitored by the operating system.
Returns
{Promise} Returns a promise which is resolved as soon as the native layer acknowledged the dispatch of the request to stop monitoring.
class ImagePicker
class ImagePicker {}
Image Picker Cordova Plugin For Multiple Image Selection
Requires Cordova plugin:
cordova-plugin-image-picker
. For more info, please see the https://github.com/wymsee/cordova-imagePickerimport { ImagePicker } from 'ionic-native';ImagePicker.getPictures(options).then((results) => {for (var i = 0; i < results.length; i++) {console.log('Image URI: ' + results[i]);}}, (err) => { });ImagePickerOptions
method getPictures
static getPictures: (options: ImagePickerOptions) => Promise<any>;
Pick pictures from the library.
Parameter options
Returns
{Promise} Returns a Promise that resolves the image file URI otherwise rejects with an error.
method hasReadPermission
static hasReadPermission: () => Promise<boolean>;
Check if we have permission to read images
Returns
{Promise} Returns a promise that resolves with a boolean that indicates whether we have permission
method requestReadPermission
static requestReadPermission: () => Promise<any>;
Request permission to read images
Returns
{Promise}
class ImageResizer
class ImageResizer {}
ImageResizer Cordova Plugin For Image Resize
Requires plugin
info.protonet.imageresizer
- use the Ionic CLI and type in the following command:ionic plugin add https://github.com/protonet/cordova-plugin-image-resizer.git
For more info, please see the https://github.com/protonet/cordova-plugin-image-resizer
import { ImageResizer, ImageResizerOptions } from 'ionic-native';let options = {uri: uri,folderName: 'Protonet',quality: 90,width: 1280,height: 1280} as ImageResizerOptions;ImageResizer.resize(options).then((filePath: string) => { console.log('FilePath', filePath); },() => { console.log('Error occured'); })ImageResizerOptions
method resize
static resize: (options: ImageResizerOptions) => Promise<any>;
Returns
{Promise}
class InAppBrowser
class InAppBrowser {}
InAppBrowser Launches in app Browser
import {InAppBrowser} from 'ionic-native';...let browser = new InAppBrowser('https://ionic.io', '_system');browser.executeScript(...);browser.insertCSS(...);browser.close();InAppBrowserEvent InAppBrowserOptions
constructor
constructor(url: string, target?: string, options?: InAppBrowserOptions);
Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.
Parameter url
The URL to load.
Parameter target
The target in which to load the URL, an optional parameter that defaults to _self.
Parameter options
Options for the InAppBrowser. Optional, defaulting to: location=yes. The options string must not contain any blank space, and each feature's name/value pairs must be separated by a comma. Feature names are case insensitive.
constructor
constructor(url: string, target?: string, options?: string);
method close
close: () => void;
Closes the InAppBrowser window.
method executeScript
executeScript: (script: { file?: string; code?: string }) => Promise<any>;
Injects JavaScript code into the InAppBrowser window.
Parameter script
Details of the script to run, specifying either a file or code key.
Returns
{Promise}
method hide
hide: () => void;
Hides an InAppBrowser window that is currently shown. Calling this has no effect if the InAppBrowser was already hidden.
method insertCSS
insertCSS: (css: { file?: string; code?: string }) => Promise<any>;
Injects CSS into the InAppBrowser window.
Parameter css
Details of the script to run, specifying either a file or code key.
Returns
{Promise}
method on
on: (event: string) => Observable<InAppBrowserEvent>;
A method that allows you to listen to events happening in the browser.
Parameter name
of the event
Returns
{Observable} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on unsubscribe.
method show
show: () => void;
Displays an InAppBrowser window that was opened hidden. Calling this has no effect if the InAppBrowser was already visible.
class InAppPurchase
class InAppPurchase {}
InAppPurchase A lightweight Cordova plugin for in app purchases on iOS/Android.
import {InAppPurchase} from 'ionic-native';InAppPurchase.getProducts(['com.yourapp.prod1', 'com.yourapp.prod2', ...]).then((products) => {console.log(products);// [{ productId: 'com.yourapp.prod1', 'title': '...', description: '...', price: '...' }, ...]}).catch((err) => {console.log(err);});InAppPurchase.buy('com.yourapp.prod1').then((data)=> {console.log(data);// {// transactionId: ...// receipt: ...// signature: ...// }}).catch((err)=> {console.log(err);});// fist buy the product...InAppPurchase.buy('com.yourapp.consumable_prod1').then(data => InAppPurchase.consume(data.productType, data.receipt, data.signature)).then(() => console.log('product was successfully consumed!')).catch( err=> console.log(err))
method buy
static buy: ( productId: string) => Promise<{ transactionId: string; receipt: string; signature: string; productType: string;}>;
Buy a product that matches the productId.
Parameter productId
A string that matches the product you want to buy.
Returns
{Promise<{transactionId: string, receipt: string, signature: string, productType: string}>} Returns a Promise that resolves with the transaction details.
method consume
static consume: ( productType: string, receipt: string, signature: string) => Promise<any>;
Call this function after purchasing a "consumable" product to mark it as consumed. On Android, you must consume products that you want to let the user purchase multiple times. If you will not consume the product after a purchase, the next time you will attempt to purchase it you will get the error message:
Parameter productType
Parameter receipt
Parameter signature
Returns
{Promise}
method getProducts
static getProducts: (productId: string[]) => Promise<any>;
Retrieves a list of full product data from Apple/Google. This method must be called before making purchases.
Parameter productId
an array of product ids.
Returns
{Promise} Returns a Promise that resolves with an array of objects.
method getReceipt
static getReceipt: () => Promise<string>;
Get the receipt.
Returns
{Promise} Returns a promise that contains the string for the receipt
method restorePurchases
static restorePurchases: () => Promise<any>;
Restore all purchases from the store
Returns
{Promise} Returns a promise with an array of purchases.
method subscribe
static subscribe: ( productId: string) => Promise<{ transactionId: string; receipt: string; signature: string; productType: string;}>;
Same as buy, but for subscription based products.
Parameter productId
A string that matches the product you want to subscribe to.
Returns
{Promise<{transactionId: string, receipt: string, signature: string, productType: string}>} Returns a Promise that resolves with the transaction details.
class Insomnia
class Insomnia {}
Insomnia Prevent the screen of the mobile device from falling asleep.
import { Insomnia } from 'ionic-native';Insomnia.keepAwake().then(() => console.log('success'),() => console.log('error'));Insomnia.allowSleepAgain().then(() => console.log('success'),() => console.log('error'));
method allowSleepAgain
static allowSleepAgain: () => Promise<any>;
Allows the application to sleep again
Returns
{Promise}
method keepAwake
static keepAwake: () => Promise<any>;
Keeps awake the application
Returns
{Promise}
class Instagram
class Instagram {}
Instagram Share a photo with the instagram app
import {Instagram} from 'ionic-native';Instagram.share('data:image/png;uhduhf3hfif33', 'Caption').then(() => console.log('Shared!')).catch((error: any) => console.error(error));
method isInstalled
static isInstalled: () => Promise<boolean | string>;
Detect if the Instagram application is installed on the device.
Returns
{Promise<boolean|string>} Returns a promise that returns a boolean value if installed, or the app version on android
method share
static share: (canvasIdOrDataUrl: string, caption?: string) => Promise<any>;
Share an image on Instagram Note: Instagram app stopped accepting pre-filled captions on both iOS and Android. As a work-around, the caption is copied to the clipboard. You have to inform your users to paste the caption.
Parameter canvasIdOrDataUrl
The canvas element id or the dataURL of the image to share
Parameter caption
The caption of the image
Returns
{Promise} Returns a promise that resolves if the image was shared
method shareAsset
static shareAsset: (assetLocalIdentifier: string) => Promise<any>;
Share a library asset or video
Parameter assetLocalIdentifier
A local fileURI
Returns
{Promise} Returns a promise that resolves if the image was shared
class IsDebug
class IsDebug {}
IsDebug Detect if the app is running in debug mode or not. Debug mode is when the app is built and installed locally via xcode / eclipse / the cordova cli etc, compared to release mode when the app was downloaded from the app / play store via an end user.
import {IsDebug} from 'ionic-native';IsDebug.getIsDebug().then((isDebug: boolean) => console.log('Is debug:', isDebug)).catch((error: any) => console.error(error));
method getIsDebug
static getIsDebug: () => Promise<boolean>;
Determine if an app was installed via xcode / eclipse / the ionic CLI etc
Returns
{Promise} Returns a promise that resolves with true if the app was installed via xcode / eclipse / the ionic CLI etc. It will resolve to false if the app was downloaded from the app / play store by the end user.
class Keyboard
class Keyboard {}
Keyboard
import { Keyboard } from 'ionic-native';
method close
static close: () => void;
Close the keyboard if open.
method disableScroll
static disableScroll: (disable: boolean) => void;
Prevents the native UIScrollView from moving when an input is focused.
Parameter disable
method hideKeyboardAccessoryBar
static hideKeyboardAccessoryBar: (hide: boolean) => void;
Hide the keyboard accessory bar with the next, previous and done buttons.
Parameter hide
method onKeyboardHide
static onKeyboardHide: () => Observable<any>;
Creates an observable that notifies you when the keyboard is hidden. Unsubscribe to observable to cancel event watch.
Returns
{Observable}
method onKeyboardShow
static onKeyboardShow: () => Observable<any>;
Creates an observable that notifies you when the keyboard is shown. Unsubscribe to observable to cancel event watch.
Returns
{Observable}
method show
static show: () => void;
Force keyboard to be shown.
class LaunchNavigator
class LaunchNavigator {}
Launch Navigator Requires Cordova plugin: uk.co.workingedge.phonegap.plugin.launchnavigator. For more info, please see the [LaunchNavigator plugin docs](https://github.com/dpa99c/phonegap-launch-navigator).
Please refer to the plugin's repo for detailed usage. This docs page only explains the Native wrapper.
import { LaunchNavigator, LaunchNavigatorOptions } from 'ionic-native';let options: LaunchNavigatorOptions = {start: 'London, ON',app: LaunchNavigator.APPS.UBER};LaunchNavigator.navigate('Toronto, ON', options).then(success => console.log('Launched navigator'),error => console.log('Error launching navigator', error));LaunchNavigatorOptions
property APP
static APP: any;
property TRANSPORT_MODE
static TRANSPORT_MODE: any;
method availableApps
static availableApps: () => Promise<string[]>;
Returns a list indicating which apps are installed and available on the current device.
Returns
{Promise<string[]>}
method getAppDisplayName
static getAppDisplayName: (app: string) => string;
Returns the display name of the specified app.
Parameter app
Returns
{string}
method getAppsForPlatform
static getAppsForPlatform: (platform: string) => string[];
Returns list of supported apps on a given platform.
Parameter platform
Returns
{string[]}
method getTransportModes
static getTransportModes: (app: string, platform: string) => string[];
Returns the list of transport modes supported by an app on a given platform.
Parameter app
Parameter platform
Returns
{string[]}
method isAppAvailable
static isAppAvailable: (app: string) => Promise<any>;
Determines if the given app is installed and available on the current device.
Parameter app
Returns
{Promise}
method navigate
static navigate: ( destination: string | number[], options?: LaunchNavigatorOptions) => Promise<any>;
Launches navigator app
Parameter destination
Location name or coordinates (as string or array)
Parameter options
Returns
{Promise}
method supportsDestName
static supportsDestName: (app: string, platform: string) => boolean;
Parameter app
Parameter platform
Returns
{boolean}
method supportsLaunchMode
static supportsLaunchMode: (app: string, platform: string) => boolean;
Indicates if an app on a given platform supports specification of launch mode. Note that currently only Google Maps on Android does.
Parameter app
Parameter platform
Returns
{boolean}
method supportsStart
static supportsStart: (app: string, platform: string) => boolean;
Indicates if an app on a given platform supports specification of start location.
Parameter app
Parameter platform
Returns
{boolean}
method supportsStartName
static supportsStartName: (app: string, platform: string) => boolean;
Parameter app
Parameter platform
Returns
{boolean}
method supportsTransportMode
static supportsTransportMode: (app: string, platform: string) => boolean;
Indicates if an app on a given platform supports specification of transport mode.
Parameter app
specified as a string, you can use one of the constants, e.g
LaunchNavigator.APP.GOOGLE_MAPS
Parameter platform
Returns
{boolean}
method userSelect
static userSelect: ( destination: string | number[], options: LaunchNavigatorOptions) => void;
Parameter destination
Parameter options
class LaunchReview
class LaunchReview {}
LaunchReview
This launches the native store app in order for the user to leave a review. On Android, the plugin opens the the app's storepage in the Play Store where the user can leave a review by pressing the stars to give a rating. On iOS, the plugin opens the app's storepage in the App Store and focuses the Review tab, where the user can leave a review by pressing "Write a review".
import { LaunchReview } from 'ionic-native';const appId: string = 'yourAppId';LaunchReview.launch(appId).then(() => console.log('Successfully launched store app');
method launch
static launch: (appId: string) => Promise<void>;
Launch store app using given app ID
Returns
{Promise}
class LocalNotifications
class LocalNotifications {}
Local Notifications This plugin allows you to display local notifications on the device
import { LocalNotifications } from 'ionic-native';// Schedule a single notificationLocalNotifications.schedule({id: 1,text: 'Single ILocalNotification',sound: isAndroid? 'file://sound.mp3': 'file://beep.caf',data: { secret: key }});// Schedule multiple notificationsLocalNotifications.schedule([{id: 1,text: 'Multi ILocalNotification 1',sound: isAndroid ? 'file://sound.mp3': 'file://beep.caf',data: { secret:key }},{id: 2,title: 'Local ILocalNotification Example',text: 'Multi ILocalNotification 2',icon: 'http://example.com/icon.png'}]);// Schedule delayed notificationLocalNotifications.schedule({text: 'Delayed ILocalNotification',at: new Date(new Date().getTime() + 3600),led: 'FF0000',sound: null});ILocalNotification
method cancel
static cancel: (notificationId: any) => Promise<any>;
Cancels single or multiple notifications
Parameter notificationId
A single notification id, or an array of notification ids.
Returns
{Promise} Returns a promise when the notification is canceled
method cancelAll
static cancelAll: () => Promise<any>;
Cancels all notifications
Returns
{Promise} Returns a promise when all notifications are canceled
method clear
static clear: (notificationId: any) => Promise<any>;
Clears single or multiple notifications
Parameter notificationId
A single notification id, or an array of notification ids.
Returns
{Promise} Returns a promise when the notification had been cleared
method clearAll
static clearAll: () => Promise<any>;
Clears all notifications
Returns
{Promise} Returns a promise when all notifications have cleared
method get
static get: (notificationId: any) => Promise<ILocalNotification>;
Get a notification object
Parameter notificationId
The id of the notification to get
Returns
{Promise}
method getAll
static getAll: () => Promise<Array<ILocalNotification>>;
Get all notification objects
Returns
{Promise<Array>}
method getAllIds
static getAllIds: () => Promise<Array<number>>;
Get all the notification ids
Returns
{Promise<Array>}
method getAllScheduled
static getAllScheduled: () => Promise<Array<ILocalNotification>>;
Get all scheduled notification objects
Returns
{Promise<Array>}
method getAllTriggered
static getAllTriggered: () => Promise<Array<ILocalNotification>>;
Get all triggered notification objects
Returns
{Promise<Array>}
method getScheduled
static getScheduled: (notificationId: any) => Promise<ILocalNotification>;
Get a scheduled notification object
Parameter notificationId
The id of the notification to get
Returns
{Promise}
method getScheduledIds
static getScheduledIds: () => Promise<Array<number>>;
Get the ids of scheduled notifications
Returns
{Promise<Array>} Returns a promise
method getTriggered
static getTriggered: (notificationId: any) => Promise<ILocalNotification>;
Get a triggered notification object
Parameter notificationId
The id of the notification to get
Returns
{Promise}
method getTriggeredIds
static getTriggeredIds: () => Promise<Array<number>>;
Get the ids of triggered notifications
Returns
{Promise<Array>}
method hasPermission
static hasPermission: () => Promise<boolean>;
Informs if the app has the permission to show notifications.
Returns
{Promise}
method isPresent
static isPresent: (notificationId: number) => Promise<boolean>;
Checks presence of a notification
Parameter notificationId
Returns
{Promise}
method isScheduled
static isScheduled: (notificationId: number) => Promise<boolean>;
Checks is a notification is scheduled
Parameter notificationId
Returns
{Promise}
method isTriggered
static isTriggered: (notificationId: number) => Promise<boolean>;
Checks if a notification is triggered
Parameter notificationId
Returns
{Promise}
method on
static on: (eventName: string, callback: any) => void;
Sets a callback for a specific event
Parameter eventName
The name of the event. Available events: schedule, trigger, click, update, clear, clearall, cancel, cancelall
Parameter callback
Call back function. All events return notification and state parameter. clear and clearall return state parameter only.
method registerPermission
static registerPermission: () => Promise<boolean>;
Register permission to show notifications if not already granted.
Returns
{Promise}
method schedule
static schedule: ( options?: ILocalNotification | Array<ILocalNotification>) => void;
Schedules a single or multiple notifications
Parameter options
optional
method update
static update: (options?: ILocalNotification) => void;
Updates a previously scheduled notification. Must include the id in the options parameter.
Parameter options
optional
class LocationAccuracy
class LocationAccuracy {}
LocationAccuracy This Cordova/Phonegap plugin for Android and iOS to request enabling/changing of Location Services by triggering a native dialog from within the app, avoiding the need for the user to leave your app to change location settings manually.
import { LocationAccuracy } from 'ionic-native';LocationAccuracy.canRequest().then((canRequest: boolean) => {if(canRequest) {// the accuracy option will be ignored by iOSLocationAccuracy.request(LocationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(() => console.log('Request successful'),error => console.log('Error requesting location permissions', error));}});
property ERROR_ALREADY_REQUESTING
static ERROR_ALREADY_REQUESTING: number;
property ERROR_CANNOT_CHANGE_ACCURACY
static ERROR_CANNOT_CHANGE_ACCURACY: number;
property ERROR_EXCEPTION
static ERROR_EXCEPTION: number;
property ERROR_GOOGLE_API_CONNECTION_FAILED
static ERROR_GOOGLE_API_CONNECTION_FAILED: number;
property ERROR_INVALID_ACCURACY
static ERROR_INVALID_ACCURACY: number;
property ERROR_INVALID_ACTION
static ERROR_INVALID_ACTION: number;
property ERROR_USER_DISAGREED
static ERROR_USER_DISAGREED: number;
property REQUEST_PRIORITY_BALANCED_POWER_ACCURACY
static REQUEST_PRIORITY_BALANCED_POWER_ACCURACY: number;
property REQUEST_PRIORITY_HIGH_ACCURACY
static REQUEST_PRIORITY_HIGH_ACCURACY: number;
property REQUEST_PRIORITY_LOW_POWER
static REQUEST_PRIORITY_LOW_POWER: number;
property REQUEST_PRIORITY_NO_POWER
static REQUEST_PRIORITY_NO_POWER: number;
property SUCCESS_SETTINGS_SATISFIED
static SUCCESS_SETTINGS_SATISFIED: number;
property SUCCESS_USER_AGREED
static SUCCESS_USER_AGREED: number;
method canRequest
static canRequest: () => Promise<boolean>;
Indicates if you can request accurate location
Returns
{Promise} Returns a promise that resovles with a boolean that indicates if you can request accurate location
method isRequesting
static isRequesting: () => Promise<boolean>;
Indicates if a request is currently in progress
Returns
{Promise} Returns a promise that resolves with a boolean that indicates if a request is currently in progress
method request
static request: (accuracy: number) => Promise<any>;
Requests accurate location
Parameter accuracy
Accuracy, from 0 to 4. You can use the static properties of this class that start with REQUEST_PRIORITY_
Returns
{Promise} Returns a promise that resolves on success and rejects if an error occurred
class Market
class Market {}
Market Opens an app's page in the market place (Google Play, App Store)
import {Market} from 'ionic-native';Market.open('your.package.name');
class MediaCapture
class MediaCapture {}
Media Capture
import { MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from 'ionic-native';let options: CaptureImageOptions = { limit: 3 };MediaCapture.captureImage(options).then((data: MediaFile[]) => console.log(data),(err: CaptureError) => console.error(err));MediaFile MediaFileData CaptureError CaptureAudioOptions CaptureImageOptions CaptureVideoOptions ConfigurationData
property supportedAudioModes
static supportedAudioModes: ConfigurationData[];
The audio recording formats supported by the device.
Returns
{ConfigurationData[]}
property supportedImageModes
static supportedImageModes: ConfigurationData[];
The recording image sizes and formats supported by the device.
Returns
{ConfigurationData[]}
property supportedVideoModes
static supportedVideoModes: ConfigurationData[];
The recording video resolutions and formats supported by the device.
Returns
{ConfigurationData[]}
method captureAudio
static captureAudio: ( options?: CaptureAudioOptions) => Promise<MediaFile[] | CaptureError>;
Start the audio recorder application and return information about captured audio clip files.
Parameter options
Returns
{Promise<MediaFile[]>}
method captureImage
static captureImage: ( options?: CaptureImageOptions) => Promise<MediaFile[] | CaptureError>;
Start the camera application and return information about captured image files.
Parameter options
Returns
{Promise<MediaFile[]>}
method captureVideo
static captureVideo: ( options?: CaptureVideoOptions) => Promise<MediaFile[] | CaptureError>;
Start the video recorder application and return information about captured video clip files.
Parameter options
Returns
{Promise<MediaFile[]>}
method onPendingCaptureError
static onPendingCaptureError: () => Observable<CaptureError>;
is fired if the capture call is unsuccessful
Returns
{Observable}
method onPendingCaptureResult
static onPendingCaptureResult: () => Observable<MediaFile[]>;
is fired if the capture call is successful
Returns
{Observable<MediaFile[]>}
class MediaPlugin
class MediaPlugin {}
MediaPlugin
import { MediaPlugin } from 'ionic-native';// Create a MediaPlugin instance. Expects path to file or url as argument// We can optionally pass a second argument to track the status of the mediaconst onStatusUpdate = (status) => console.log(status);const file = new MediaPlugin('path/to/file.mp3', onStatusUpdate);// Catch the Success & Error Output// Platform Quirks// iOS calls success on completion of playback only// Android calls success on completion of playback AND on release()file.init.then(() => {console.log('Playback Finished');}, (err) => {console.log('somthing went wrong! error code: ' + err.code + ' message: ' + err.message);});// play the filefile.play();// pause the filefile.pause();// get current playback positionfile.getCurrentPosition().then((position) => {console.log(position);});// get file durationfile.getDuration();// skip to 10 seconds (expects int value in ms)file.seekTo(10000);// stop playing the filefile.stop();// release the native audio resource// Platform Quirks:// iOS simply create a new instance and the old one will be overwritten// Android you must call release() to destroy instances of media when you are donefile.release();// Recording to a filevar newFile = new MediaPlugin('path/to/file.mp3');newFile.startRecord();newFile.stopRecord();
constructor
constructor(src: string, onStatusUpdate?: Function);
Open a media file
Parameter src
A URI containing the audio content.
Parameter onStatusUpdate
A callback function to be invoked when the status of the file changes
property init
init: Promise<any>;
property MEDIA_ERR_ABORTED
static MEDIA_ERR_ABORTED: number;
property MEDIA_ERR_DECODE
static MEDIA_ERR_DECODE: number;
property MEDIA_ERR_NETWORK
static MEDIA_ERR_NETWORK: number;
property MEDIA_ERR_NONE_SUPPORTED
static MEDIA_ERR_NONE_SUPPORTED: number;
property MEDIA_NONE
static MEDIA_NONE: number;
property MEDIA_PAUSED
static MEDIA_PAUSED: number;
property MEDIA_RUNNING
static MEDIA_RUNNING: number;
property MEDIA_STARTING
static MEDIA_STARTING: number;
property MEDIA_STOPPED
static MEDIA_STOPPED: number;
method getCurrentAmplitude
getCurrentAmplitude: () => Promise<any>;
Get the current amplitude of the current recording.
Returns
{Promise} Returns a promise with the amplitude of the current recording
method getCurrentPosition
getCurrentPosition: () => Promise<any>;
Get the current position within an audio file. Also updates the Media object's position parameter.
Returns
{Promise} Returns a promise with the position of the current recording
method getDuration
getDuration: () => number;
Get the duration of an audio file in seconds. If the duration is unknown, it returns a value of -1.
Returns
{number} Returns a promise with the duration of the current recording
method pause
pause: () => void;
Pauses playing an audio file.
method pauseRecord
pauseRecord: () => void;
Pauses recording
method play
play: (iosOptions?: { numberOfLoops?: number; playAudioWhenScreenIsLocked?: boolean;}) => void;
Starts or resumes playing an audio file.
method release
release: () => void;
Releases the underlying operating system's audio resources. This is particularly important for Android, since there are a finite amount of OpenCore instances for media playback. Applications should call the release function for any Media resource that is no longer needed.
method resumeRecord
resumeRecord: () => void;
Resumes recording
method seekTo
seekTo: (milliseconds: number) => void;
Sets the current position within an audio file.
Parameter milliseconds
The time position you want to set for the current audio file
method setVolume
setVolume: (volume: number) => void;
Set the volume for an audio file.
Parameter volume
The volume to set for playback. The value must be within the range of 0.0 to 1.0.
method startRecord
startRecord: () => void;
Starts recording an audio file.
method stop
stop: () => void;
Stops playing an audio file.
method stopRecord
stopRecord: () => void;
Stops recording
class Mixpanel
class Mixpanel {}
Mixpanel Cordova Plugin that wraps Mixpanel SDK for Android and iOS
import {Mixpanel} from 'ionic-native';Mixpanel.init(token).then(onSuccess).catch(onError);MixpanelPeople
property people
static readonly people: typeof MixpanelPeople;
Returns
{MixpanelPeople}
method alias
static alias: (aliasId: string, originalId: string) => Promise<any>;
Parameter aliasId
Parameter originalId
Returns
{Promise}
method distinctId
static distinctId: () => Promise<any>;
Returns
{Promise}
method flush
static flush: () => Promise<any>;
Returns
{Promise}
method identify
static identify: (distinctId: string) => Promise<any>;
Parameter distinctId
Returns
{Promise}
method init
static init: (token: string) => Promise<any>;
Parameter token
Returns
{Promise}
method registerSuperProperties
static registerSuperProperties: (superProperties: any) => Promise<any>;
Parameter superProperties
Returns
{Promise}
method reset
static reset: () => Promise<any>;
Returns
{Promise}
method showSurvey
static showSurvey: () => Promise<any>;
Returns
{Promise}
method track
static track: (eventName: string, eventProperties?: any) => Promise<any>;
Parameter eventName
Parameter eventProperties
optional
Returns
{Promise}
class MixpanelPeople
class MixpanelPeople {}
property plugin
static plugin: string;
property pluginRef
static pluginRef: string;
method identify
static identify: (distinctId: string) => Promise<any>;
Parameter distinctId
{Promise}
method increment
static increment: (peopleProperties: any) => Promise<any>;
Parameter peopleProperties
{Promise}
method set
static set: (peopleProperties: any) => Promise<any>;
Parameter peopleProperties
{Promise}
method setOnce
static setOnce: (peopleProperties: any) => Promise<any>;
Parameter peopleProperties
{Promise}
method setPushId
static setPushId: (pushId: string) => Promise<any>;
Parameter pushId
{Promise}
class MusicControls
class MusicControls {}
MusicControls Music controls for Cordova applications. Display a 'media' notification with play/pause, previous, next buttons, allowing the user to control the play. Handle also headset event (plug, unplug, headset button).
import {MusicControls} from 'ionic-native';MusicControls.create({track : 'Time is Running Out', // optional, default : ''artist : 'Muse', // optional, default : ''cover : 'albums/absolution.jpg', // optional, default : nothing// cover can be a local path (use fullpath 'file:///storage/emulated/...', or only 'my_image.jpg' if my_image.jpg is in the www folder of your app)// or a remote url ('http://...', 'https://...', 'ftp://...')isPlaying : true, // optional, default : truedismissable : true, // optional, default : false// hide previous/next/close buttons:hasPrev : false, // show previous button, optional, default: truehasNext : false, // show next button, optional, default: truehasClose : true, // show close button, optional, default: false// Android only, optional// text displayed in the status bar when the notification (and the ticker) are updatedticker : 'Now playing "Time is Running Out"'});MusicControls.subscribe().subscribe(action => {switch(action) {case 'music-controls-next':// Do somethingbreak;case 'music-controls-previous':// Do somethingbreak;case 'music-controls-pause':// Do somethingbreak;case 'music-controls-play':// Do somethingbreak;case 'music-controls-destroy':// Do somethingbreak;// Headset events (Android only)case 'music-controls-media-button' :// Do somethingbreak;case 'music-controls-headset-unplugged':// Do somethingbreak;case 'music-controls-headset-plugged':// Do somethingbreak;default:break;}});MusicControls.listen(); // activates the observable aboveMusicControls.updateIsPlaying(true);MusicControlsOptions
method create
static create: (options: MusicControlsOptions) => Promise<any>;
Create the media controls
Parameter options
Returns
{Promise}
method destroy
static destroy: () => Promise<any>;
Destroy the media controller
Returns
{Promise}
method listen
static listen: () => void;
Start listening for events, this enables the Observable from the subscribe method
method subscribe
static subscribe: () => Observable<any>;
Subscribe to the events of the media controller
Returns
{Observable}
method updateIsPlaying
static updateIsPlaying: (isPlaying: boolean) => void;
Toggle play/pause:
Parameter isPlaying
class NativeAudio
class NativeAudio {}
NativeAudio Native Audio Playback
import {NativeAudio} from 'ionic-native';NativeAudio.preloadSimple('uniqueId1', 'path/to/file.mp3').then(onSuccess, onError);NativeAudio.preloadComplex('uniqueId2', 'path/to/file2.mp3', 1, 1, 0).then(onSuccess, onError);NativeAudio.play('uniqueId1').then(onSuccess, onError);// can optionally pass a callback to be called when the file is done playingNativeAudio.play('uniqueId1', () => console.log('uniqueId1 is done playing'));NativeAudio.loop('uniqueId2').then(onSuccess, onError);NativeAudio.setVolumeForComplexAsset('uniqueId2', 0.6).then(onSuccess,onError);NativeAudio.stop('uniqueId1').then(onSuccess,onError);NativeAudio.unload('uniqueId1').then(onSuccess,onError);
method loop
static loop: (id: string) => Promise<any>;
Loops an audio asset infinitely, this only works for complex assets
Parameter id
unique ID for the audio file {Promise}
method play
static play: (id: string, completeCallback?: Function) => Promise<any>;
Plays an audio asset
Parameter id
unique ID for the audio file
Parameter completeCallback
optional. Callback to be invoked when audio is done playing
Returns
{Promise}
method preloadComplex
static preloadComplex: ( id: string, assetPath: string, volume: number, voices: number, delay: number) => Promise<any>;
Loads an audio file into memory. Optimized for background music / ambient sound. Uses highlevel native APIs with a larger footprint. (iOS: AVAudioPlayer). Can be stopped / looped and used with multiple voices. Can be faded in and out using the delay parameter.
Parameter id
unique ID for the audio file
Parameter assetPath
the relative path or absolute URL (inluding http://) to the audio asset.
Parameter volume
the volume of the preloaded sound (0.1 to 1.0)
Parameter voices
the number of multichannel voices available
Parameter delay
Returns
{Promise}
method preloadSimple
static preloadSimple: (id: string, assetPath: string) => Promise<any>;
Loads an audio file into memory. Optimized for short clips / single shots (up to five seconds). Cannot be stopped / looped.
Parameter id
unique ID for the audio file
Parameter assetPath
the relative path or absolute URL (inluding http://) to the audio asset.
Returns
{Promise}
method setVolumeForComplexAsset
static setVolumeForComplexAsset: (id: string, volume: number) => Promise<any>;
Changes the volume for preloaded complex assets.
Parameter id
unique ID for the audio file
Parameter volume
the volume of the audio asset (0.1 to 1.0)
Returns
{Promise}
method stop
static stop: (id: string) => Promise<any>;
Stops playing an audio
Parameter id
unique ID for the audio file
Returns
{Promise}
method unload
static unload: (id: string) => Promise<any>;
Unloads an audio file from memory
Parameter id
unique ID for the audio file
Returns
{Promise}
class NativeGeocoder
class NativeGeocoder {}
NativeGeocoder Cordova plugin for native forward and reverse geocoding
import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult } from 'ionic-native';NativeGeocoder.reverseGeocode(52.5072095, 13.1452818).then((result: NativeGeocoderReverseResult) => console.log("The address is " + result.address + " in " + result.countryCode)).catch((error: any) => console.log(error));NativeGeocoder.forwardGeocode("Berlin").then((coordinates: NativeGeocoderForwardResult) => console.log("The coordinates are latitude=" + coordinates.latitude + " and longitude=" + coordinates.longitude)).catch((error: any) => console.log(error));NativeGeocoderReverseResult NativeGeocoderForwardResult
Modifiers
@beta
method forwardGeocode
static forwardGeocode: ( addressString: string) => Promise<NativeGeocoderForwardResult>;
Forward geocode a given address to find coordinates
Parameter addressString
The address to be geocoded {Promise}
method reverseGeocode
static reverseGeocode: ( latitude: number, longitude: number) => Promise<NativeGeocoderReverseResult>;
Reverse geocode a given latitude and longitude to find location address
Parameter latitude
The latitude
Parameter longitude
The longitude {Promise}
class NativePageTransitions
class NativePageTransitions {}
NativePageTransitions The Native Page Transitions plugin uses native hardware acceleration to animate your transitions between views. You have complete control over the type of transition, the duration, and direction.
import {NativePageTransitions, NativeTransitionOptions} from 'ionic-native';let options: NativeTransitionOptions = {direction: 'up',duration: 500,slowdownfactor: 3,slidePixels: 20,iosdelay: 100,androiddelay: 150,winphonedelay: 250,fixedPixelsTop: 0,fixedPixelsBottom: 60};NativePageTransitions.slide(options).then(onSuccess).catch(onError);
method curl
static curl: (options: NativeTransitionOptions) => Promise<any>;
Perform a slide animation
Parameter options
Options for the transition
Returns
{Promise}
method drawer
static drawer: (options: NativeTransitionOptions) => Promise<any>;
Perform a slide animation
Parameter options
Options for the transition
Returns
{Promise}
method fade
static fade: (options: NativeTransitionOptions) => Promise<any>;
Perform a fade animation
Parameter options
Options for the transition
Returns
{Promise}
method flip
static flip: (options: NativeTransitionOptions) => Promise<any>;
Perform a flip animation
Parameter options
Options for the transition
Returns
{Promise}
method slide
static slide: (options: NativeTransitionOptions) => Promise<any>;
Perform a slide animation
Parameter options
Options for the transition
Returns
{Promise}
class NativeStorage
class NativeStorage {}
NativeStorage Native storage of variables in Android and iOS
import { NativeStorage } from 'ionic-native';NativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'}).then(() => console.log('Stored item!'),error => console.error('Error storing item', error));NativeStorage.getItem('myitem').then(data => console.log(data),error => console.error(error));
method clear
static clear: () => Promise<any>;
Removes all stored values.
Returns
{Promise}
method getItem
static getItem: (reference: string) => Promise<any>;
Gets a stored item
Parameter reference
Returns
{Promise}
method remove
static remove: (reference: string) => Promise<any>;
Removes a single stored item
Parameter reference
Returns
{Promise}
method setItem
static setItem: (reference: string, value: any) => Promise<any>;
Stores a value
Parameter reference
Parameter value
Returns
{Promise}
class NavigationBar
class NavigationBar {}
NavigationBar The NavigationBar plugin can you to hide and auto hide the android navigation bar.
import { NavigationBar } from 'ionic-native';let autoHide: boolean = true;NavigationBar.hide(autoHide);Modifiers
@beta
method hideNavigationBar
static hideNavigationBar: () => Promise<any>;
Hide the navigation bar. {Promise}
method setUp
static setUp: (autohide?: boolean) => Promise<any>;
hide automatically (or not) the navigation bar.
Parameter autohide
{Promise}
class Ndef
class Ndef {}
property plugin
static plugin: string;
property pluginName
static pluginName: string;
property pluginRef
static pluginRef: string;
method androidApplicationRecord
static androidApplicationRecord: (packageName: string) => any;
method mimeMediaRecord
static mimeMediaRecord: (mimeType: string, payload: string) => any;
method textRecord
static textRecord: (text: string) => any;
method uriRecord
static uriRecord: (uri: string) => any;
class Network
class Network {}
Network Requires Cordova plugin: cordova-plugin-network-information. For more info, please see the [Network plugin docs](https://github.com/apache/cordova-plugin-network-information).
import { Network } from 'ionic-native';// watch network for a disconnectlet disconnectSubscription = Network.onDisconnect().subscribe(() => {console.log('network was disconnected :-(');});// stop disconnect watchdisconnectSubscription.unsubscribe();// watch network for a connectionlet connectSubscription = Network.onConnect().subscribe(() => {console.log('network connected!');// We just got a connection but we need to wait briefly// before we determine the connection type. Might need to wait// prior to doing any api requests as well.setTimeout(() => {if (Network.type === 'wifi') {console.log('we got a wifi connection, woohoo!');}}, 3000);});// stop connect watchconnectSubscription.unsubscribe();The
type
property will return one of the following connection types:unknown
,ethernet
,wifi
,2g
,3g
,4g
,cellular
,none
property downlinkMax
static downlinkMax: string;
Downlink Max Speed {string}
property type
static type: string;
Connection type {string}
method onchange
static onchange: () => Observable<any>;
Returns an observable to watch connection changes {Observable}
method onConnect
static onConnect: () => Observable<any>;
Get notified when the device goes online
Returns
{Observable} Returns an observable.
method onDisconnect
static onDisconnect: () => Observable<any>;
Get notified when the device goes offline
Returns
{Observable} Returns an observable.
method ontypechange
static ontypechange: () => Observable<any>;
Returns an observable to watch connection type changes {Observable}
class NFC
class NFC {}
NFC The NFC plugin allows you to read and write NFC tags. You can also beam to, and receive from, other NFC enabled devices.
Use to - read data from NFC tags - write data to NFC tags - send data to other NFC enabled devices - receive data from NFC devices
This plugin uses NDEF (NFC Data Exchange Format) for maximum compatibilty between NFC devices, tag types, and operating systems.
import {NFC, Ndef} from 'ionic-native';let message = Ndef.textRecord('Hello world');NFC.share([message]).then(onSuccess).catch(onError);
method addMimeTypeListener
static addMimeTypeListener: ( mimeType: string, onSuccess?: Function, onFailure?: Function) => Observable<any>;
Registers an event listener for NDEF tags matching a specified MIME type.
Parameter mimeType
Parameter onSuccess
Parameter onFailure
Returns
{Observable}
method addNdefFormatableListener
static addNdefFormatableListener: ( onSuccess?: Function, onFailure?: Function) => Observable<any>;
Registers an event listener for formatable NDEF tags.
Parameter onSuccess
Parameter onFailure
Returns
{Observable}
method addNdefListener
static addNdefListener: ( onSuccess?: Function, onFailure?: Function) => Observable<any>;
Registers an event listener for any NDEF tag.
Parameter onSuccess
Parameter onFailure
Returns
{Observable}
method addTagDiscoveredListener
static addTagDiscoveredListener: ( onSuccess?: Function, onFailure?: Function) => Observable<any>;
Registers an event listener for tags matching any tag type.
Parameter onSuccess
Parameter onFailure
Returns
{Observable}
method bytesToHexString
static bytesToHexString: (bytes: number[]) => string;
Convert bytes to hex string
Parameter bytes
Returns
{string}
method bytesToString
static bytesToString: (bytes: number[]) => string;
Convert bytes to string
Parameter bytes
Returns
{string}
method enabled
static enabled: () => Promise<any>;
Check if NFC is available and enabled on this device.
Returns
{Promise}
method erase
static erase: () => Promise<any>;
Erase a NDEF tag
method handover
static handover: (uris: string[]) => Promise<any>;
Send a file to another device via NFC handover.
Parameter uris
A URI as a String, or an array of URIs.
Returns
{Promise}
method makeReadyOnly
static makeReadyOnly: () => Promise<any>;
Makes a NFC tag read only. **Warning** this is permanent.
Returns
{Promise}
method share
static share: (message: any[]) => Promise<any>;
Shares an NDEF Message via peer-to-peer.
Parameter message
An array of NDEF Records.
Returns
{Promise}
method showSettings
static showSettings: () => Promise<any>;
Show the NFC settings on the device.
Returns
{Promise}
method stopHandover
static stopHandover: () => Promise<any>;
Stop sharing NDEF data via NFC handover.
Returns
{Promise}
method stringToBytes
static stringToBytes: (str: string) => number[];
Convert string to bytes
Parameter str
Returns
{number[]}
method unshare
static unshare: () => Promise<any>;
Stop sharing NDEF data via peer-to-peer.
Returns
{Promise}
method write
static write: (message: any[]) => Promise<any>;
Qrites an NdefMessage to a NFC tag.
Parameter message
Returns
{Promise}
class OneSignal
class OneSignal {}
OneSignal The OneSignal plugin is an client implementation for using the [OneSignal](https://onesignal.com/) Service. OneSignal is a simple implementation for delivering push notifications.
Requires Cordova plugin:
onesignal-cordova-plugin
. For more info, please see the [OneSignal Cordova Docs](https://documentation.onesignal.com/docs/phonegap-sdk-installation).import { OneSignal } from 'ionic-native';OneSignal.startInit('b2f7f966-d8cc-11e4-bed1-df8f05be55ba', '703322744261');OneSignal.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.InAppAlert);OneSignal.handleNotificationReceived().subscribe(() => {// do something when notification is received});OneSignal.handleNotificationOpened().subscribe(() => {// do something when a notification is opened});OneSignal.endInit();OSNotification OSLockScreenVisibility OSDisplayType OSNotificationPayload OSActionButton OSBackgroundImageLayout OSNotificationOpenedResult OSActionType
property OSInFocusDisplayOption
static OSInFocusDisplayOption: { None: number; InAppAlert: number; Notification: number;};
constants to use in inFocusDisplaying()
method deleteTag
static deleteTag: (key: string) => void;
Deletes a tag that was previously set on a user with
sendTag
orsendTags
. UsedeleteTags
if you need to delete more than one.Parameter Key
to remove.
method deleteTags
static deleteTags: (keys: string[]) => void;
Deletes tags that were previously set on a user with
sendTag
orsendTags
.Parameter Keys
to remove.
method enableSound
static enableSound: (enable: boolean) => void;
Warning: Only applies to Android and Amazon. You can call this from your UI from a button press for example to give your user's options for your notifications.
By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on. Passing false means that the device will only vibrate unless the device is set to a total silent mode.
Parameter false
to disable sound, true to re-enable it.
method enableVibrate
static enableVibrate: (enable: boolean) => void;
Warning: Only applies to Android and Amazon. You can call this from your UI from a button press for example to give your user's options for your notifications.
By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode. Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.
Parameter false
to disable vibrate, true to re-enable it.
method endInit
static endInit: () => any;
Must be called after
startInit
to complete initialization of OneSignal.Returns
{any}
method getIds
static getIds: () => Promise<{ userId: string; pushToken: string }>;
Lets you retrieve the OneSignal user id and device token. Your handler is called after the device is successfully registered with OneSignal.
Returns
{Promise} Returns a Promise that resolves if the device was successfully registered.
userId {string} OneSignal userId is a UUID formatted string. (unique per device per app)
pushToken {string} A push token is a Google/Apple assigned identifier(unique per device per app).
method getTags
static getTags: () => Promise<any>;
Retrieve a list of tags that have been set on the user from the OneSignal server.
Returns
{Promise} Returns a Promise that resolves when tags are recieved.
method handleNotificationOpened
static handleNotificationOpened: () => Observable<OSNotificationOpenedResult>;
Callback to run when a notification is tapped on from the notification shade (**ANDROID**) or notification center (**iOS**), or when closing an Alert notification shown in the app (if InAppAlert is enabled in inFocusDisplaying).
{Observable}
method handleNotificationReceived
static handleNotificationReceived: () => Observable<OSNotification>;
Callback to run when a notification is received, whether it was displayed or not.
{Observable}
method inFocusDisplaying
static inFocusDisplaying: (displayOption: OSDisplayType) => any;
Setting to control how OneSignal notifications will be shown when one is received while your app is in focus. By default this is set to inAppAlert, which can be helpful during development.
Parameter displayOption
Returns
{any}
method iOSSettings
static iOSSettings: (settings: { kOSSettingsKeyAutoPrompt: boolean; kOSSettingsKeyInAppLaunchURL: boolean;}) => any;
**iOS** - Settings for iOS apps
Parameter settings
kOSSettingsKeyAutoPrompt: boolean = true Auto prompt user for notification permissions.
kOSSettingsKeyInAppLaunchURL: boolean = false Launch notifications with a launch URL as an in app webview.
Returns
{any}
method postNotification
static postNotification: (notificationObj: OSNotification) => Promise<any>;
Parameter Parameters
see POST [documentation](https://documentation.onesignal.com/v2.0/docs/notifications-create-notification)
Returns
{Promise} Returns a Promise that resolves if the notification was send successfully.
method promptLocation
static promptLocation: () => void;
Prompts the user for location permission to allow geotagging based on the "Location radius" filter on the OneSignal dashboard.
method registerForPushNotifications
static registerForPushNotifications: () => void;
Call this when you would like to prompt an iOS user to accept push notifications with the default system prompt. Only works if you set
kOSSettingsAutoPrompt
tofalse
iniOSSettings
method sendTag
static sendTag: (key: string, value: string) => void;
Tag a user based on an app event of your choosing so later you can create segments on [onesignal.com](https://onesignal.com/) to target these users. Recommend using sendTags over sendTag if you need to set more than one tag on a user at a time.
Parameter Key
of your choosing to create or update.
Parameter Value
to set on the key. NOTE: Passing in a blank String deletes the key, you can also call deleteTag.
method sendTags
static sendTags: (json: any) => void;
Tag a user based on an app event of your choosing so later you can create segments on [onesignal.com](https://onesignal.com/) to target these users. Recommend using sendTags over sendTag if you need to set more than one tag on a user at a time.
Parameter Pass
a json object with key/value pairs like: {key: "value", key2: "value2"}
method setLogLevel
static setLogLevel: (logLevel: { logLevel: number; visualLevel: number;}) => void;
Enable logging to help debug if you run into an issue setting up OneSignal. The logging levels are as follows: 0 = None, 1= Fatal, 2 = Errors, 3 = Warnings, 4 = Info, 5 = Debug, 6 = Verbose
The higher the value the more information is shown.
Parameter contains
two properties: logLevel (for console logging) and visualLevel (for dialog messages)
method setSubscription
static setSubscription: (enable: boolean) => void;
You can call this method with false to opt users out of receiving all notifications through OneSignal. You can pass true later to opt users back into notifications.
Parameter enable
method startInit
static startInit: (appId: string, googleProjectNumber?: string) => any;
Start the initialization process. Once you are done configuring OneSignal, call the
endInit
function.Parameter appId
Your OneSignal app id
Parameter googleProjectNumber
**ANDROID** - your Google project number; only required for Android GCM/FCM pushes.
Returns
{any}
method syncHashedEmail
static syncHashedEmail: (email: string) => void;
Parameter email
class PayPal
class PayPal {}
PayPal PayPal plugin for Cordova/Ionic Applications
import {PayPal, PayPalPayment, PayPalConfiguration} from "ionic-native";PayPal.init({"PayPalEnvironmentProduction": "YOUR_PRODUCTION_CLIENT_ID","PayPalEnvironmentSandbox": "YOUR_SANDBOX_CLIENT_ID"}).then(() => {// Environments: PayPalEnvironmentNoNetwork, PayPalEnvironmentSandbox, PayPalEnvironmentProductionPayPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({// Only needed if you get an "Internal Service Error" after PayPal login!//payPalShippingAddressOption: 2 // PayPalShippingAddressOptionPayPal})).then(() => {let payment = new PayPalPayment('3.33', 'USD', 'Description', 'sale');PayPal.renderSinglePaymentUI(payment).then(() => {// Successfully paid// Example sandbox response//// {// "client": {// "environment": "sandbox",// "product_name": "PayPal iOS SDK",// "paypal_sdk_version": "2.16.0",// "platform": "iOS"// },// "response_type": "payment",// "response": {// "id": "PAY-1AB23456CD789012EF34GHIJ",// "state": "approved",// "create_time": "2016-10-03T13:33:33Z",// "intent": "sale"// }// }}, () => {// Error or render dialog closed without being successful});}, () => {// Error in configuration});}, () => {// Error in initialization, maybe PayPal isn't supported or something else});PayPalEnvironment PayPalConfigurationOptions PayPalPayment PayPalItem PayPalPaymentDetails PayPalShippingAddress
method clientMetadataID
static clientMetadataID: () => Promise<any>;
Once a user has consented to future payments, when the user subsequently initiates a PayPal payment from their device to be completed by your server, PayPal uses a Correlation ID to verify that the payment is originating from a valid, user-consented device+application. This helps reduce fraud and decrease declines. This method MUST be called prior to initiating a pre-consented payment (a "future payment") from a mobile device. Pass the result to your server, to include in the payment request sent to PayPal. Do not otherwise cache or store this value.
Returns
{Promise}
method init
static init: (clientIdsForEnvironments: PayPalEnvironment) => Promise<any>;
You must preconnect to PayPal to prepare the device for processing payments. This improves the user experience, by making the presentation of the UI faster. The preconnect is valid for a limited time, so the recommended time to preconnect is on page load.
Parameter clientIdsForEnvironments
: set of client ids for environments
Returns
{Promise}
method prepareToRender
static prepareToRender: ( environment: string, configuration: PayPalConfiguration) => Promise<any>;
You must preconnect to PayPal to prepare the device for processing payments. This improves the user experience, by making the presentation of the UI faster. The preconnect is valid for a limited time, so the recommended time to preconnect is on page load.
Parameter environment
: available options are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentProduction" and "PayPalEnvironmentSandbox"
Parameter configuration
: PayPalConfiguration object, for Future Payments merchantName, merchantPrivacyPolicyURL and merchantUserAgreementURL must be set be set
Returns
{Promise}
method renderFuturePaymentUI
static renderFuturePaymentUI: () => Promise<any>;
Please Read Docs on Future Payments at https://github.com/paypal/PayPal-iOS-SDK#future-payments
Returns
{Promise}
method renderProfileSharingUI
static renderProfileSharingUI: (scopes: string[]) => Promise<any>;
Please Read Docs on Profile Sharing at https://github.com/paypal/PayPal-iOS-SDK#profile-sharing
Parameter scopes
scopes Set of requested scope-values. Accepted scopes are: openid, profile, address, email, phone, futurepayments and paypalattributes See https://developer.paypal.com/docs/integration/direct/identity/attributes/ for more details
Returns
{Promise}
method renderSinglePaymentUI
static renderSinglePaymentUI: (payment: PayPalPayment) => Promise<any>;
Start PayPal UI to collect payment from the user. See https://developer.paypal.com/webapps/developer/docs/integration/mobile/ios-integration-guide/ for more documentation of the params.
Parameter payment
PayPalPayment object
Returns
{Promise}
method version
static version: () => Promise<string>;
Retrieve the version of the PayPal iOS SDK library. Useful when contacting support.
Returns
{Promise}
class PayPalConfiguration
class PayPalConfiguration implements PayPalConfigurationOptions {}
constructor
constructor(options?: PayPalConfigurationOptions);
You use a PayPalConfiguration object to configure many aspects of how the SDK behaves. see defaults for options available
class PayPalItem
class PayPalItem {}
constructor
constructor( name: string, quantity: number, price: string, currency: string, sku?: string);
The PayPalItem class defines an optional itemization for a payment.
Parameter name
: Name of the item. 127 characters max
Parameter quantity
: Number of units. 10 characters max.
Parameter price
: Unit price for this item 10 characters max. May be negative for "coupon" etc
Parameter currency
: ISO standard currency code.
Parameter sku
: The stock keeping unit for this item. 50 characters max (optional)
See Also
https://developer.paypal.com/docs/api/#item-object for more details.
property currency
currency: string;
ISO standard currency code.
property name
name: string;
Name of the item. 127 characters max
property price
price: string;
Unit price for this item 10 characters max.
property quantity
quantity: number;
Number of units. 10 characters max.
property sku
sku?: string;
The stock keeping unit for this item. 50 characters max (optional)
class PayPalPayment
class PayPalPayment {}
constructor
constructor( amount: string, currency: string, shortDescription: string, intent: string, details?: PayPalPaymentDetails);
property amount
amount: string;
The amount of the payment.
property bnCode
bnCode: string;
Optional Build Notation code ("BN code"), obtained from partnerprogram@paypal.com, for your tracking purposes.
property currency
currency: string;
The ISO 4217 currency for the payment.
property custom
custom: string;
Optional text, for your tracking purposes. (up to 256 characters)
property details
details: PayPalPaymentDetails;
Optional PayPalPaymentDetails object
property intent
intent: string;
"Sale" for an immediate payment.
property invoiceNumber
invoiceNumber: string;
Optional invoice number, for your tracking purposes. (up to 256 characters)
property items
items: PayPalItem[];
Optional array of PayPalItem objects.
property shippingAddress
shippingAddress: string;
Optional customer shipping address, if your app wishes to provide this to the SDK.
property shortDescription
shortDescription: string;
A short description of the payment.
property softDescriptor
softDescriptor: string;
Optional text which will appear on the customer's credit card statement. (up to 22 characters)
class PayPalPaymentDetails
class PayPalPaymentDetails {}
constructor
constructor(subtotal: string, shipping: string, tax: string);
The PayPalPaymentDetails class defines optional amount details.
Parameter subtotal
: Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places.
Parameter shipping
: Amount charged for shipping. 10 characters max with support for 2 decimal places.
Parameter tax
: Amount charged for tax. 10 characters max with support for 2 decimal places.
property shipping
shipping: string;
Amount charged for shipping. 10 characters max with support for 2 decimal places.
property subtotal
subtotal: string;
Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places.
property tax
tax: string;
Amount charged for tax. 10 characters max with support for 2 decimal places.
class PayPalShippingAddress
class PayPalShippingAddress {}
constructor
constructor( recipientName: string, line1: string, line2: string, city: string, state: string, postalCode: string, countryCode: string);
See the documentation of the individual properties for more detail.
Parameter recipientName
: Name of the recipient at this address. 50 characters max.
Parameter line1
: Line 1 of the address (e.g., Number, street, etc). 100 characters max.
Parameter line2
: Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional.
Parameter city
: City name. 50 characters max.
Parameter state
: 2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries.
Parameter postalCode
: ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries.
Parameter countryCode
: 2-letter country code. 2 characters max.
property city
city: string;
City name. 50 characters max.
property countryCode
countryCode: string;
2-letter country code. 2 characters max.
property line1
line1: string;
Line 1 of the address (e.g., Number, street, etc). 100 characters max.
property line2
line2: string;
Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional.
property postalCode
postalCode: string;
ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries.
property recipientName
recipientName: string;
Name of the recipient at this address. 50 characters max.
property state
state: string;
2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries.
class PhotoLibrary
class PhotoLibrary {}
PhotoLibrary The PhotoLibrary plugin allows access to photos from device by url. So you can use plain img tag to display photos and their thumbnails, and different 3rd party libraries as well. Saving photos and videos to the library is also supported. cdvphotolibrary urls should be trusted by Angular. See plugin homepage to learn how.
import { PhotoLibrary } from 'ionic-native';PhotoLibrary.requestAuthorization().then(() => {PhotoLibrary.getLibrary().subscribe({next: library => {library.forEach(function(libraryItem) {console.log(libraryItem.id); // ID of the photoconsole.log(libraryItem.photoURL); // Cross-platform access to photoconsole.log(libraryItem.thumbnailURL);// Cross-platform access to thumbnailconsole.log(libraryItem.fileName);console.log(libraryItem.width);console.log(libraryItem.height);console.log(libraryItem.creationDate);console.log(libraryItem.latitude);console.log(libraryItem.longitude);console.log(libraryItem.albumIds); // array of ids of appropriate AlbumItem, only of includeAlbumsData was used});},error: err => {},complete: () => { console.log("could not get photos"); }});}).catch(err => console.log("permissions weren't granted"));
method getAlbums
static getAlbums: () => Promise<AlbumItem[]>;
Returns list of photo albums on device. {Promise<AlbumItem[]>} Resolves to list of albums.
method getLibrary
static getLibrary: (options?: GetLibraryOptions) => Observable<LibraryItem[]>;
Retrieves library items. Library item contains photo metadata like width and height, as well as photoURL and thumbnailURL.
Parameter options
Optional, like thumbnail size and chunks settings. {Observable<LibraryItem[]>} Returns library items. If appropriate option was set, will be returned by chunks.
method getPhoto
static getPhoto: ( photo: string | LibraryItem, options?: GetPhotoOptions) => Promise<Blob>;
Returns photo as Blob.
Parameter photo
Id or LibraryItem.
Parameter options
Optional options. {Promise} Resolves requested photo as blob.
method getPhotoURL
static getPhotoURL: ( photo: string | LibraryItem, options?: GetPhotoOptions) => Promise<string>;
Provides means to request photo URL by id.
Parameter photo
Id or LibraryItem.
Parameter options
Optional options. {Promise} Resolves to URL of cdvphotolibrary schema.
method getThumbnail
static getThumbnail: ( photo: string | LibraryItem, options?: GetThumbnailOptions) => Promise<Blob>;
Returns thumbnail as Blob.
Parameter photo
Id or LibraryItem.
Parameter options
Options, like thumbnail size or quality. {Promise} Resolves requested thumbnail as blob.
method getThumbnailURL
static getThumbnailURL: ( photo: string | LibraryItem, options?: GetThumbnailOptions) => Promise<string>;
Provides means to request URL of thumbnail, with specified size or quality.
Parameter photo
Id of photo, or LibraryItem.
Parameter options
Options, like thumbnail size or quality. {Promise} Resolves to URL of cdvphotolibrary schema.
method requestAuthorization
static requestAuthorization: ( options?: RequestAuthorizationOptions) => Promise<void>;
Asks user permission to access photo library.
Parameter options
Optional, like whether only read access needed or read/write. { Promise} Returns a promise that resolves when permissions are granted, and fails when not.
method saveImage
static saveImage: ( url: string, album: AlbumItem | string, options?: GetThumbnailOptions) => Promise<LibraryItem>;
Saves image to specified album. Album will be created if not exists. LibraryItem that represents saved image is returned.
Parameter url
URL of a file, or DataURL.
Parameter album
Name of an album or AlbumItem object.
Parameter options
Options, like thumbnail size for resulting LibraryItem. {Promise} Resolves to LibraryItem that represents saved image.
method saveVideo
static saveVideo: (url: string, album: AlbumItem | string) => Promise<void>;
Saves video to specified album. Album will be created if not exists.
Parameter url
URL of a file, or DataURL.
Parameter album
Name of an album or AlbumItem object. {Promise} Resolves when save operation completes.
class PhotoViewer
class PhotoViewer {}
Photo Viewer This plugin can display your image in full screen with the ability to pan, zoom, and share the image.
import { PhotoViewer } from 'ionic-native';PhotoViewer.show('https://mysite.com/path/to/image.jpg');PhotoViewer.show('https://mysite.com/path/to/image.jpg', 'My image title', {share: false});
method show
static show: ( url: string, title?: string, options?: { share?: boolean }) => void;
Shows an image in full screen
Parameter url
URL or path to image
Parameter title
Parameter options
class PinDialog
class PinDialog {}
Pin Dialog
import { PinDialog } from 'ionic-native';PinDialog.prompt('Enter your PIN', 'Verify PIN', ['OK', 'Cancel']).then((result: any) => {if (result.buttonIndex == 1) console.log('User clicked OK, value is: ', result.input1);else if(result.buttonIndex == 2) console.log('User cancelled');});
method prompt
static prompt: ( message: string, title: string, buttons: string[]) => Promise<{ buttonIndex: number; input1: string }>;
Show pin dialog
Parameter message
Message to show the user
Parameter title
Title of the dialog
Parameter buttons
Buttons to show
Returns
{Promise<{ buttonIndex: number, input1: string }>}
class Pinterest
class Pinterest {}
Pinterest Cordova plugin for Pinterest
import { Pinterest, PinterestUser, PinterestPin, PinterestBoard } from 'ionic-native';const scopes = [Pinterest.SCOPES.READ_PUBLIC,Pinterest.SCOPES.WRITE_PUBLIC,Pinterest.SCOPES.READ_RELATIONSHIPS,Pinterest.SCOPES.WRITE_RELATIONSHIPS];Pinterest.login(scopes).then(res => console.log('Logged in!', res)).catch(err => console.error('Error loggin in', err));Pinterest.getMyPins().then((pins: Array<PinterestPin>) => console.log(pins)).catch(err => console.error(err));Pinterest.getMe().then((user: PinterestUser) => console.log(user));Pinterest.getMyBoards().then((boards: Array<PinterestBoard>) => console.log(boards));PinterestUser PinterestBoard PinterestPin
Modifiers
@beta
property SCOPES
SCOPES: { READ_PUBLIC: string; WRITE_PUBLIC: string; READ_RELATIONSHIPS: string; WRITE_RELATIONSHIPS: string;};
Convenience constant for authentication scopes
method createBoard
static createBoard: (name: string, desc?: string) => Promise<PinterestBoard>;
Create a new board for the authenticated user.
Parameter name
Name of the board
Parameter desc
Optional description of the board
Returns
{Promise}
method createPin
static createPin: ( note: string, boardId: string, imageUrl: string, link?: string) => Promise<PinterestPin>;
Creates a Pin
Parameter note
Note/Description of the pin
Parameter boardId
Board ID to put the Pin under
Parameter imageUrl
URL of the image to share
Parameter link
Optional link to share
Returns
{Promise}
method deleteBoard
static deleteBoard: (boardId: string) => Promise<any>;
Delete a board.
Parameter boardId
The ID of the board
Returns
{Promise}
method deletePin
static deletePin: (pinId: string) => Promise<any>;
Deletes a pin
Parameter pinId
The ID of the pin
Returns
{Promise}
method getBoard
static getBoard: (boardId: string, fields?: string) => Promise<PinterestBoard>;
Get a board's data.
Parameter boardId
Parameter fields
Returns
{Promise}
method getBoardPins
static getBoardPins: ( boardId: string, fields?: string, limit?: number) => Promise<Array<PinterestPin>>;
Get Pins of a specific board.
Parameter boardId
The ID of the board
Parameter fields
Optional fields separated by comma
Parameter limit
Optional limit, defaults to 100, maximum is 100.
Returns
{Promise<Array>}
method getMe
static getMe: (fields?: string) => Promise<PinterestUser>;
Gets the authenticated user's profile
Parameter fields
Fields to retrieve, separated by commas. Defaults to all available fields.
Returns
{Promise} Returns a promise that resolves with the user's object
method getMyBoards
static getMyBoards: ( fields?: string, limit?: number) => Promise<Array<PinterestBoard>>;
Parameter fields
Optional fields separated by comma
Parameter limit
Optional limit, defaults to 100, maximum is 100.
Returns
{Promise<Array>}
method getMyFollowedBoards
static getMyFollowedBoards: ( fields?: string, limit?: number) => Promise<Array<PinterestBoard>>;
Get the authenticated user's followed boards.
Parameter fields
Optional fields separated by comma
Parameter limit
Optional limit, defaults to 100, maximum is 100.
Returns
{Promise<Array>}
method getMyFollowedInterests
static getMyFollowedInterests: (fields?: string, limit?: number) => Promise<any>;
Get the authenticated user's followed interests.
Parameter fields
Optional fields separated by comma
Parameter limit
Optional limit, defaults to 100, maximum is 100.
Returns
{Promise}
method getMyFollowers
static getMyFollowers: ( fields?: string, limit?: number) => Promise<Array<PinterestUser>>;
Get the authenticated user's followers.
Parameter fields
Optional fields separated by comma
Parameter limit
Optional limit, defaults to 100, maximum is 100.
Returns
{Promise<Array>}
method getMyLikes
static getMyLikes: ( fields?: string, limit?: number) => Promise<Array<PinterestPin>>;
Get the authenticated user's likes.
Parameter fields
Optional fields separated by comma
Parameter limit
Optional limit, defaults to 100, maximum is 100.
Returns
{Promise<Array>}
method getMyPins
static getMyPins: ( fields?: string, limit?: number) => Promise<Array<PinterestPin>>;
Parameter fields
Optional fields separated by comma
Parameter limit
Optional limit, defaults to 100, maximum is 100.
Returns
{Promise<Array>}
method getPin
static getPin: (pinId: string, fields?: string) => Promise<PinterestPin>;
Get a Pin by ID.
Parameter pinId
The ID of the Pin
Parameter fields
Optional fields separated by comma
Returns
{Promise}
method getUser
static getUser: (username: string, fields?: string) => Promise<PinterestUser>;
Get a user's profile.
Parameter username
Parameter fields
Returns
{Promise}
method login
static login: (scopes: string[]) => Promise<any>;
Logs the user in using their Pinterest account.
Parameter scopes
Array of scopes that you need access to. You can use Pinterest.SCOPES constant for convenience.
Returns
{Promise} The response object will contain the user's profile data, as well as the access token (if you need to use it elsewhere, example: send it to your server and perform actions on behalf of the user).
class PowerManagement
class PowerManagement {}
PowerManagement The PowerManagement plugin offers access to the devices power-management functionality. It should be used for applications which keep running for a long time without any user interaction.
import {PowerManagement} from 'ionic-native';PowerManagement.acquire().then(onSuccess).catch(onError);
method acquire
static acquire: () => Promise<any>;
Acquire a wakelock by calling this.
Returns
{Promise}
method dim
static dim: () => Promise<any>;
This acquires a partial wakelock, allowing the screen to be dimmed.
Returns
{Promise}
method release
static release: () => Promise<any>;
Release the wakelock. It's important to do this when you're finished with the wakelock, to avoid unnecessary battery drain.
Returns
{Promise}
method setReleaseOnPause
static setReleaseOnPause: (set: boolean) => Promise<any>;
By default, the plugin will automatically release a wakelock when your app is paused (e.g. when the screen is turned off, or the user switches to another app). It will reacquire the wakelock upon app resume. If you would prefer to disable this behaviour, you can use this function.
Parameter set
Returns
{Promise}
class Printer
class Printer {}
Printer Prints documents or HTML rendered content
import {Printer, PrintOptions} from 'ionic-native';Printer.isAvailable().then(onSuccess, onError);let options: PrintOptions = {name: 'MyDocument',printerId: 'printer007',duplex: true,landscape: true,grayscale: true};Printer.print(content, options).then(onSuccess, onError);PrintOptions
method isAvailable
static isAvailable: () => Promise<boolean>;
Checks whether to device is capable of printing.
Returns
{Promise}
method print
static print: ( content: string | HTMLElement, options?: PrintOptions) => Promise<any>;
Sends content to the printer.
Parameter content
The content to print. Can be a URL or an HTML string. If a HTML DOM Object is provided, its innerHtml property value will be used.
Parameter options
optional. The options to pass to the printer
Returns
{Promise}
class Push
class Push {}
Push Register and receive push notifications.
Requires Cordova plugin:
phonegap-plugin-push
. For more info, please see the [Push plugin docs](https://github.com/phonegap/phonegap-plugin-push).For TypeScript users, see the [Push plugin docs about using TypeScript for custom notifications](https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/TYPESCRIPT.md).
import { Push } from 'ionic-native';
method hasPermission
static hasPermission: () => Promise<{ isEnabled: boolean }>;
Check whether the push notification permission has been granted. {Promise<{isEnabled: boolean}>} Returns a Promise that resolves with an object with one property: isEnabled, a boolean that indicates if permission has been granted.
method init
static init: (options: PushOptions) => PushNotification;
Initialize the plugin on the native side.
var push = Push.init({android: {senderID: '12345679'},ios: {alert: 'true',badge: true,sound: 'false'},windows: {}});Parameter options
The Push [options](https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#parameters).
Returns
{PushNotification} Returns a new [PushNotification](https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#pushonevent-callback) object.
class Rollbar
class Rollbar {}
Rollbar This plugin adds Rollbar App monitoring to your application
import { Rollbar } from 'ionic-native';Rollbar.init();Modifiers
@beta
method init
static init: () => Promise<any>;
This function initializes the monitoring of your application {Promise} Returns a promise that resolves when the plugin successfully initializes
class SafariViewController
class SafariViewController {}
SafariViewController
import { SafariViewController } from 'ionic-native';SafariViewController.isAvailable().then((available: boolean) => {if(available){SafariViewController.show({url: 'http://ionic.io',hidden: false,animated: false,transition: 'curl',enterReaderModeIfAvailable: true,tintColor: '#ff0000'}).then((result: any) => {if(result.event === 'opened') console.log('Opened');else if(result.event === 'loaded') console.log('Loaded');else if(result.event === 'closed') console.log('Closed');},(error: any) => console.error(error));} else {// use fallback browser, example InAppBrowser}});SafariViewControllerOptions
method connectToService
static connectToService: () => Promise<any>;
Tries to connect to the Chrome's custom tabs service. you must call this method before calling any of the other methods listed below.
Returns
{Promise}
method hide
static hide: () => Promise<any>;
Hides Safari View Controller
method isAvailable
static isAvailable: () => Promise<boolean>;
Checks if SafariViewController is available
Returns
{Promise}
method mayLaunchUrl
static mayLaunchUrl: (url: string) => Promise<any>;
For even better performance optimization, call this methods if there's more than a 50% chance the user will open a certain URL.
Parameter url
Returns
{Promise}
method show
static show: (options?: SafariViewControllerOptions) => Promise<any>;
Shows Safari View Controller
Parameter options
optional
Returns
{Promise}
method warmUp
static warmUp: () => Promise<any>;
Call this method whenever there's a chance the user will open an external url.
Returns
{Promise}
class ScreenOrientation
class ScreenOrientation {}
Screen Orientation Cordova plugin to set/lock the screen orientation in a common way for iOS, Android, WP8 and Blackberry 10. This plugin is based on an early version of Screen Orientation API so the api does not currently match the current spec.
Requires Cordova plugin:
cordova-plugin-screen-orientation
. For more info, please see the [Screen Orientation plugin docs](https://github.com/apache/cordova-plugin-screen-orientation).import { ScreenOrientation } from 'ionic-native';// set to either landscapeScreenOrientation.lockOrientation('landscape');// allow user rotateScreenOrientation.unlockOrientation();Accepted orientation values:
| Value | Description | |-------------------------------|------------------------------------------------------------------------------| | portrait-primary | The orientation is in the primary portrait mode. | | portrait-secondary | The orientation is in the secondary portrait mode. | | landscape-primary | The orientation is in the primary landscape mode. | | landscape-secondary | The orientation is in the secondary landscape mode. | | portrait | The orientation is either portrait-primary or portrait-secondary (sensor). | | landscape | The orientation is either landscape-primary or landscape-secondary (sensor). |
property orientation
static orientation: string;
Get the current orientation of the device.
method lockOrientation
static lockOrientation: (orientation: string) => void;
Lock the orientation to the passed value. See below for accepted values
Parameter orientation
The orientation which should be locked. Accepted values see table above.
method unlockOrientation
static unlockOrientation: () => void;
Unlock and allow all orientations.
class Screenshot
class Screenshot {}
Screenshot Captures a screen shot
import {Screenshot} from 'ionic-native';// Take a screenshot and save to fileScreenshot.save('jpg', 80, 'myscreenshot.jpg').then(onSuccess, onError);// Take a screenshot and get temporary file URIScreenshot.URI(80).then(onSuccess, onError);
method save
static save: ( format?: string, quality?: number, filename?: string) => Promise<any>;
Takes screenshot and saves the image
Parameter
{string} format. Format can take the value of either 'jpg' or 'png' On ios, only 'jpg' format is supported
Parameter
{number} quality. Determines the quality of the screenshot. Default quality is set to 100.
Parameter
{string} filename. Name of the file as stored on the storage
Returns
{Promise}
method URI
static URI: (quality?: number) => Promise<any>;
Takes screenshot and returns the image as an URI
Parameter
{number} quality. Determines the quality of the screenshot. Default quality is set to 100.
Returns
{Promise}
class SecureStorage
class SecureStorage {}
Secure Storage This plugin gets, sets and removes key,value pairs from a device's secure storage.
Requires Cordova plugin:
cordova-plugin-secure-storage
. For more info, please see the [Cordova Secure Storage docs](https://github.com/Crypho/cordova-plugin-secure-storage).import { SecureStorage } from 'ionic-native';let secureStorage: SecureStorage = new SecureStorage();secureStorage.create('my_store_name').then(() => console.log('Storage is ready!'),error => console.log(error));secureStorage.get('myitem').then(data => console.log(data),error => console.log(error));secureStorage.set('myitem', 'myvalue').then(data => console.log(data),error => console.log(error));secureStorage.remove('myitem').then(data => console.log(data),error => console.log(error));
constructor
constructor();
method create
create: (store: string) => Promise<any>;
Creates a namespaced storage.
Parameter store
Returns
{Promise}
method get
get: (reference: string) => Promise<any>;
Gets a stored item
Parameter reference
Returns
{Promise}
method remove
remove: (reference: string) => Promise<any>;
Removes a single stored item
Parameter reference
Returns
{Promise}
method set
set: (reference: string, value: string) => Promise<any>;
Stores a value
Parameter reference
Parameter value
Returns
{Promise}
class Serial
class Serial {}
Serial This plugin provides functions for working with Serial connections
import { Serial } from 'ionic-native';Serial.requestPermission().then(() => {Serial.open({baudRate: 9800}).then(() => {console.log('Serial connection opened');});}).catch((error: any) => console.log(error));
method close
static close: () => Promise<any>;
Close the serial connection
{Promise} Returns a promise that resolves when the serial connection is closed
method open
static open: (options: SerialOpenOptions) => Promise<any>;
Open connection to a serial device
Parameter options
Options used to open serial connection {Promise} Returns a promise that resolves when the serial connection is opened
method read
static read: () => Promise<any>;
Read from a serial connection
{Promise} Returns a promise that resolves with data read from the serial connection
method registerReadCallback
static registerReadCallback: () => Observable<any>;
Watch the incoming data from the serial connection. Clear the watch by unsubscribing from the observable
Returns
{Observable} Observable returns an observable that you can subscribe to
method requestPermission
static requestPermission: (options?: SerialPermissionOptions) => Promise<any>;
Request permission to connect to a serial device
Parameter options
Options used to request serial permissions for an unknown device {Promise} Returns a promise that resolves when permissions are granted
method write
static write: (data: any) => Promise<any>;
Write to a serial connection
Parameter data
data to write to the serial connection {Promise} Returns a promise that resolves when the write is complete
method writeHex
static writeHex: (data: any) => Promise<any>;
Write hex to a serial connection
Parameter data
data to write to the serial connection {Promise} Returns a promise that resolves when the write is complete
class Shake
class Shake {}
Shake Handles shake gesture
import {Shake} from 'ionic-native';let watch = Shake.startWatch(60).subscribe(() => {// do something});watch.unsubscribe();
method startWatch
static startWatch: (sensitivity?: number) => Observable<any>;
Watch for shake gesture
Parameter sensitivity
Optional sensitivity parameter. Defaults to 40
Returns
{Observable}
class Sim
class Sim {}
Sim Gets info from the Sim card like the carrier name, mcc, mnc and country code and other system dependent info.
Requires Cordova plugin:
cordova-plugin-sim
. For more info, please see the [Cordova Sim docs](https://github.com/pbakondy/cordova-plugin-sim).import { Sim } from 'ionic-native';Sim.getSimInfo().then((info) => console.log('Sim info: ', info),(err) => console.log('Unable to get sim info: ', err));Sim.hasReadPermission().then((info) => console.log('Has permission: ', info));Sim.requestReadPermission().then(() => console.log('Permission granted'),() => console.log('Permission denied'));
method getSimInfo
static getSimInfo: () => Promise<any>;
Returns info from the SIM card.
Returns
{Promise}
method hasReadPermission
static hasReadPermission: () => Promise<any>;
Check permission
Returns
{Promise}
method requestReadPermission
static requestReadPermission: () => Promise<any>;
Request permission
Returns
{Promise}
class SMS
class SMS {}
SMS
Requires Cordova plugin: cordova-plugin-sms. For more info, please see the [SMS plugin docs](https://github.com/cordova-sms/cordova-sms-plugin).
import { SMS } from 'ionic-native';// Send a text message using default optionsSMS.send('416123456', 'Hello world!');SmsOptions SmsOptionsAndroid
method hasPermission
static hasPermission: () => Promise<boolean>;
This function lets you know if the app has permission to send SMS {Promise} returns a promise that resolves with a boolean that indicates if we have permission
method send
static send: ( phoneNumber: string | string[], message: string, options?: SmsOptions) => Promise<any>;
Sends sms to a number
Parameter phoneNumber
Phone number
Parameter message
Message
Parameter options
Options
Returns
{Promise} Resolves promise when the SMS has been sent
class SocialSharing
class SocialSharing {}
Social Sharing Share text, files, images, and links via social networks, sms, and email.
import { SocialSharing } from 'ionic-native';// Check if sharing via email is supportedSocialSharing.canShareViaEmail().then(() => {// Sharing via email is possible}).catch(() => {// Sharing via email is not possible});// Share via emailSocialSharing.shareViaEmail('Body', 'Subject', 'recipient@example.org').then(() => {// Success!}).catch(() => {// Error!});
method canShareVia
static canShareVia: ( appName: string, message?: string, subject?: string, image?: string, url?: string) => Promise<any>;
Checks if you can share via a specific app.
Parameter appName
App name or package name. Examples: instagram or com.apple.social.facebook
Parameter message
Parameter subject
Parameter image
Parameter url
Returns
{Promise}
method canShareViaEmail
static canShareViaEmail: () => Promise<any>;
Checks if you can share via email
Returns
{Promise}
method share
static share: ( message?: string, subject?: string, file?: string | string[], url?: string) => Promise<any>;
Shares using the share sheet
Parameter message
The message you would like to share.
Parameter subject
The subject
Parameter file
URL(s) to file(s) or image(s), local path(s) to file(s) or image(s), or base64 data of an image. Only the first file/image will be used on Windows Phone.
Parameter url
A URL to share
Returns
{Promise}
method shareVia
static shareVia: ( appName: string, message: string, subject?: string, image?: string, url?: string) => Promise<any>;
Share via AppName
Parameter appName
App name or package name. Examples: instagram or com.apple.social.facebook
Parameter message
Parameter subject
Parameter image
Parameter url
Returns
{Promise}
method shareViaEmail
static shareViaEmail: ( message: string, subject: string, to: string[], cc?: string[], bcc?: string[], files?: string | string[]) => Promise<any>;
Share via Email
Parameter message
Parameter subject
Parameter to
Parameter cc
Optional
Parameter bcc
Optional
Parameter files
Optional URL or local path to file(s) to attach
Returns
{Promise}
method shareViaFacebook
static shareViaFacebook: ( message: string, image?: string, url?: string) => Promise<any>;
Shares directly to Facebook
Parameter message
Parameter image
Parameter url
Returns
{Promise}
method shareViaFacebookWithPasteMessageHint
static shareViaFacebookWithPasteMessageHint: ( message: string, image?: string, url?: string, pasteMessageHint?: string) => Promise<any>;
Shares directly to Facebook with a paste message hint
Parameter message
Parameter image
Parameter url
Parameter pasteMessageHint
Returns
{Promise}
method shareViaInstagram
static shareViaInstagram: (message: string, image: string) => Promise<any>;
Shares directly to Instagram
Parameter message
Parameter image
Returns
{Promise}
method shareViaSMS
static shareViaSMS: (messge: string, phoneNumber: string) => Promise<any>;
Share via SMS
Parameter messge
message to send
Parameter phoneNumber
Number or multiple numbers seperated by commas
Returns
{Promise}
method shareViaTwitter
static shareViaTwitter: ( message: string, image?: string, url?: string) => Promise<any>;
Shares directly to Twitter
Parameter message
Parameter image
Parameter url
Returns
{Promise}
method shareViaWhatsApp
static shareViaWhatsApp: ( message: string, image?: string, url?: string) => Promise<any>;
Shares directly to WhatsApp
Parameter message
Parameter image
Parameter url
Returns
{Promise}
method shareViaWhatsAppToReceiver
static shareViaWhatsAppToReceiver: ( receiver: string, message: string, image?: string, url?: string) => Promise<any>;
Shares directly to a WhatsApp Contact
Parameter receiver
Pass phone number on Android, and Addressbook ID (abid) on iOS
Parameter message
Message to send
Parameter image
Image to send (does not work on iOS
Parameter url
Link to send
Returns
{Promise}
method shareWithOptions
static shareWithOptions: (options: { message?: string; subject?: string; files?: string | string[]; url?: string; chooserTitle?: string;}) => Promise<any>;
Shares using the share sheet with additional options and returns a result object or an error message (requires plugin version 5.1.0+)
Parameter options
The options object with the message, subject, files, url and chooserTitle properties.
Returns
{Promise}
class SpeechRecognition
class SpeechRecognition {}
SpeechRecognition This plugin does speech recognition using cloud services
import { SpeechRecognition } from 'ionic-native';// Check feature availableSpeechRecognition.isRecognitionAvailable().then((available: boolean) => console.log(available))// Start the recognition processSpeechRecognition.startListening(options).subscribe((matches: Array<string>) => console.log(matches),(onerror) => console.log('error:', onerror))// Stop the recognition process (iOS only)SpeechRecognition.stopListening()// Get the list of supported languagesSpeechRecognition.getSupportedLanguages().then((languages: Array<string>) => console.log(languages),(error) => console.log(error))// Check permissionSpeechRecognition.hasPermission().then((hasPermission: boolean) => console.log(hasPermission))// Request permissionsSpeechRecognition.requestPermission().then(() => console.log('Granted'),() => console.log('Denied'))Modifiers
@beta
method getSupportedLanguages
static getSupportedLanguages: () => Promise<Array<string>>;
Get the list of supported languages {Promise< Array >} list of languages
method hasPermission
static hasPermission: () => Promise<boolean>;
Check permission {Promise} has permission
method isRecognitionAvailable
static isRecognitionAvailable: () => Promise<boolean>;
Check feature available {Promise}
method requestPermission
static requestPermission: () => Promise<void>;
Request permissions {Promise}
method startListening
static startListening: ( options?: SpeechRecognitionListeningOptions) => Observable<string[]>;
Start the recognition process {Promise< Array >} list of recognized terms
method stopListening
static stopListening: () => Promise<void>;
Stop the recognition process
class SpinnerDialog
class SpinnerDialog {}
Spinner Dialog
import { SpinnerDialog } from 'ionic-native';SpinnerDialog.show();SpinnerDialog.hide();SpinnerDialogIOSOptions
method hide
static hide: () => void;
Hides the spinner dialog if visible
method show
static show: ( title?: string, message?: string, cancelCallback?: any, iOSOptions?: SpinnerDialogIOSOptions) => void;
Shows the spinner dialog
Parameter title
Spinner title (shows on Android only)
Parameter message
Spinner message
Parameter cancelCallback
Set to true to set spinner not cancelable. Or provide a function to call when the user cancels the spinner.
Parameter iOSOptions
Options for iOS only
class Splashscreen
class Splashscreen {}
Splashscreen This plugin displays and hides a splash screen during application launch. The methods below allows showing and hiding the splashscreen after the app has loaded.
import { Splashscreen } from 'ionic-native';Splashscreen.show();Splashscreen.hide();
class SQLite
class SQLite {}
SQLite
Access SQLite databases on the device.
import { SQLite } from 'ionic-native';// OPTION A: Use static constructorSQLite.openDatabase({name: 'data.db',location: 'default'}).then((db: SQLite) => {db.executeSql('create table danceMoves(name VARCHAR(32))', []).then(() => {}).catch(() => {});}).catch(error => console.error('Error opening database', error));// OPTION B: Create a new instance of SQLitelet db = new SQLite();db.openDatabase({name: 'data.db',location: 'default' // the location field is required}).then(() => {db.executeSql('create table danceMoves(name VARCHAR(32))', []).then(() => {}, (err) => {console.error('Unable to execute sql: ', err);});}, (err) => {console.error('Unable to open database: ', err);});
constructor
constructor();
property databaseFeatures
databaseFeatures: any;
method abort
abort: (txFailure: any) => void;
Parameter txFailure
method abortallPendingTransactions
abortallPendingTransactions: () => void;
method abortFromQ
abortFromQ: (sqlerror: any) => void;
Parameter sqlerror
method addStatement
addStatement: (sql: any, values: any) => Promise<any>;
Parameter sql
Parameter values
Returns
{Promise}
method addTransaction
addTransaction: (transaction: any) => void;
method close
close: () => Promise<any>;
Returns
{Promise}
method deleteDatabase
static deleteDatabase: (first: any) => Promise<any>;
Parameter first
Returns
{Promise}
method echoTest
static echoTest: () => Promise<any>;
Returns
{Promise}
method executeSql
executeSql: (statement: string, params: any) => Promise<any>;
Execute SQL on the opened database. Note, you must call
openDatabase
first, and ensure it resolved and successfully opened the database.
method finish
finish: () => void;
method handleStatementFailure
handleStatementFailure: (handler: any, response: any) => void;
Parameter handler
Parameter response
method handleStatementSuccess
handleStatementSuccess: (handler: any, response: any) => void;
Parameter handler
Parameter response
method openDatabase
static openDatabase: (config: any) => Promise<SQLite>;
Open or create a SQLite database file.
See the plugin docs for an explanation of all options: https://github.com/litehelpers/Cordova-sqlite-storage#opening-a-database
Parameter config
the config for opening the database.
method readTransaction
readTransaction: (fn: any) => Promise<any>;
Parameter fn
Returns
{Promise}
method run
run: () => void;
method sqlBatch
sqlBatch: (sqlStatements: any) => Promise<any>;
Parameter sqlStatements
Returns
{Promise}
method start
start: () => void;
method startNextTransaction
startNextTransaction: () => void;
method transaction
transaction: (fn: any) => Promise<any>;
Parameter fn
Returns
{Promise}
class StatusBar
class StatusBar {}
Status Bar Manage the appearance of the native status bar.
Requires Cordova plugin:
cordova-plugin-statusbar
. For more info, please see the [StatusBar plugin docs](https://github.com/apache/cordova-plugin-statusbar).import { StatusBar } from 'ionic-native';StatusBar.overlaysWebView(true); // let status bar overlay webviewStatusBar.backgroundColorByHexString('#ffffff'); // set status bar to white
property isVisible
static isVisible: boolean;
Whether the StatusBar is currently visible or not.
method backgroundColorByHexString
static backgroundColorByHexString: (hexString: string) => void;
Set the status bar to a specific hex color (CSS shorthand supported!).
iOS note: you must call StatusBar.overlaysWebView(false) to enable color changing.
Parameter hexString
The hex value of the color.
method backgroundColorByName
static backgroundColorByName: (colorName: string) => void;
Set the status bar to a specific named color. Valid options: black, darkGray, lightGray, white, gray, red, green, blue, cyan, yellow, magenta, orange, purple, brown.
iOS note: you must call StatusBar.overlaysWebView(false) to enable color changing.
Parameter colorName
The name of the color (from above)
method hide
static hide: () => void;
Hide the StatusBar
method overlaysWebView
static overlaysWebView: (doesOverlay: boolean) => void;
Set whether the status bar overlays the main app view. The default is true.
Parameter doesOverlay
Whether the status bar overlays the main app view.
method show
static show: () => void;
Show the StatusBar
method styleBlackOpaque
static styleBlackOpaque: () => void;
Use the blackOpaque statusbar (light text, for dark backgrounds).
method styleBlackTranslucent
static styleBlackTranslucent: () => void;
Use the blackTranslucent statusbar (light text, for dark backgrounds).
method styleDefault
static styleDefault: () => void;
Use the default statusbar (dark text, for light backgrounds).
method styleLightContent
static styleLightContent: () => void;
Use the lightContent statusbar (light text, for dark backgrounds).
class Stepcounter
class Stepcounter {}
Stepcounter Cordova plugin for using device's stepcounter on Android (API > 19)
Use to - start and stop stepcounter service - read device's stepcounter data
import { Stepcounter } from 'ionic-native';let startingOffset = 0;Stepcounter.start(startingOffset).then(onSuccess => console.log('stepcounter-start success', onSuccess), onFailure => console.log('stepcounter-start error', onFailure));Stepcounter.getHistory().then(historyObj => console.log('stepcounter-history success', historyObj), onFailure => console.log('stepcounter-history error', onFailure));
method deviceCanCountSteps
static deviceCanCountSteps: () => Promise<boolean | any>;
Returns true/false if Android device is running >API level 19 && has the step counter API available
Returns
{Promise<any | boolean>} Returns a Promise that resolves on success, or rejects on failure
method getHistory
static getHistory: () => Promise<any>;
Get the step history (JavaScript object)
Returns
{Promise} Returns a Promise that resolves on success, or rejects on failure
method getStepCount
static getStepCount: () => Promise<number | any>;
Get the amount of steps since the start command has been called
Returns
{Promise<any | number>} Returns a Promise that resolves on success with the amount of steps since the start command has been called, or rejects on failure
method getTodayStepCount
static getTodayStepCount: () => Promise<number | any>;
Get the amount of steps for today (or -1 if it no data given)
Returns
{Promise<any | number>} Returns a Promise that resolves on success with the amount of steps today, or rejects on failure
method start
static start: (startingOffset: number) => Promise<number | any>;
Start the step counter
Parameter startingOffset
will be added to the total steps counted in this session
Returns
{Promise<any | number>} Returns a Promise that resolves on success or rejects on failure
method stop
static stop: () => Promise<number | any>;
Stop the step counter
Returns
{Promise<any | number>} Returns a Promise that resolves on success with the amount of steps since the start command has been called, or rejects on failure
class StreamingMedia
class StreamingMedia {}
StreamingMedia This plugin allows you to stream audio and video in a fullscreen, native player on iOS and Android.
import {StreamingMedia, StreamingVideoOptions} from 'ionic-native';let options: StreamingVideoOptions = {successCallback: () => { console.log('Video played') },errorCallback: (e) => { console.log('Error streaming') },orientation: 'landscape'};StreamingMedia.playVideo('https://path/to/video/stream', options);StreamingVideoOptions StreamingAudioOptions
method pauseAudio
static pauseAudio: () => void;
Pauses streaming audio
method playAudio
static playAudio: (audioUrl: string, options?: StreamingAudioOptions) => void;
Streams an audio
Parameter audioUrl
The URL of the audio stream
Parameter options
Options
method playVideo
static playVideo: (videoUrl: string, options?: StreamingVideoOptions) => void;
Streams a video
Parameter videoUrl
The URL of the video
Parameter options
Options
method resumeAudio
static resumeAudio: () => void;
Resumes streaming audio
method stopAudio
static stopAudio: () => void;
Stops streaming audio
class Stripe
class Stripe {}
Stripe A plugin that allows you to use Stripe's Native SDKs for Android and iOS.
import { Stripe } from 'ionic-native';Stripe.setPublishableKey('my_publishable_key');let card = {number: '4242424242424242',expMonth: 12,expYear: 2020,cvc: '220'};Stripe.createCardToken(card).then(token => console.log(token)).catch(error => console.error(error));StripeCardTokenParams
method createCardToken
static createCardToken: (params: StripeCardTokenParams) => Promise<string>;
Create Credit Card Token
Parameter params
Credit card information {Promise} returns a promise that resolves with the token, or reject with an error
method setPublishableKey
static setPublishableKey: (publishableKey: string) => Promise<void>;
Set publishable key
Parameter publishableKey
Publishable key {Promise}
class TextToSpeech
class TextToSpeech {}
TextToSpeech Text to Speech plugin
import {TextToSpeech} from 'ionic-native';TextToSpeech.speak('Hello World').then(() => console.log('Success')).catch((reason: any) => console.log(reason));TTSOptions
class ThemeableBrowser
class ThemeableBrowser {}
ThemeableBrowser In-app browser that allows styling.
import { ThemeableBrowser } from 'ionic-native';// can add options from the original InAppBrowser in a JavaScript object form (not string)// This options object also takes additional parameters introduced by the ThemeableBrowser plugin// This example only shows the additional parameters for ThemeableBrowser// Note that that `image` and `imagePressed` values refer to resources that are stored in your applet options = {statusbar: {color: '#ffffffff'},toolbar: {height: 44,color: '#f0f0f0ff'},title: {color: '#003264ff',showPageTitle: true},backButton: {image: 'back',imagePressed: 'back_pressed',align: 'left',event: 'backPressed'},forwardButton: {image: 'forward',imagePressed: 'forward_pressed',align: 'left',event: 'forwardPressed'},closeButton: {image: 'close',imagePressed: 'close_pressed',align: 'left',event: 'closePressed'},customButtons: [{image: 'share',imagePressed: 'share_pressed',align: 'right',event: 'sharePressed'}],menu: {image: 'menu',imagePressed: 'menu_pressed',title: 'Test',cancel: 'Cancel',align: 'right',items: [{event: 'helloPressed',label: 'Hello World!'},{event: 'testPressed',label: 'Test!'}]},backButtonCanClose: true};let browser = new ThemeableBrowser('https://ionic.io', '_blank', options);We suggest that you refer to the plugin's repository for additional information on usage that may not be covered here. ThemeableBrowserButton ThemeableBrowserOptions
constructor
constructor(url: string, target: string, styleOptions: ThemeableBrowserOptions);
method close
close: () => void;
Closes the browser window.
method executeScript
executeScript: (script: { file?: string; code?: string }) => Promise<any>;
Injects JavaScript code into the browser window.
Parameter script
Details of the script to run, specifying either a file or code key.
Returns
{Promise}
method insertCss
insertCss: (css: { file?: string; code?: string }) => Promise<any>;
Injects CSS into the browser window.
Parameter css
Details of the script to run, specifying either a file or code key.
Returns
{Promise}
method on
on: (event: string) => Observable<InAppBrowserEvent>;
A method that allows you to listen to events happening in the browser. Available events are:
ThemeableBrowserError
,ThemeableBrowserWarning
,critical
,loadfail
,unexpected
,undefined
Parameter event
Event name
Returns
{Observable} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on unsubscribe.
method reload
reload: () => void;
Reloads the current page
method show
show: () => void;
Displays an browser window that was opened hidden. Calling this has no effect if the browser was already visible.
class ThreeDeeTouch
class ThreeDeeTouch {}
3DTouch Please do refer to the original plugin's repo for detailed usage. The usage example here might not be sufficient.
import { ThreeDeeTouch } from 'ionic-native';// import for type completion on variablesimport { ThreeDeeTouchQuickAction, ThreeDeeTouchForceTouch } from 'ionic-native';...ThreeDeeTouch.isAvailable().then(isAvailable => console.log("3D Touch available? " + isAvailable));ThreeDeeTouch.watchForceTouches().subscribe((data: ThreeDeeTouchForceTouch) => {console.log("Force touch %" + data.force);console.log("Force touch timestamp: " + data.timestamp);console.log("Force touch x: " + data.x);console.log("Force touch y: " + data.y);});let actions: Array<ThreeDeeTouchQuickAction> = [{type: 'checkin',title: 'Check in',subtitle: 'Quickly check in',iconType: 'Compose'},{type: 'share',title: 'Share',subtitle: 'Share like you care',iconType: 'Share'},{type: 'search',title: 'Search',iconType: 'Search'},{title: 'Show favorites',iconTemplate: 'HeartTemplate'}];ThreeDeeTouch.configureQuickActions(actions);ThreeDeeTouch.onHomeIconPressed().subscribe((payload) => {// returns an object that is the button you presedconsole.log('Pressed the ${payload.title} button')console.log(payload.type)})ThreeDeeTouchQuickAction ThreeDeeTouchForceTouch
method configureQuickActions
static configureQuickActions: ( quickActions: Array<ThreeDeeTouchQuickAction>) => void;
setup the 3D-touch actions, takes an array of objects with the following
Parameter type
(optional) A type that can be used
onHomeIconPressed
callbackParameter title
Title for your action
Parameter subtitle
(optional) A short description for your action
Parameter iconType
(optional) Choose between Prohibit, Contact, Home, MarkLocation, Favorite, Love, Cloud, Invitation, Confirmation, Mail, Message, Date, Time, CapturePhoto, CaptureVideo, Task, TaskCompleted, Alarm, Bookmark, Shuffle, Audio, Update
Parameter iconTemplate
(optional) Can be used to provide your own icon
method disableLinkPreview
static disableLinkPreview: () => void;
Disabled the link preview feature, if enabled.
method enableLinkPreview
static enableLinkPreview: () => void;
Enable Link Preview. UIWebView and WKWebView (the webviews powering Cordova apps) don't allow the fancy new link preview feature of iOS9.
method isAvailable
static isAvailable: () => Promise<boolean>;
You need an iPhone 6S or some future tech to use the features of this plugin, so you can check at runtime if the user's device is supported.
Returns
{Promise} returns a promise that resolves with a boolean that indicates whether the plugin is available or not
method onHomeIconPressed
static onHomeIconPressed: () => Observable<any>;
When a home icon is pressed, your app launches and this JS callback is invoked.
Returns
{Observable} returns an observable that notifies you when he user presses on the home screen icon
method watchForceTouches
static watchForceTouches: () => Observable<ThreeDeeTouchForceTouch>;
You can get a notification when the user force touches the webview. The plugin defines a Force Touch when at least 75% of the maximum force is applied to the screen. Your app will receive the x and y coordinates, so you have to figure out which UI element was touched.
Returns
{Observable} Returns an observable that sends a
ThreeDeeTouchForceTouch
object
class Toast
class Toast {}
Toast This plugin allows you to show a native Toast (a little text popup) on iOS, Android and WP8. It's great for showing a non intrusive native notification which is guaranteed always in the viewport of the browser.
Requires Cordova plugin:
cordova-plugin-x-toast
. For more info, please see the [Toast plugin docs](https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin).import { Toast } from 'ionic-native';Toast.show("I'm a toast", '5000', 'center').subscribe(toast => {console.log(toast);});ToastOptions
method hide
static hide: () => Promise<any>;
Manually hide any currently visible toast.
Returns
{Promise} Returns a Promise that resolves on success.
method show
static show: ( message: string, duration: string, position: string) => Observable<any>;
Show a native toast for the given duration at the specified position.
Parameter message
The message to display.
Parameter duration
Duration to show the toast, either 'short', 'long' or any number of milliseconds: '1500'.
Parameter position
Where to position the toast, either 'top', 'center', or 'bottom'.
Returns
{Observable} Returns an Observable that notifies first on success and then when tapped, rejects on error.
method showLongBottom
static showLongBottom: (message: string) => Observable<any>;
Shorthand for
show(message, 'long', 'bottom')
.Parameter message
Returns
{Observable} Returns an Observable that notifies first on success and then when tapped, rejects on error.
method showLongCenter
static showLongCenter: (message: string) => Observable<any>;
Shorthand for
show(message, 'long', 'center')
.Parameter message
Returns
{Observable} Returns an Observable that notifies first on success and then when tapped, rejects on error.
method showLongTop
static showLongTop: (message: string) => Observable<any>;
Shorthand for
show(message, 'long', 'top')
.Parameter message
Returns
{Observable} Returns an Observable that notifies first on success and then when tapped, rejects on error.
method showShortBottom
static showShortBottom: (message: string) => Observable<any>;
Shorthand for
show(message, 'short', 'bottom')
.Parameter message
Returns
{Observable} Returns an Observable that notifies first on success and then when tapped, rejects on error.
method showShortCenter
static showShortCenter: (message: string) => Observable<any>;
Shorthand for
show(message, 'short', 'center')
.Parameter message
Returns
{Observable} Returns an Observable that notifies first on success and then when tapped, rejects on error.
method showShortTop
static showShortTop: (message: string) => Observable<any>;
Shorthand for
show(message, 'short', 'top')
.Parameter message
Returns
{Observable} Returns an Observable that notifies first on success and then when tapped, rejects on error.
method showWithOptions
static showWithOptions: (options: ToastOptions) => Observable<any>;
Show a native toast with the given options.
Parameter options
Options for showing a toast. Available options: message The message to display. duration Duration to show the toast, either 'short', 'long' or any number of milliseconds: '1500'. position Where to position the toast, either 'top', 'center', or 'bottom'. addPixelsY Offset in pixels to move the toast up or down from its specified position.
Returns
{Observable} Returns an Observable that notifies first on success and then when tapped, rejects on error.
class TouchID
class TouchID {}
TouchID Scan the fingerprint of a user with the TouchID sensor.
Requires Cordova plugin:
cordova-plugin-touch-id
. For more info, please see the [TouchID plugin docs](https://github.com/EddyVerbruggen/cordova-plugin-touch-id).### Import Touch ID Plugin into Project
import { TouchID } from 'ionic-native';### Check for Touch ID Availability
TouchID.isAvailable().then(res => console.log('TouchID is available!'),err => console.error('TouchID is not available', err));### Invoke Touch ID w/ Custom Message
TouchID.verifyFingerprint('Scan your fingerprint please').then(res => console.log('Ok', res),err => console.error('Error', err));### Error Codes
The plugin will reject for various reasons. Your app will most likely need to respond to the cases differently.
Here is a list of some of the error codes:
-
-1
- Fingerprint scan failed more than 3 times --2
or-128
- User tapped the 'Cancel' button --3
- User tapped the 'Enter Passcode' or 'Enter Password' button --4
- The scan was cancelled by the system (Home button for example) --6
- TouchID is not Available --8
- TouchID is locked out from too many tries
method isAvailable
static isAvailable: () => Promise<any>;
Checks Whether TouchID is available or not.
Returns
{Promise} Returns a Promise that resolves if yes, rejects if no.
method verifyFingerprint
static verifyFingerprint: (message: string) => Promise<any>;
Show TouchID dialog and wait for a fingerprint scan. If user taps 'Enter Password' button, brings up standard system passcode screen.
Parameter message
The message to display
Returns
{Promise} Returns a Promise the resolves if the fingerprint scan was successful, rejects with an error code (see above).
method verifyFingerprintWithCustomPasswordFallback
static verifyFingerprintWithCustomPasswordFallback: ( message: string) => Promise<any>;
Show TouchID dialog and wait for a fingerprint scan. If user taps 'Enter Password' button, rejects with code '-3' (see above).
Parameter message
The message to display
Returns
{Promise} Returns a Promise the resolves if the fingerprint scan was successful, rejects with an error code (see above).
method verifyFingerprintWithCustomPasswordFallbackAndEnterPasswordLabel
static verifyFingerprintWithCustomPasswordFallbackAndEnterPasswordLabel: ( message: string, enterPasswordLabel: string) => Promise<any>;
Show TouchID dialog with custom 'Enter Password' message and wait for a fingerprint scan. If user taps 'Enter Password' button, rejects with code '-3' (see above).
Parameter message
The message to display
Parameter enterPasswordLabel
Custom text for the 'Enter Password' button
Returns
{Promise} Returns a Promise the resolves if the fingerprint scan was successful, rejects with an error code (see above).
class Transfer
class Transfer {}
Transfer
This plugin allows you to upload and download files.
import { Transfer } from 'ionic-native';// Create instance:const fileTransfer = new Transfer();// Upload a file:fileTransfer.upload(..).then(..).catch(..);// Download a file:fileTransfer.download(..).then(..).catch(..);// Abort active transfer:fileTransfer.abort();E.gupload(){const fileTransfer = new Transfer();var options: any;options = {fileKey: 'file',fileName: 'name.jpg',headers: {}.....}fileTransfer.upload("<file path>", "<api endpoint>", options).then((data) => {// success}, (err) => {// error})}// Cordovadeclare var cordova: any;download() {const fileTransfer = new Transfer();let url = 'http://www.example.com/file.pdf';fileTransfer.download(url, cordova.file.dataDirectory + 'file.pdf').then((entry) => {console.log('download complete: ' + entry.toURL());}, (error) => {// handle error});}Note: You will not see your documents using a file explorer on your device. Use adb:
adb shellrun-as com.your.appcd fileslsTo store files in a different/publicly accessible directory, please refer to the following link https://github.com/apache/cordova-plugin-file#where-to-store-files
FileUploadOptions FileUploadResult FileTransferError
constructor
constructor();
property FileTransferErrorCode
static FileTransferErrorCode: { FILE_NOT_FOUND_ERR: number; INVALID_URL_ERR: number; CONNECTION_ERR: number; ABORT_ERR: number; NOT_MODIFIED_ERR: number;};
Error code rejected from upload with FileTransferError Defined in FileTransferError. FILE_NOT_FOUND_ERR: 1 Return when file was not found INVALID_URL_ERR: 2, Return when url was invalid CONNECTION_ERR: 3, Return on connection error ABORT_ERR: 4, Return on aborting NOT_MODIFIED_ERR: 5 Return on "304 Not Modified" HTTP response {number}
method abort
abort: () => void;
Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of FileTransferError.ABORT_ERR.
method download
download: ( source: string, target: string, trustAllHosts?: boolean, options?: { [s: string]: any }) => Promise<any>;
Downloads a file from server.
Parameter source
URL of the server to download the file, as encoded by encodeURI().
Parameter target
Filesystem url representing the file on the device. For backwards compatibility, this can also be the full path of the file on the device.
Parameter trustAllHosts
Optional parameter, defaults to false. If set to true, it accepts all security certificates. This is useful because Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS.
Parameter Optional
parameters, currently only supports headers (such as Authorization (Basic Authentication), etc).
Returns
{Promise} Returns a Promise that resolves to a FileEntry object.
method onProgress
onProgress: (listener: (event: ProgressEvent) => any) => void;
Registers a listener that gets called whenever a new chunk of data is transferred.
Parameter Listener
that takes a progress event.
method upload
upload: ( fileUrl: string, url: string, options?: FileUploadOptions, trustAllHosts?: boolean) => Promise<FileUploadResult>;
Sends a file to a server.
Parameter fileUrl
Filesystem URL representing the file on the device or a data URI. For backwards compatibility, this can also be the full path of the file on the device.
Parameter url
URL of the server to receive the file, as encoded by encodeURI().
Parameter options
Optional parameters.
Parameter trustAllHosts
Optional parameter, defaults to false. If set to true, it accepts all security certificates. This is useful since Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS.
Returns
{Promise} Returns a Promise that resolves to a FileUploadResult and rejects with FileTransferError.
class TwitterConnect
class TwitterConnect {}
Twitter Connect Plugin to use Twitter Single Sign On Uses Twitter's Fabric SDK
import {TwitterConnect} from 'ionic-native';function onSuccess(response) {console.log(response);// Will console log something like:// {// userName: 'myuser',// userId: '12358102',// secret: 'tokenSecret'// token: 'accessTokenHere'// }}TwitterConnect.login().then(onSuccess, onError);TwitterConnect.logout().then(onLogoutSuccess, onLogoutError);TwitterConnectResponse
method login
static login: () => Promise<TwitterConnectResponse>;
Logs in
Returns
{Promise} returns a promise that resolves if logged in and rejects if failed to login
method logout
static logout: () => Promise<any>;
Logs out
Returns
{Promise} returns a promise that resolves if logged out and rejects if failed to logout
method showUser
static showUser: () => Promise<any>;
Returns user's profile information
Returns
{Promise} returns a promise that resolves if user profile is successfully retrieved and rejects if request fails
class UniqueDeviceID
class UniqueDeviceID {}
UniqueDeviceID This plugin produces a unique, cross-install, app-specific device id.
import { UniqueDeviceID } from 'ionic-native';UniqueDeviceID.get().then((uuid: any) => console.log(uuid)).catch((error: any) => console.log(error));
method get
static get: () => Promise<string>;
Gets a unique, cross-install, app-specific device id. {Promise} Returns a promise that resolves when something happens
class Vibration
class Vibration {}
Vibration Vibrates the device
import { Vibration } from 'ionic-native';// Vibrate the device for a second// Duration is ignored on iOS.Vibration.vibrate(1000);// Vibrate 2 seconds// Pause for 1 second// Vibrate for 2 seconds// Patterns work on Android and Windows onlyVibration.vibrate([2000,1000,2000]);// Stop any current vibrations immediately// Works on Android and Windows onlyVibration.vibrate(0);
method vibrate
static vibrate: (time: number | Array<number>) => void;
Vibrates the device for given amount of time.
Parameter time
Milliseconds to vibrate the device. If passed an array of numbers, it will define a vibration pattern. Pass 0 to stop any vibration immediately.
class VideoEditor
class VideoEditor {}
VideoEditor Edit videos using native device APIs
import {VideoEditor} from 'ionic-native';VideoEditor.transcodeVideo({fileUri: '/path/to/input.mov',outputFileName: 'output.mp4',outputFileType: VideoEditor.OutputFileType.MPEG4}).then((fileUri: string) => console.log('video transcode success', fileUri)).catch((error: any) => console.log('video transcode error', error));TranscodeOptions TrimOptions CreateThumbnailOptions GetVideoInfoOptions VideoInfo
property OptimizeForNetworkUse
static OptimizeForNetworkUse: { NO: number; YES: number };
property OutputFileType
static OutputFileType: { M4V: number; MPEG4: number; M4A: number; QUICK_TIME: number;};
method createThumbnail
static createThumbnail: (options: CreateThumbnailOptions) => Promise<string>;
Create a JPEG thumbnail from a video
Parameter options
Options
Returns
{Promise} Returns a promise that resolves to the path to the jpeg image on the device
method getVideoInfo
static getVideoInfo: (options: GetVideoInfoOptions) => Promise<VideoInfo>;
Get info on a video (width, height, orientation, duration, size, & bitrate)
Parameter options
Options
Returns
{Promise} Returns a promise that resolves to an object containing info on the video
method transcodeVideo
static transcodeVideo: (options: TranscodeOptions) => Promise<string>;
Transcode a video
Parameter options
Options
Returns
{Promise} Returns a promise that resolves to the path of the transcoded video
method trim
static trim: (options: TrimOptions) => Promise<string>;
Trim a video
Parameter options
Options
Returns
{Promise} Returns a promise that resolves to the path of the trimmed video
class VideoPlayer
class VideoPlayer {}
VideoPlayer A Codova plugin that simply allows you to immediately play a video in fullscreen mode.
Requires Cordova plugin:
com.moust.cordova.videoplayer
. For more info, please see the [VideoPlayer plugin docs](https://github.com/moust/cordova-plugin-videoplayer).import { VideoPlayer } from 'ionic-native';// Playing a video.VideoPlayer.play("file:///android_asset/www/movie.mp4").then(() => {console.log('video completed');}).catch(err => {console.log(err);});VideoOptions
method close
static close: () => void;
Stops the video playback immediatly.
method play
static play: (fileUrl: string, options?: VideoOptions) => Promise<any>;
Plays the video from the passed url.
Parameter fileUrl
File url to the video.
Parameter options
Optional video playback settings. See options above.
Returns
{Promise} Resolves promise when the video was played successfully.
class WebIntent
class WebIntent {}
WebIntent For usage information please refer to the plugin's Github repo.
import {WebIntent} from 'ionic-native';WebIntent.startActivity(options).then(onSuccess, onError);
property ACTION_VIEW
static ACTION_VIEW: any;
property EXTRA_TEXT
static EXTRA_TEXT: any;
method getExtra
static getExtra: (extra: any) => Promise<any>;
Parameter extra
Returns
{Promise}
method getUri
static getUri: () => Promise<string>;
Returns
{Promise}
method hasExtra
static hasExtra: (extra: any) => Promise<any>;
Parameter extra
Returns
{Promise}
method onNewIntent
static onNewIntent: () => Promise<string>;
Returns
{Promise}
method sendBroadcast
static sendBroadcast: (options: { action: string; extras?: { option: boolean };}) => Promise<any>;
Parameter options
{ action: string, extras?: { option: boolean } }
Returns
{Promise}
method startActivity
static startActivity: (options: { action: any; url: string; type?: string;}) => Promise<any>;
Parameter options
{ action: any, url: string, type?: string }
Returns
{Promise}
class YoutubeVideoPlayer
class YoutubeVideoPlayer {}
YoutubeVideoPlayer Plays YouTube videos in Native YouTube App
import {YoutubeVideoPlayer} from 'ionic-native';YoutubeVideoPlayer.openVideo('myvideoid');
method openVideo
static openVideo: (videoId: string) => void;
Plays a YouTube video
Parameter videoId
Video ID
class ZBar
class ZBar {}
ZBar The ZBar Scanner Plugin allows you to scan 2d barcodes.
Requires Cordova plugin:
cordova-plugin-cszbar
. For more info, please see the [zBar plugin docs](https://github.com/tjwoon/csZBar).import { ZBar } from 'ionic-native';let zBarOptions = {flash: "off",drawSight: false};ZBar.scan(zBarOptions).then(result => {console.log(result); // Scanned code}).catch(error => {console.log(error); // Error message});ZBarOptions
method scan
static scan: (options: ZBarOptions) => Promise<any>;
Open the scanner
Parameter options
Scan options
Returns
{Promise} Returns a Promise that resolves with the scanned string, or rejects with an error.
class Zip
class Zip {}
Zip A Cordova plugin to unzip files in Android and iOS.
import {Zip} from 'ionic-native';Zip.unzip('path/to/source.zip', 'path/to/dest', (progress) => console.log('Unzipping, ' + Math.round((progress.loaded / progress.total) * 100) + '%')).then((result) => {if(result === 0) console.log('SUCCESS');if(result === -1) console.log('FAILED');});
method unzip
static unzip: ( sourceZip: string, destUrl: string, onProgress?: Function) => Promise<number>;
Extracts files from a ZIP archive
Parameter sourceZip
Source ZIP file
Parameter destUrl
Destination folder
Parameter onProgress
optional callback to be called on progress update
Returns
{Promise} returns a promise that resolves with a number. 0 is success, -1 is error
Interfaces
interface ActionSheetOptions
interface ActionSheetOptions {}
property addCancelButtonWithLabel
addCancelButtonWithLabel?: string;
Add a cancel button with text
property addDestructiveButtonWithLabel
addDestructiveButtonWithLabel?: string;
Add a destructive button with text
property androidEnableCancelButton
androidEnableCancelButton?: boolean;
Enable a cancel on Android
property androidTheme
androidTheme?: number;
Theme to be used on Android
property buttonLabels
buttonLabels: string[];
The labels for the buttons. Uses the index x
property position
position?: number[];
On an iPad, set the X,Y position
property title
title?: string;
The title for the actionsheet
property winphoneEnableCancelButton
winphoneEnableCancelButton?: boolean;
Enable a cancel on Windows Phone
interface AdMobAdExtras
interface AdMobAdExtras {}
property color_bg
color_bg: string;
property color_bg_top
color_bg_top: string;
property color_border
color_border: string;
property color_link
color_link: string;
property color_text
color_text: string;
property color_url
color_url: string;
interface AdMobOptions
interface AdMobOptions {}
property adExtras
adExtras?: AdMobAdExtras;
Set extra color style for Ad
property adId
adId?: string;
Banner ad ID
property adSize
adSize?: AdMobAdSize;
Banner Ad Size, defaults to
SMART_BANNER
. IT can be:SMART_BANNER
,BANNER
,MEDIUM_RECTANGLE
,FULL_BANNER
,LEADERBOARD
,SKYSCRAPER
, orCUSTOM
property autoShow
autoShow?: boolean;
Auto show interstitial ad when loaded. Set to false if hope to control the show timing with prepareInterstitial/showInterstitial
property height
height?: number;
Banner height, valid when
adSize
is set toCUSTOM
property isTesting
isTesting?: boolean;
Set to true to receive test ad for testing purposes
property orientationRenew
orientationRenew?: boolean;
Re-create the banner on web view orientation change (not screen orientation), or else just move the banner. Default:true.
property overlap
overlap?: boolean;
Allow banner to overlap webview, or else it will push webview up or down to avoid overlap. Defaults to false.
property position
position?: number;
Position of banner ad. Defaults to
TOP_CENTER
. You can use theAdMob.AD_POSITION
property to select other values.
property width
width?: number;
Banner width, valid when
adSize
is set toCUSTOM
property x
x?: number;
X in pixels. Valid when
position
is set toPOS_XY
property y
y?: number;
Y in pixels. Valid when
position
is set toPOS_XY
interface AlbumItem
interface AlbumItem {}
interface AlipayOrder
interface AlipayOrder {}
https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.wlOhAE&treeId=193&articleId=105465&docType=1
All values need be urlencoded.
property app_id
app_id: string;
appId assigned by Alipay
property biz_content
biz_content: string;
biz content. formated in json. see alipay doc for detail.
property charset
charset: string;
Charset Possible values: "UTF-8", "GBK" Default: "UTF-8"
property format
format?: string;
Data format Default: "JSON"
property method
method: string;
Api name. Should be: alipay.trade.app.pay
property notify_url
notify_url: string;
Notify url.
property sign
sign: string;
Sign value. Should be got from server side. Default: 'RSA'
property sign_type
sign_type: string;
Sign method Default: 'RSA'
property timestamp
timestamp: string;
Timestamp, formated like "yyyy-MM-dd HH:mm:ss", e.g. 2014-07-24 03:07:50
property version
version: string;
Api version. Fixed value '1.0'
interface AndroidFingerprintAuthOptions
interface AndroidFingerprintAuthOptions {}
property clientId
clientId: string;
Required Used as the alias for your key in the Android Key Store.
property dialogHint
dialogHint?: string;
Set the hint displayed by the fingerprint icon on the fingerprint authentication dialog.
property dialogMessage
dialogMessage?: string;
Set the message of the fingerprint authentication dialog.
property dialogTitle
dialogTitle?: string;
Set the title of the fingerprint authentication dialog.
property disableBackup
disableBackup?: boolean;
Set to true to remove the "USE BACKUP" button
property locale
locale?: string;
Change the language. (en_US or es)
property maxAttempts
maxAttempts?: number;
The device max is 5 attempts. Set this parameter if you want to allow fewer than 5 attempts.
property password
password?: string;
Used to create credential string for encrypted token
property token
token?: string;
Required for decrypt() Encrypted user credentials to decrypt upon successful authentication.
property userAuthRequired
userAuthRequired?: boolean;
Require the user to authenticate with a fingerprint to authorize every use of the key. New fingerprint enrollment will invalidate key and require backup authenticate to re-enable the fingerprint authentication dialog.
property username
username?: string;
Used to create credential string for encrypted token and as alias to retrieve the cipher.
interface AndroidPushOptions
interface AndroidPushOptions {}
property clearBadge
clearBadge?: boolean | string;
If true the icon badge will be cleared on init and before push messages are processed.
property clearNotifications
clearNotifications?: boolean | string;
If true the app clears all pending notifications when it is closed.
property forceShow
forceShow?: boolean | string;
If true will always show a notification, even when the app is on the foreground.
property icon
icon?: string;
The name of a drawable resource to use as the small-icon. The name should not include the extension.
property iconColor
iconColor?: string;
Sets the background color of the small icon on Android 5.0 and greater. [Supported Formats](http://developer.android.com/intl/ru/reference/android/graphics/Color.html#parseColor(java.lang.String))
property senderID
senderID: string;
Maps to the project number in the Google Developer Console.
property sound
sound?: boolean | string;
If true it plays the sound specified in the push data or the default system sound.
property topics
topics?: string[];
If the array contains one or more strings each string will be used to subscribe to a GcmPubSub topic.
property vibrate
vibrate?: boolean | string;
If true the device vibrates on receipt of notification.
interface AnimateCameraOptions
interface AnimateCameraOptions {}
interface AppRateCallbacks
interface AppRateCallbacks {}
property onButtonClicked
onButtonClicked?: Function;
call back function. called when user clicked on rate-dialog buttons
property onRateDialogShow
onRateDialogShow?: Function;
call back function. called when rate-dialog showing
interface AppRatePreferences
interface AppRatePreferences {}
property callbacks
callbacks?: AppRateCallbacks;
Callbacks for events
property customLocale
customLocale?: any;
Custom locale object
property displayAppName
displayAppName?: string;
Custom application title
property openStoreInApp
openStoreInApp?: boolean;
leave app or no when application page opened in app store (now supported only for iOS). Defaults to
false
property promptAgainForEachNewVersion
promptAgainForEachNewVersion?: boolean;
Show dialog again when application version will be updated. Defaults to
true
property storeAppURL
storeAppURL?: AppRateStoreAppUrls;
App Store URLS
property useCustomRateDialog
useCustomRateDialog?: boolean;
use custom view for rate dialog. Defaults to
false
property useLanguage
useLanguage?: string;
Custom BCP 47 language tag
property usesUntilPrompt
usesUntilPrompt?: number;
count of runs of application before dialog will be displayed. Defaults to
3
interface AppRateStoreAppUrls
interface AppRateStoreAppUrls {}
property android
android?: string;
application URL in GooglePlay
property blackberry
blackberry?: string;
application URL in AppWorld
property ios
ios?: string;
application id in AppStore
property windows
windows?: string;
application URL in Windows Store
property windows8
windows8?: string;
application URL in WindowsStore
interface BackgroundFetchConfig
interface BackgroundFetchConfig {}
property stopOnTerminate
stopOnTerminate?: boolean;
Set true to cease background-fetch from operating after user "closes" the app. Defaults to true.
interface BackgroundGeolocationConfig
interface BackgroundGeolocationConfig {}
property activitiesInterval
activitiesInterval?: number;
ANDROID ONLY with BackgroundGeolocation.LocationProvider.ANDROID_ACTIVITY_PROVIDER
Rate in milliseconds at which activity recognition occurs. Larger values will result in fewer activity detections while improving battery life.
property activityType
activityType?: string;
IOS ONLY [AutomotiveNavigation, OtherNavigation, Fitness, Other] Presumably, this affects iOS GPS algorithm.
See Also
Apple docs for more information (https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html#//apple_ref/occ/instp/CLLocationManager/activityType)
property debug
debug?: boolean;
When enabled, the plugin will emit sounds for life-cycle events of background-geolocation! See debugging sounds table.
property desiredAccuracy
desiredAccuracy: number;
Desired accuracy in meters. Possible values [0, 10, 100, 1000]. The lower the number, the more power devoted to GeoLocation resulting in higher accuracy readings. 1000 results in lowest power drain and least accurate readings.
See Also
Apple docs (https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/index.html#//apple_ref/occ/instp/CLLocationManager/desiredAccuracy)
property distanceFilter
distanceFilter: number;
The minimum distance (measured in meters) a device must move horizontally before an update event is generated.
See Also
Apple docs. (https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html#//apple_ref/occ/instp/CLLocationManager/distanceFilter)
property fastestInterval
fastestInterval?: number;
ANDROID ONLY with BackgroundGeolocation.LocationProvider.ANDROID_ACTIVITY_PROVIDER
Fastest rate in milliseconds at which your app can handle location updates.
See Also
Android docs (https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest.html#getFastestInterval())
property httpHeaders
httpHeaders?: any;
Optional HTTP headers sent along in HTTP request
property interval
interval?: number;
ANDROID, WP8 ONLY When using BackgroundGeolocation.LocationProvider.ANDROID_DISTANCE_FILTER_PROVIDER: The minimum time interval between location updates in milliseconds.
See Also
Android docs (http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(long,%20float,%20android.location.Criteria,%20android.app.PendingIntent)) and the MS doc (http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator.reportinterval) for more information When using BackgroundGeolocation.LocationProvider.ANDROID_ACTIVITY_PROVIDER: Rate in milliseconds at which your app prefers to receive location updates.
Android docs (https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest.html#getInterval())
property locationProvider
locationProvider?: number;
ANDROID ONLY Set location service provider
See Also
wiki (https://github.com/mauron85/cordova-plugin-background-geolocation/wiki/Android-providers)
property maxLocations
maxLocations?: number;
Limit maximum number of locations stored into db
Defaults to 10000
property notificationIconColor
notificationIconColor?: string;
ANDROID ONLY The accent color to use for notification. Eg. #4CAF50.
property notificationIconLarge
notificationIconLarge?: string;
ANDROID ONLY
The filename of a custom notification icon. See android quirks.
NOTE: Only available for API Level >=21.
property notificationIconSmall
notificationIconSmall?: string;
ANDROID ONLY
The filename of a custom notification icon. See android quirks.
NOTE: Only available for API Level >=21.
property notificationText
notificationText?: string;
ANDROID ONLY Custom notification text in the drawer.
property notificationTitle
notificationTitle?: string;
ANDROID ONLY Custom notification title in the drawer.
property pauseLocationUpdates
pauseLocationUpdates?: boolean;
IOS ONLY
Pauses location updates when app is paused
Defaults to true
property saveBatteryOnBackground
saveBatteryOnBackground?: boolean;
IOS ONLY
Switch to less accurate significant changes and region monitory when in background (default)
Defaults to 100
property startForeground
startForeground?: boolean;
ANDROID ONLY
If false location service will not be started in foreground and no notification will be shown.
Defaults to true
property startOnBoot
startOnBoot?: boolean;
ANDROID ONLY
Start background service on device boot.
Defaults to false
property stationaryRadius
stationaryRadius: number;
Stationary radius in meters. When stopped, the minimum distance the device must move beyond the stationary location for aggressive background-tracking to engage.
property stopOnStillActivity
stopOnStillActivity?: boolean;
ANDROID ONLY with BackgroundGeolocation.LocationProvider.ANDROID_ACTIVITY_PROVIDER
stop() is forced, when the STILL activity is detected (default is true)
property stopOnTerminate
stopOnTerminate?: boolean;
IOS, ANDROID ONLY Enable this in order to force a stop() when the application terminated (e.g. on iOS, double-tap home button, swipe away the app).o
Defaults to true
property syncThreshold
syncThreshold?: number;
Specifies how many previously failed locations will be sent to server at once
Defaults to 100
property syncUrl
syncUrl?: string;
Server url where to send fail to post locations
See Also
https://github.com/mauron85/cordova-plugin-background-geolocation#http-locations-posting
property url
url?: string;
Server url where to send HTTP POST with recorded locations
See Also
https://github.com/mauron85/cordova-plugin-background-geolocation#http-locations-posting
interface BackgroundGeolocationResponse
interface BackgroundGeolocationResponse {}
property accuracy
accuracy: number;
estimated accuracy of this location, in meters.
property altitude
altitude: number;
altitude if available, in meters above the WGS 84 reference ellipsoid.
property altitudeAccuracy
altitudeAccuracy: number;
accuracy of the altitude if available.
property bearing
bearing: number;
bearing, in degrees.
property coords
coords: Coordinates;
A Coordinates object defining the current location
property debug
debug: boolean;
true if location recorded as part of debug
property latitude
latitude: number;
latitude, in degrees.
property locationId
locationId: number;
ID of location as stored in DB (or null)
property longitude
longitude: number;
longitude, in degrees.
property serviceProvider
serviceProvider: string;
Service provider
property speed
speed: number;
speed if it is available, in meters/second over ground.
property time
time: number;
UTC time of this fix, in milliseconds since January 1, 1970.
property timestamp
timestamp: number;
A timestamp representing the time at which the location was retrieved.
interface BackgroundModeConfiguration
interface BackgroundModeConfiguration {}
Configurations items that can be updated.
property resume
resume?: boolean;
By default the app will come to foreground when taping on the notification. If false, plugin wont come to foreground when tapped.
property silent
silent?: boolean;
if true plugin will not display a notification. Default is false.
property text
text?: String;
Description of background task
property ticker
ticker?: String;
The text that scrolls itself on statusbar
property title
title?: String;
Title of the background task
interface BarcodeScannerOptions
interface BarcodeScannerOptions {}
property disableAnimations
disableAnimations?: boolean;
Disable animations. Supported on iOS only.
property disableSuccessBeep
disableSuccessBeep?: boolean;
Disable success beep. Supported on iOS only.
property formats
formats?: string;
Formats separated by commas. Defaults to all formats except
PDF_417
andRSS_EXPANDED
.
property orientation
orientation?: string;
Orientation. Supported on Android only. Can be set to
portrait
orlandscape
. Defaults to none so the user can rotate the phone and pick an orientation.
property preferFrontCamera
preferFrontCamera?: boolean;
Prefer front camera. Supported on iOS and Android.
property prompt
prompt?: string;
Prompt text. Supported on Android only.
property resultDisplayDuration
resultDisplayDuration?: number;
Display scanned text for X ms. 0 suppresses it entirely, default 1500. Supported on Android only.
property showFlipCameraButton
showFlipCameraButton?: boolean;
Show flip camera button. Supported on iOS and Android.
property showTorchButton
showTorchButton?: boolean;
Show torch button. Supported on iOS and Android.
property torchOn
torchOn?: boolean;
Launch with the torch switched on (if available). Supported on Android only.
interface BatteryStatusResponse
interface BatteryStatusResponse {}
interface Beacon
interface Beacon {}
property accuracy
accuracy: number;
The accuracy of the ranging.
property major
major: number;
The beacon's major identifier number.
property minor
minor: number;
The beacon's major identifier number.
property proximity
proximity: | 'ProximityImmediate' | 'ProximityNear' | 'ProximityFar' | 'ProximityUnknown';
The proximity of the beacon relative to the phone.
Possible options are: ProximityImmediate ProximityNear ProximityFar ProximityUnknown
property rssi
rssi: number;
Received Signal Strength Indicator. The strength of the beacon's signal when it reaches the device. RSSI ranges from aprox -26 (a few inches) to -100 (40-50 m distance).
property tx
tx: number;
Transmission Power of the beacon. A constant emitted by the beacon which indicates what's the expected RSSI at a distance of 1 meter to the beacon.
property uuid
uuid: string;
The physical device's identifier.
interface BeaconRegion
interface BeaconRegion {}
property identifier
identifier: string;
A unique identifier for this region.
property major
major?: number;
The beacon's major identifier number. Optional, of nothing is supplied the plugin will treat it as a wildcard.
property minor
minor?: number;
The beacon's minor identifier number. Optional, of nothing is supplied the plugin will treat it as a wildcard.
property notifyEntryStateOnDisplay
notifyEntryStateOnDisplay?: boolean;
If set to true the device will scan for beacons and determine region state anytime the device's screen is turned on or off. Useful for debugging.
property uuid
uuid: string;
The the beacon identifier the device will "watch" for. Many beacons can share the same uuid.
interface CalendarOptions
interface CalendarOptions {}
property calendarId
calendarId?: number;
Calendar id
property calendarName
calendarName?: string;
Calendar name. Ths is supported by
iOS
only.
property firstReminderMinutes
firstReminderMinutes?: number;
property id
id?: string;
Id
property recurrence
recurrence?: string;
Recurrence. Can be set to
daily
,weekly
,monthly
oryearly
property recurrenceEndDate
recurrenceEndDate?: Date;
Recurrence end date. Valid only when
recurrence
option is set.
property recurrenceInterval
recurrenceInterval?: number;
Recurrence interval. Valid only when
recurrence
option is set.
property secondReminderMinutes
secondReminderMinutes?: number;
property url
url?: string;
URL
interface Callback
interface Callback<T> {}
call signature
(error: Error, parameter: T): void;
interface CameraOptions
interface CameraOptions {}
property allowEdit
allowEdit?: boolean;
Allow simple editing of image before selection.
property cameraDirection
cameraDirection?: number;
Choose the camera to use (front- or back-facing). Defined in Camera.Direction. Default is BACK. BACK: 0 FRONT: 1
property correctOrientation
correctOrientation?: boolean;
Rotate the image to correct for the orientation of the device during capture.
property destinationType
destinationType?: number;
Choose the format of the return value. Defined in Camera.DestinationType. Default is FILE_URI. DATA_URL : 0, Return image as base64-encoded string, FILE_URI : 1, Return image file URI, NATIVE_URI : 2 Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
property encodingType
encodingType?: number;
Choose the returned image file's encoding. Defined in Camera.EncodingType. Default is JPEG JPEG : 0 Return JPEG encoded image PNG : 1 Return PNG encoded image
property mediaType
mediaType?: number;
Set the type of media to select from. Only works when PictureSourceType is PHOTOLIBRARY or SAVEDPHOTOALBUM. Defined in Camera.MediaType PICTURE: 0 allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType VIDEO: 1 allow selection of video only, WILL ALWAYS RETURN FILE_URI ALLMEDIA : 2 allow selection from all media types
property popoverOptions
popoverOptions?: CameraPopoverOptions;
iOS-only options that specify popover location in iPad. Defined in CameraPopoverOptions.
property quality
quality?: number;
Picture quality in range 0-100. Default is 50
property saveToPhotoAlbum
saveToPhotoAlbum?: boolean;
Save the image to the photo album on the device after capture.
property sourceType
sourceType?: number;
Set the source of the picture. Defined in Camera.PictureSourceType. Default is CAMERA. PHOTOLIBRARY : 0, CAMERA : 1, SAVEDPHOTOALBUM : 2
property targetHeight
targetHeight?: number;
Height in pixels to scale image. Must be used with targetWidth. Aspect ratio remains constant.
property targetWidth
targetWidth?: number;
Width in pixels to scale image. Must be used with targetHeight. Aspect ratio remains constant.
interface CameraPopoverOptions
interface CameraPopoverOptions {}
iOS-only parameters that specify the anchor element location and arrow direction of the popover when selecting images from an iPad's library or album.
property arrowDir
arrowDir: number;
Direction the arrow on the popover should point. Defined in Camera.PopoverArrowDirection Matches iOS UIPopoverArrowDirection constants. ARROW_UP : 1, ARROW_DOWN : 2, ARROW_LEFT : 4, ARROW_RIGHT : 8, ARROW_ANY : 15
property height
height: number;
property width
width: number;
property x
x: number;
property y
y: number;
interface CameraPosition
interface CameraPosition {}
interface CameraPreviewRect
interface CameraPreviewRect {}
interface CameraPreviewSize
interface CameraPreviewSize {}
interface CaptureAudioOptions
interface CaptureAudioOptions {}
interface CaptureError
interface CaptureError {}
property code
code: string;
interface CaptureImageOptions
interface CaptureImageOptions {}
property limit
limit?: number;
Maximum number of images to capture. This limit is not supported on iOS, only one image will be taken per invocation.
interface CaptureVideoOptions
interface CaptureVideoOptions {}
property duration
duration?: number;
Maximum duration per video clip. This will be ignored on BlackBerry.
property limit
limit?: number;
Maximum number of video clips to record. This value is ignored on iOS, only one video clip can be taken per invocation.
property quality
quality?: number;
Quality of the video. This parameter can only be used with Android.
interface CardIOOptions
interface CardIOOptions {}
property guideColor
guideColor?: string;
Changes the color of the guide overlay on the camera. The color is provided in hexadecimal format (e.g.
#FFFFFF
)
property hideCardIOLogo
hideCardIOLogo?: boolean;
The card.io logo will not be shown overlaid on the camera.
property keepApplicationTheme
keepApplicationTheme?: boolean;
The theme for the card.io Activity's will be set to the theme of the application.
property languageOrLocale
languageOrLocale?: string;
The preferred language for all strings appearing in the user interface. If not set, or if set to null, defaults to the device's current language setting.
property noCamera
noCamera?: boolean;
If set, the card will not be scanned with the camera.
property requireCardholderName
requireCardholderName?: boolean;
The user will be prompted for the cardholder name
property requireCVV
requireCVV?: boolean;
The user will be prompted for the card CVV
property requireExpiry
requireExpiry?: boolean;
Set to true to require expiry date
property requirePostalCode
requirePostalCode?: boolean;
The user will be prompted for the card billing postal code.
property restrictPostalCodeToNumericOnly
restrictPostalCodeToNumericOnly?: boolean;
The postal code will only collect numeric input. Set this if you know the expected country's postal code has only numeric postal codes.
property scanExpiry
scanExpiry?: boolean;
If scanExpiry is true, an attempt to extract the expiry from the card image will be made.
property scanInstructions
scanInstructions?: string;
Used to display instructions to the user while they are scanning their card.
property supressConfirmation
supressConfirmation?: boolean;
The user will not be prompted to confirm their card number after processing.
property supressManual
supressManual?: boolean;
Removes the keyboard button from the scan screen.
property supressScan
supressScan?: boolean;
Once a card image has been captured but before it has been processed, this value will determine whether to continue processing as usual.
property useCardIOLogo
useCardIOLogo?: boolean;
The card.io logo will be shown instead of the PayPal logo.
interface CardIOResponse
interface CardIOResponse {}
property cardholderName
cardholderName: string;
Cardholder name
property cardNumber
cardNumber: string;
Full card number
property cardType
cardType: string;
Card type
property cvv
cvv: string;
CVV
property expiryMonth
expiryMonth: number;
Expiry month
property expiryYear
expiryYear: number;
Expiry year
property postalCode
postalCode: string;
Postal code
property redactedCardNumber
redactedCardNumber: string;
Masked card number, showing only last 4 digits
interface CategoryAction
interface CategoryAction {}
interface CategoryActionData
interface CategoryActionData {}
property callback
callback: string;
property destructive
destructive: boolean;
property foreground
foreground: boolean;
property title
title: string;
interface CategoryArray
interface CategoryArray {}
index signature
[name: string]: CategoryAction;
interface CircularRegion
interface CircularRegion {}
property identifier
identifier: string;
A unique identifier for this region.
property latitude
latitude: number;
The latitude of this region.
property longitude
longitude: number;
The longitude of this region.
property radius
radius: number;
The radius of the geofence for this region.
interface ConfigurationData
interface ConfigurationData {}
property height
height: number;
The height of the image or video in pixels. The value is zero for sound clips.
property type
type: string;
The ASCII-encoded lowercase string representing the media type.
property width
width: number;
The width of the image or video in pixels. The value is zero for sound clips.
interface Coordinates
interface Coordinates {}
property accuracy
accuracy: number;
A double representing the accuracy of the latitude and longitude properties, expressed in meters.
property altitude
altitude: number;
A double representing the position's altitude in metres, relative to sea level. This value can be null if the implementation cannot provide the data.
property altitudeAccuracy
altitudeAccuracy: number;
A double representing the accuracy of the altitude expressed in meters. This value can be null.
property heading
heading: number;
A double representing the direction in which the device is traveling. This value, specified in degrees, indicates how far off from heading true north the device is. 0 degrees represents true north, and the direction is determined clockwise (which means that east is 90 degrees and west is 270 degrees). If speed is 0, heading is NaN. If the device is unable to provide heading information, this value is null.
property latitude
latitude: number;
a double representing the position's latitude in decimal degrees.
property longitude
longitude: number;
A double representing the position's longitude in decimal degrees.
property speed
speed: number;
A double representing the velocity of the device in meters per second. This value can be null.
interface CordovaFiniteObservableOptions
interface CordovaFiniteObservableOptions extends CordovaOptions {}
property resultFinalPredicate
resultFinalPredicate?: (result: any) => boolean;
Function that gets a result returned from plugin's success callback, and decides whether it is last value and observable should complete.
property resultTransform
resultTransform?: (result: any) => any;
Function that gets called after resultFinalPredicate, and removes service data that indicates end of stream from the result.
interface CordovaOptions
interface CordovaOptions {}
property callbackOrder
callbackOrder?: 'reverse';
Callback order. Set to reverse if the success/error callbacks are the first 2 arguments that the wrapped method takes.
property callbackStyle
callbackStyle?: 'node' | 'object';
Callback style
property clearFunction
clearFunction?: string;
If observable is set to true, this can be set to a different function name that will cancel the observable.
property clearWithArgs
clearWithArgs?: boolean;
This can be used if clearFunction is set. Set this to true to call the clearFunction with the same arguments used in the initial function.
property element
element?: any;
Element to attach the event listener to, this is optional, defaults to
window
property errorIndex
errorIndex?: number;
Set a custom index for the error callback function. This doesn't work if callbackOrder or callbackStyle are set.
property errorName
errorName?: string;
Error function property name. This must be set if callbackStyle is set to object.
property event
event?: string;
Event name, this must be set if eventObservable is set to true
property eventObservable
eventObservable?: boolean;
Creates an observable that wraps a global event. Replaces document.addEventListener
property observable
observable?: boolean;
Set to true to return an observable
property otherPromise
otherPromise?: boolean;
Set to true if the wrapped method returns a promise
property platforms
platforms?: string[];
Supported platforms
property successIndex
successIndex?: number;
Set a custom index for the success callback function. This doesn't work if callbackOrder or callbackStyle are set.
property successName
successName?: string;
Success function property name. This must be set if callbackStyle is set to object.
property sync
sync?: boolean;
Set to true if the wrapped method is a sync function
interface CreateThumbnailOptions
interface CreateThumbnailOptions {}
property atTime
atTime?: number;
Location in the video to create the thumbnail (in seconds)
property fileUri
fileUri: string;
The path to the video on the device
property height
height?: number;
Height of the thumbnail.
property outputFileName
outputFileName: string;
The file name for the JPEG image
property quality
quality?: number;
Quality of the thumbnail (between 1 and 100).
property width
width?: number;
Width of the thumbnail.
interface DatePickerOptions
interface DatePickerOptions {}
property allowFutureDates
allowFutureDates?: boolean;
Shows or hide dates after selected date.
property allowOldDates
allowOldDates?: boolean;
Shows or hide dates earlier then selected date.
property androidTheme
androidTheme?: number;
Choose the Android theme for the picker. You can use the DatePicker.ANDROID_THEMES property. Values: 1: THEME_TRADITIONAL | 2: THEME_HOLO_DARK | 3: THEME_HOLO_LIGHT | 4: THEME_DEVICE_DEFAULT_DARK | 5: THEME_DEVICE_DEFAULT_LIGHT
property cancelButtonColor
cancelButtonColor?: string;
Hex color of cancel button.
property cancelButtonLabel
cancelButtonLabel?: string;
Label of cancel button.
property cancelText
cancelText?: string;
Label of BUTTON_NEGATIVE (cancel button). If empty, uses android.R.string.cancel.
property date
date: Date | string | number;
Selected date
property doneButtonColor
doneButtonColor?: string;
Hex color of done button.
property doneButtonLabel
doneButtonLabel?: string;
Label of done button.
property is24Hour
is24Hour?: boolean;
Shows time dialog in 24 hours format.
property locale
locale?: string;
Force locale for datePicker.
property maxDate
maxDate?: Date | string | number;
Maximum date Default?: empty String
property minDate
minDate?: Date | string | number;
Minimum date Default: empty String
property minuteInterval
minuteInterval?: number;
Interval between options in the minute section of the date picker.
property mode
mode: string;
The mode of the date picker Values: date | time | datetime
property nowText
nowText?: string;
Label of now button. If empty, doesn't show the option to select current time.
property okText
okText?: string;
Label of BUTTON_POSITIVE (done button) on Android
property popoverArrowDirection
popoverArrowDirection?: string;
Force the UIPopoverArrowDirection enum. The value any will revert to default UIPopoverArrowDirectionAny and let the app choose the proper direction itself.
property titleText
titleText?: string;
Label for the dialog title. If empty, uses android default (Set date/Set time). Default?: empty String
property todayText
todayText?: string;
Label of today button. If empty, doesn't show the option to select current date.
property x
x?: number;
X position of date picker. The position is absolute to the root view of the application.
property y
y?: number;
Y position of date picker. The position is absolute to the root view of the application.
interface DeeplinkMatch
interface DeeplinkMatch {}
property $args
$args: any;
Any arguments passed either through route parameters or GET parameters
property $link
$link: any;
The deeplink object processed from the plugin, along with any any internal native data available as "extras" at the time the route was matched (for example, Facebook sometimes adds extra data)
property $route
$route: any;
The route info for the matched route
interface DeviceMotionAccelerationData
interface DeviceMotionAccelerationData {}
interface DeviceMotionAccelerometerOptions
interface DeviceMotionAccelerometerOptions {}
property frequency
frequency?: number;
Requested period of calls to accelerometerSuccess with acceleration data in Milliseconds. Default: 10000
interface DeviceOrientationCompassHeading
interface DeviceOrientationCompassHeading {}
property headingAccuracy
headingAccuracy: number;
The deviation in degrees between the reported heading and the true heading. (Number)
property magneticHeading
magneticHeading: number;
The heading in degrees from 0-359.99 at a single moment in time. (Number)
property timestamp
timestamp: any;
The time at which this heading was determined. (DOMTimeStamp)
property trueHeading
trueHeading: number;
The heading relative to the geographic North Pole in degrees 0-359.99 at a single moment in time. A negative value indicates that the true heading can't be determined. (Number)
interface DeviceOrientationCompassOptions
interface DeviceOrientationCompassOptions {}
interface DialogsPromptCallback
interface DialogsPromptCallback {}
property buttonIndex
buttonIndex: number;
The index of the pressed button. (Number) Note that the index uses one-based indexing, so the value is 1, 2, 3, etc.
property input1
input1: string;
The text entered in the prompt dialog box. (String)
interface DirectoryEntry
interface DirectoryEntry extends Entry {}
This interface represents a directory on a file system.
method createReader
createReader: () => DirectoryReader;
Creates a new DirectoryReader to read Entries from this Directory.
method getDirectory
getDirectory: ( path: string, options?: Flags, successCallback?: (entry: DirectoryEntry) => void, errorCallback?: (error: FileError) => void) => void;
Creates or looks up a directory.
Parameter path
Either an absolute path or a relative path from this DirectoryEntry to the directory to be looked up or created. It is an error to attempt to create a directory whose immediate parent does not yet exist.
Parameter options
If create and exclusive are both true and the path already exists, getDirectory must fail. If create is true, the path doesn't exist, and no other error occurs, getDirectory must create and return a corresponding DirectoryEntry. If create is not true and the path doesn't exist, getDirectory must fail. If create is not true and the path exists, but is a file, getDirectory must fail. Otherwise, if no other error occurs, getDirectory must return a DirectoryEntry corresponding to path.
Parameter successCallback
A callback that is called to return the Directory selected or created.
Parameter errorCallback
A callback that is called when errors happen.
method getFile
getFile: ( path: string, options?: Flags, successCallback?: (entry: FileEntry) => void, errorCallback?: (error: FileError) => void) => void;
Creates or looks up a file.
Parameter path
Either an absolute path or a relative path from this DirectoryEntry to the file to be looked up or created. It is an error to attempt to create a file whose immediate parent does not yet exist.
Parameter options
If create and exclusive are both true, and the path already exists, getFile must fail. If create is true, the path doesn't exist, and no other error occurs, getFile must create it as a zero-length file and return a corresponding FileEntry. If create is not true and the path doesn't exist, getFile must fail. If create is not true and the path exists, but is a directory, getFile must fail. Otherwise, if no other error occurs, getFile must return a FileEntry corresponding to path.
Parameter successCallback
A callback that is called to return the File selected or created.
Parameter errorCallback
A callback that is called when errors happen.
method removeRecursively
removeRecursively: ( successCallback: () => void, errorCallback?: (error: FileError) => void) => void;
Deletes a directory and all of its contents, if any. In the event of an error (e.g. trying to delete a directory that contains a file that cannot be removed), some of the contents of the directory may be deleted. It is an error to attempt to delete the root directory of a filesystem.
Parameter successCallback
A callback that is called on success.
Parameter errorCallback
A callback that is called when errors happen.
interface DirectoryReader
interface DirectoryReader {}
This interface lets a user list files and directories in a directory. If there are no additions to or deletions from a directory between the first and last call to readEntries, and no errors occur, then: A series of calls to readEntries must return each entry in the directory exactly once. Once all entries have been returned, the next call to readEntries must produce an empty array. If not all entries have been returned, the array produced by readEntries must not be empty. The entries produced by readEntries must not include the directory itself ["."] or its parent [".."].
method readEntries
readEntries: ( successCallback: (entries: Entry[]) => void, errorCallback?: (error: FileError) => void) => void;
Read the next block of entries from this directory.
Parameter successCallback
Called once per successful call to readEntries to deliver the next previously-unreported set of Entries in the associated Directory. If all Entries have already been returned from previous invocations of readEntries, successCallback must be called with a zero-length array as an argument.
Parameter errorCallback
A callback indicating that there was an error reading from the Directory.
interface DownloadProgress
interface DownloadProgress {}
Defines the format of the DownloadProgress object, used to send periodical update notifications on the progress of the update download.
property receivedBytes
receivedBytes: number;
property totalBytes
totalBytes: number;
interface EmailComposerOptions
interface EmailComposerOptions {}
interface Entry
interface Entry {}
An abstract interface representing entries in a file system, each of which may be a File or DirectoryEntry.
property filesystem
filesystem: FileSystem;
The file system on which the entry resides.
property fullPath
fullPath: string;
The full absolute path from the root to the entry.
property isDirectory
isDirectory: boolean;
Entry is a directory.
property isFile
isFile: boolean;
Entry is a file.
property name
name: string;
The name of the entry, excluding the path leading to it.
property nativeURL
nativeURL: string;
method copyTo
copyTo: ( parent: DirectoryEntry, newName?: string, successCallback?: (entry: Entry) => void, errorCallback?: (error: FileError) => void) => void;
Copy an entry to a different location on the file system. It is an error to try to: copy a directory inside itself or to any child at any depth; copy an entry into its parent if a name different from its current one isn't provided; copy a file to a path occupied by a directory; copy a directory to a path occupied by a file; copy any element to a path occupied by a directory which is not empty. A copy of a file on top of an existing file must attempt to delete and replace that file. A copy of a directory on top of an existing empty directory must attempt to delete and replace that directory. Directory copies are always recursive--that is, they copy all contents of the directory.
Parameter parent
The directory to which to move the entry.
Parameter newName
The new name of the entry. Defaults to the Entry's current name if unspecified.
Parameter successCallback
A callback that is called with the Entry for the new object.
Parameter errorCallback
A callback that is called when errors happen.
method getMetadata
getMetadata: ( successCallback: (metadata: Metadata) => void, errorCallback?: (error: FileError) => void) => void;
Look up metadata about this entry.
Parameter successCallback
A callback that is called with the time of the last modification.
Parameter errorCallback
A callback that is called when errors happen.
method getParent
getParent: ( successCallback: (entry: Entry) => void, errorCallback?: (error: FileError) => void) => void;
Look up the parent DirectoryEntry containing this Entry. If this Entry is the root of its filesystem, its parent is itself.
Parameter successCallback
A callback that is called with the time of the last modification.
Parameter errorCallback
A callback that is called when errors happen.
method moveTo
moveTo: ( parent: DirectoryEntry, newName?: string, successCallback?: (entry: Entry) => void, errorCallback?: (error: FileError) => void) => void;
Move an entry to a different location on the file system. It is an error to try to: move a directory inside itself or to any child at any depth;move an entry into its parent if a name different from its current one isn't provided; move a file to a path occupied by a directory; move a directory to a path occupied by a file; move any element to a path occupied by a directory which is not empty. A move of a file on top of an existing file must attempt to delete and replace that file. A move of a directory on top of an existing empty directory must attempt to delete and replace that directory.
Parameter parent
The directory to which to move the entry.
Parameter newName
The new name of the entry. Defaults to the Entry's current name if unspecified.
Parameter successCallback
A callback that is called with the Entry for the new location.
Parameter errorCallback
A callback that is called when errors happen.
method remove
remove: ( successCallback: () => void, errorCallback?: (error: FileError) => void) => void;
Deletes a file or directory. It is an error to attempt to delete a directory that is not empty. It is an error to attempt to delete the root directory of a filesystem.
Parameter successCallback
A callback that is called on success.
Parameter errorCallback
A callback that is called when errors happen.
method toInternalURL
toInternalURL: () => string;
Return a URL that can be passed across the bridge to identify this entry. string URL that can be passed across the bridge to identify this entry
method toURL
toURL: () => string;
Returns a URL that can be used as the src attribute of a or tag. If that is not possible, construct a cdvfile:// URL. string URL
interface ErrorCallback
interface ErrorCallback {}
call signature
(error?: Error): void;
interface EstimoteBeaconRegion
interface EstimoteBeaconRegion {}
property identifier
identifier?: string;
property major
major: number;
property minor
minor: number;
property state
state?: string;
property uuid
uuid: string;
interface FacebookLoginResponse
interface FacebookLoginResponse {}
property authResponse
authResponse: { session_key: boolean; accessToken: string; expiresIn: number; sig: string; secret: string; userID: string;};
property status
status: string;
interface FileEntry
interface FileEntry extends Entry {}
This interface represents a file on a file system.
method createWriter
createWriter: ( successCallback: (writer: FileWriter) => void, errorCallback?: (error: FileError) => void) => void;
Creates a new FileWriter associated with the file that this FileEntry represents.
Parameter successCallback
A callback that is called with the new FileWriter.
Parameter errorCallback
A callback that is called when errors happen.
method file
file: ( successCallback: (file: File) => void, errorCallback?: (error: FileError) => void) => void;
Returns a File that represents the current state of the file that this FileEntry represents.
Parameter successCallback
A callback that is called with the File.
Parameter errorCallback
A callback that is called when errors happen.
interface FileError
interface FileError {}
interface FileReader
interface FileReader {}
property error
error: Error;
property onabort
onabort: (evt: ProgressEvent) => void;
property onerror
onerror: (evt: ProgressEvent) => void;
property onload
onload: (evt: ProgressEvent) => void;
property onloadend
onloadend: (evt: ProgressEvent) => void;
property onloadstart
onloadstart: (evt: ProgressEvent) => void;
property onprogress
onprogress: (evt: ProgressEvent) => void;
property readyState
readyState: number;
property result
result: string | ArrayBuffer;
method abort
abort: () => void;
method readAsArrayBuffer
readAsArrayBuffer: (fe: File | Blob) => void;
method readAsBinaryString
readAsBinaryString: (fe: File | Blob) => void;
method readAsDataURL
readAsDataURL: (fe: File | Blob) => void;
method readAsText
readAsText: (fe: File | Blob, encoding?: string) => void;
interface FileSaver
interface FileSaver extends EventTarget {}
This interface provides methods to monitor the asynchronous writing of blobs to disk using progress events and event handler attributes.
property error
error: Error;
The last error that occurred on the FileSaver.
property onabort
onabort: (event: ProgressEvent) => void;
Handler for abort events.
property onerror
onerror: (event: ProgressEvent) => void;
Handler for error events.
property onprogress
onprogress: (event: ProgressEvent) => void;
Handler for progress events.
property onwrite
onwrite: (event: ProgressEvent) => void;
Handler for write events.
property onwriteend
onwriteend: (event: ProgressEvent) => void;
Handler for writeend events.
property onwritestart
onwritestart: (event: ProgressEvent) => void;
Handler for writestart events.
property readyState
readyState: number;
The FileSaver object can be in one of 3 states. The readyState attribute, on getting, must return the current state, which must be one of the following values: INIT WRITING DONE
method abort
abort: () => void;
Terminate file operation
interface FileSystem
interface FileSystem {}
This interface represents a file system.
interface FileTransferError
interface FileTransferError {}
property body
body: string;
Response body. This attribute is only available when a response is received from the HTTP connection.
property code
code: number;
One of the predefined error codes listed below.
property exception
exception: string;
Either e.getMessage or e.toString.
property http_status
http_status: number;
HTTP status code. This attribute is only available when a response code is received from the HTTP connection.
property source
source: string;
URL to the source.
property target
target: string;
URL to the target.
interface FileUploadOptions
interface FileUploadOptions {}
property chunkedMode
chunkedMode?: boolean;
Whether to upload the data in chunked streaming mode. Defaults to true.
property fileKey
fileKey?: string;
The name of the form element. Defaults to 'file'.
property fileName
fileName?: string;
The file name to use when saving the file on the server. Defaults to 'image.jpg'.
property headers
headers?: { [s: string]: any;};
A map of header name/header values. Use an array to specify more than one value. On iOS, FireOS, and Android, if a header named Content-Type is present, multipart form data will NOT be used.
property httpMethod
httpMethod?: string;
The HTTP method to use - either PUT or POST. Defaults to POST.
property mimeType
mimeType?: string;
The mime type of the data to upload. Defaults to image/jpeg.
property params
params?: { [s: string]: any;};
A set of optional key/value pairs to pass in the HTTP request.
interface FileUploadResult
interface FileUploadResult {}
property bytesSent
bytesSent: number;
The number of bytes sent to the server as part of the upload.
property headers
headers: { [s: string]: any;};
The HTTP response headers by the server.
property response
response: string;
The HTTP response returned by the server.
property responseCode
responseCode: number;
The HTTP response code returned by the server.
interface FileWriter
interface FileWriter extends FileSaver {}
This interface expands on the FileSaver interface to allow for multiple write actions, rather than just saving a single Blob.
property length
length: number;
The length of the file. If the user does not have read access to the file, this will be the highest byte offset at which the user has written.
property position
position: number;
The byte offset at which the next write to the file will occur. This always less or equal than length. A newly-created FileWriter will have position set to 0.
method seek
seek: (offset: number) => void;
The file position at which the next write will occur.
Parameter offset
If nonnegative, an absolute byte offset into the file. If negative, an offset back from the end of the file.
method truncate
truncate: (size: number) => void;
Changes the length of the file to that specified. If shortening the file, data beyond the new length will be discarded. If extending the file, the existing data will be zero-padded up to the new length.
Parameter size
The size to which the length of the file is to be adjusted, measured in bytes.
method write
write: (data: ArrayBuffer | Blob | string) => void;
Write the supplied data to the file at position.
Parameter data
The blob to write.
interface FingerprintOptions
interface FingerprintOptions {}
property clientId
clientId: string;
Key for platform keychain
property clientSecret
clientSecret?: string;
Secret password. Only for android
property disableBackup
disableBackup?: boolean;
Disable 'use backup' option. Only for android (optional)
interface Flags
interface Flags {}
This dictionary is used to supply arguments to methods that look up or create files or directories.
property create
create?: boolean;
Used to indicate that the user wants to create a file or directory if it was not previously there.
property exclusive
exclusive?: boolean;
By itself, exclusive must have no effect. Used with create, it must cause getFile and getDirectory to fail if the target path already exists.
interface GeocoderRequest
interface GeocoderRequest {}
interface GeocoderResult
interface GeocoderResult {}
property adminArea
adminArea?: string;
property country
country?: string;
property countryCode
countryCode?: string;
property extra
extra?: { featureName?: string; lines?: Array<string>; permises?: string; phone?: string; url?: string;};
property locale
locale?: string;
property locality
locality?: string;
property position
position?: { lat: number; lng: number;};
property postalCode
postalCode?: string;
property subAdminArea
subAdminArea?: string;
property subLocality
subLocality?: string;
property subThoroughfare
subThoroughfare?: string;
property thoroughfare
thoroughfare?: string;
interface GeolocationOptions
interface GeolocationOptions {}
property enableHighAccuracy
enableHighAccuracy?: boolean;
Indicates the application would like to receive the best possible results. If true and if the device is able to provide a more accurate position, it will do so. Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example). On the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power. Default: false. {boolean}
property maximumAge
maximumAge?: number;
Is a positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device must return a cached position regardless of its age. Default: 0.
property timeout
timeout?: number;
Is a positive long value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. The default value is Infinity, meaning that getCurrentPosition() won't return until the position is available.
interface Geoposition
interface Geoposition {}
interface GetLibraryOptions
interface GetLibraryOptions {}
property chunkTimeSec
chunkTimeSec?: number;
property includeAlbumData
includeAlbumData?: boolean;
property itemsInChunk
itemsInChunk?: number;
property quality
quality?: number;
property thumbnailHeight
thumbnailHeight?: number;
property thumbnailWidth
thumbnailWidth?: number;
property useOriginalFileNames
useOriginalFileNames?: boolean;
interface GetPhotoOptions
interface GetPhotoOptions {}
interface GetThumbnailOptions
interface GetThumbnailOptions {}
property quality
quality?: number;
property thumbnailHeight
thumbnailHeight?: number;
property thumbnailWidth
thumbnailWidth?: number;
interface GetVideoInfoOptions
interface GetVideoInfoOptions {}
property fileUri
fileUri: string;
The path to the video on the device.
interface GoogleMapsCircleOptions
interface GoogleMapsCircleOptions {}
property center
center?: GoogleMapsLatLng;
property fillColor
fillColor?: string;
property radius
radius?: number;
property strokeColor
strokeColor?: string;
property strokeWidth
strokeWidth?: number;
property visible
visible?: boolean;
property zIndex
zIndex?: number;
interface GoogleMapsGroundOverlayOptions
interface GoogleMapsGroundOverlayOptions {}
interface GoogleMapsKmlOverlayOptions
interface GoogleMapsKmlOverlayOptions {}
property animation
animation?: boolean;
property preserveViewport
preserveViewport?: boolean;
property url
url?: string;
interface GoogleMapsMarkerIcon
interface GoogleMapsMarkerIcon {}
interface GoogleMapsMarkerOptions
interface GoogleMapsMarkerOptions {}
property animation
animation?: string;
Which animation to play when marker is added to a map.
property disableAutoPan
disableAutoPan?: boolean;
Set to true to disable auto panning when the marker is clicked.
property draggable
draggable?: boolean;
Set true if you want to enable to drag the marker. (Default: false) Important! Drag starts after long pressed on the marker.
property flat
flat?: boolean;
Set true if you want to use a flat marker. (Default: false)
property icon
icon?: any;
The icon image url or properties. Also you can specify HTML Color values. Alternatively you can specify the image as Base64
property infoClick
infoClick?: Function;
Function to be invoked when the user clicks on the info box
property infoWindowAnchor
infoWindowAnchor?: number[];
Specify the anchor of the InfoWindow
property markerClick
markerClick?: Function;
Function to be invoked when the user clicks on the marker
property position
position?: GoogleMapsLatLng;
The position of the marker.
property rotation
rotation?: number;
Set rotation angle. (Default: 0)
property snippet
snippet?: string;
The snippet of the infoWindow.
property styles
styles?: any;
Specify the options for title.
property title
title?: string;
The content of the infoWindow.
property visible
visible?: boolean;
Set false if you want to hide. (Default: true)
property zIndex
zIndex?: number;
iOS only, Plugin Version >= 1.3.3 Higher zIndex value overlays will be drawn on top of lower zIndex value tile layers and overlays. (You're able to run this on Android, but it will have no effect)
interface GoogleMapsPolygonOptions
interface GoogleMapsPolygonOptions {}
property addHole
addHole?: Array<GoogleMapsLatLng>;
property fillColor
fillColor?: string;
property geodesic
geodesic?: boolean;
property points
points?: Array<GoogleMapsLatLng>;
property strokeColor
strokeColor?: string;
property strokeWidth
strokeWidth?: number;
property visible
visible?: boolean;
property zIndex
zIndex?: number;
interface GoogleMapsPolylineOptions
interface GoogleMapsPolylineOptions {}
interface GoogleMapsTileOverlayOptions
interface GoogleMapsTileOverlayOptions {}
property opacity
opacity?: number;
property tileSize
tileSize?: number;
property tileUrlFormat
tileUrlFormat?: string;
property visible
visible?: boolean;
property zIndex
zIndex?: number;
interface GyroscopeOptions
interface GyroscopeOptions {}
Interface that represent option data
property frequency
frequency: number;
Represent how often (in milliseconds) sensor should be read. Default is 10000 ms
interface GyroscopeOrientation
interface GyroscopeOrientation {}
Interface that represent output data
interface HealthData
interface HealthData {}
property endDate
endDate: Date;
End date from which to get data
property sourceBundleId
sourceBundleId: string;
The complete package of the source that produced this data. In Android, if not specified, it's assigned to the package of the App. In iOS this is ignored and set automatically to the bunde id of the app.
property sourceName
sourceName: string;
The source that produced this data. In iOS this is ignored and set automatically to the name of your app.
property startDate
startDate: Date;
Start date from which to get data
property unit
unit: string;
Unit of corresponding value of Datatype (see https://github.com/dariosalvi78/cordova-plugin-health#supported-data-types)
property value
value: string;
Value of corresponding Datatype (see https://github.com/dariosalvi78/cordova-plugin-health#supported-data-types)
interface HealthQueryOptions
interface HealthQueryOptions {}
property ascending
ascending?: boolean;
Optional indicator to sort values ascending or descending
property dataType
dataType: string;
Datatype to be queried (see https://github.com/dariosalvi78/cordova-plugin-health#supported-data-types)
property endDate
endDate: Date;
End date from which to get data
property filtered
filtered?: boolean;
In Android, it is possible to query for "raw" steps or to select those as filtered by the Google Fit app. In the latter case the query object must contain the field filtered: true.
property limit
limit?: number;
Optional limit the number of values returned. Defaults to 1000
property startDate
startDate: Date;
Start date from which to get data
interface HealthQueryOptionsAggregated
interface HealthQueryOptionsAggregated {}
property bucket
bucket: string;
if specified, aggregation is grouped an array of "buckets" (windows of time), supported values are: 'hour', 'day', 'week', 'month', 'year'.
property dataType
dataType: string;
Datatype to be queried (see https://github.com/dariosalvi78/cordova-plugin-health#supported-data-types)
property endDate
endDate: Date;
End date from which to get data
property startDate
startDate: Date;
Start date from which to get data
interface HealthStoreOptions
interface HealthStoreOptions {}
property dataType
dataType: string;
Datatype to be queried (see https://github.com/dariosalvi78/cordova-plugin-health#supported-data-types)
property endDate
endDate: Date;
End date from which to get data
property sourceBundleId
sourceBundleId: string;
property sourceName
sourceName: string;
property startDate
startDate: Date;
Start date from which to get data
property value
value: string;
Value of corresponding Datatype (see "Overview of valid datatypes")
interface HotspotConnectionInfo
interface HotspotConnectionInfo {}
property BSSID
BSSID: string;
The basic service set identifier (BSSID) of the current access point.
property IPAddress
IPAddress: string;
The IP Address
property linkSpeed
linkSpeed: string;
The current link speed in Mbps
property networkID
networkID: string;
Each configured network has a unique small integer ID, used to identify the network when performing operations on the supplicant.
property SSID
SSID: string;
The service set identifier (SSID) of the current 802.11 network.
interface HotspotDevice
interface HotspotDevice {}
interface HotspotNetwork
interface HotspotNetwork {}
property BSSID
BSSID: string;
MAC Address of the access point
property capabilities
capabilities: string;
Describes the authentication, key management, and encryption schemes supported by the access point.
property frequency
frequency: number;
The primary 20 MHz frequency (in MHz) of the channel over which the client is communicating with the access point.
property level
level: number;
The detected signal level in dBm, also known as the RSSI.
property SSID
SSID: string;
Human readable network name
property timestamp
timestamp: number;
Timestamp in microseconds (since boot) when this result was last seen.
interface HotspotNetworkConfig
interface HotspotNetworkConfig {}
property deviceIPAddress
deviceIPAddress: string;
Device IP Address
property deviceMacAddress
deviceMacAddress: string;
Device MAC Address
property gatewayIPAddress
gatewayIPAddress: string;
Gateway IP Address
property gatewayMacAddress
gatewayMacAddress: string;
Gateway MAC Address
interface HttpdOptions
interface HttpdOptions {}
property localhost_only
localhost_only?: boolean;
Setting this option to false will allow remote access to your web server (over any IP). Default is false.
property port
port?: number;
The port number to use. Default is 8888
property www_root
www_root?: string;
The public root directory for your web server. This path is relative to your app's www directory. Default is current directory.
interface HTTPResponse
interface HTTPResponse {}
property data
data?: any;
The data that is in the response. This property usually exists when a promise returned by a request method resolves.
property error
error?: string;
Error response from the server. This property usually exists when a promise returned by a request method rejects.
property headers
headers: any;
The headers of the response
property status
status: number;
The status number of the response
interface IBeaconDelegate
interface IBeaconDelegate {}
method didChangeAuthorizationStatus
didChangeAuthorizationStatus: () => Observable<string>;
An observable that publishes information about the location permission authorization status.
Returns
{Observable} Returns a string.
method didDetermineStateForRegion
didDetermineStateForRegion: () => Observable<IBeaconPluginResult>;
An Observable that publishes event data to it's subscribers when the native layer is able to determine the device's state.
This event is called when the phone begins starts monitoring, when requestStateForRegion is called, etc.
Returns
{Observable} Returns a IBeaconPluginResult object with information about the event, region, and beacon(s).
method didEnterRegion
didEnterRegion: () => Observable<IBeaconPluginResult>;
An Observable that publishes event data to it's subscribers when the phone enters a region that it was asked to monitor.
If the user has given the app Always-Location permission, this function will be called even when the app is not running on iOS. The app will run silently in the background for a small amount of time.
Returns
{Observable} Returns a IBeaconPluginResult object with information about the event, region, and beacon(s).
method didExitRegion
didExitRegion: () => Observable<IBeaconPluginResult>;
An Observable that publishes event data to it's subscribers when the phone exits a region that it was asked to monitor.
If the user has given the app Always-Location permission, this function will be called even when the app is not running on iOS. The app will run silently in the background for a small amount of time.
Returns
{Observable} Returns a IBeaconPluginResult object with information about the event, region, and beacon(s).
method didRangeBeaconsInRegion
didRangeBeaconsInRegion: () => Observable<IBeaconPluginResult>;
An Observable that publishes event data to it's subscribers each time that the device ranges beacons. Modern Android and iOS devices range aproximately once per second.
Returns
{Observable} Returns a IBeaconPluginResult object with information about the event, region, and beacon(s).
method didStartMonitoringForRegion
didStartMonitoringForRegion: () => Observable<IBeaconPluginResult>;
An Observable that publishes event data to it's subscribers when the device begins monitoring a region.
Returns
{Observable} Returns a IBeaconPluginResult object with information about the event, region, and beacon(s).
method monitoringDidFailForRegionWithError
monitoringDidFailForRegionWithError: () => Observable<IBeaconPluginResult>;
An Observable that publishes event data to it's subscribers when the device fails to monitor a region.
Returns
{Observable} Returns a IBeaconPluginResult object with information about the event, region, and beacon(s).
method peripheralManagerDidStartAdvertising
peripheralManagerDidStartAdvertising: () => Observable<IBeaconPluginResult>;
An Observable that publishes event data to it's subscribers when the device begins advertising as an iBeacon.
Returns
{Observable} Returns a IBeaconPluginResult object with information about the event, region, and beacon(s).
method peripheralManagerDidUpdateState
peripheralManagerDidUpdateState: () => Observable<IBeaconPluginResult>;
An Observable that publishes event data to it's subscribers when the state of the peripheral manager's state updates.
Returns
{Observable} Returns a IBeaconPluginResult object with information about the event, region, and beacon(s).
interface IBeaconPluginResult
interface IBeaconPluginResult {}
property authorizationStatus
authorizationStatus: string;
The status of the location permission for iOS.
property beacons
beacons: Beacon[];
An array of beacon objects
property error
error: string;
Error message, used only with monitoringDidFailForRegionWithError delegate.
property eventType
eventType: string;
The name of the delegate function that produced the PluginResult object.
property region
region: Region;
The region that triggered the event.
property state
state: 'CLRegionStateInside' | 'CLRegionStateOutside';
The state of the phone in relation to the region. Inside/outside for example.
interface IContactAddress
interface IContactAddress {}
property country
country?: string;
The country name.
property formatted
formatted?: string;
The full address formatted for display.
property locality
locality?: string;
The city or locality.
property postalCode
postalCode?: string;
The zip code or postal code.
property pref
pref?: boolean;
Set to true if this ContactAddress contains the user's preferred value.
property region
region?: string;
The state or region.
property streetAddress
streetAddress?: string;
The full street address.
property type
type?: string;
A string indicating what type of field this is, home for example.
interface IContactError
interface IContactError {}
interface IContactField
interface IContactField {}
interface IContactFindOptions
interface IContactFindOptions {}
Search options to filter navigator.contacts.
property desiredFields
desiredFields?: string[];
Contact fields to be returned back. If specified, the resulting Contact object only features values for these fields.
property filter
filter?: string;
The search string used to find navigator.contacts.
property hasPhoneNumber
hasPhoneNumber?: boolean;
(Android only): Filters the search to only return contacts with a phone number informed.
property multiple
multiple?: boolean;
Determines if the find operation returns multiple navigator.contacts. Defaults to false.
interface IContactName
interface IContactName {}
property familyName
familyName?: string;
The contact's family name.
property formatted
formatted?: string;
The complete name of the contact.
property givenName
givenName?: string;
The contact's given name.
property honorificPrefix
honorificPrefix?: string;
The contact's prefix (example Mr. or Dr.)
property honorificSuffix
honorificSuffix?: string;
The contact's suffix (example Esq.).
property middleName
middleName?: string;
The contact's middle name.
interface IContactOrganization
interface IContactOrganization {}
property department
department?: string;
The department the contract works for.
property name
name?: string;
The name of the organization.
property pref
pref?: boolean;
Set to true if this ContactOrganization contains the user's preferred value.
property title
title?: string;
The contact's title at the organization.
property type
type?: string;
A string that indicates what type of field this is, home for example.
interface IContactProperties
interface IContactProperties {}
property addresses
addresses?: IContactAddress[];
An array of all the contact's addresses.
property birthday
birthday?: Date;
The birthday of the contact.
property categories
categories?: IContactField[];
An array of all the user-defined categories associated with the contact.
property displayName
displayName?: string;
The name of this Contact, suitable for display to end users.
property emails
emails?: IContactField[];
An array of all the contact's email addresses.
property id
id?: string;
A globally unique identifier.
property ims
ims?: IContactField[];
An array of all the contact's IM addresses.
property name
name?: IContactName;
An object containing all components of a persons name.
property nickname
nickname?: string;
A casual name by which to address the contact.
property note
note?: string;
A note about the contact.
property organizations
organizations?: IContactOrganization[];
An array of all the contact's organizations.
property phoneNumbers
phoneNumbers?: IContactField[];
An array of all the contact's phone numbers.
property photos
photos?: IContactField[];
An array of the contact's photos.
property urls
urls?: IContactField[];
An array of web pages associated with the contact.
interface ILocalNotification
interface ILocalNotification {}
property at
at?: any;
The date and time when the system should deliver the local notification. If the specified value is nil or is a date in the past, the local notification is delivered immediately. Default: now ~ new Date()
property badge
badge?: number;
The number currently set as the badge of the app icon in Springboard (iOS) or at the right-hand side of the local notification (Android) Default: 0 (which means don't show a number)
property color
color?: string;
ANDROID ONLY RGB value for the background color of the smallIcon. Default: Androids COLOR_DEFAULT, which will vary based on Android version.
property data
data?: any;
Arbitrary data, objects will be encoded to JSON string Default: null
property every
every?: string;
The interval at which to reschedule the local notification. That can be a value of second, minute, hour, day, week, month or year Default: 0 (which means that the system triggers the local notification once)
property firstAt
firstAt?: any;
property icon
icon?: string;
ANDROID ONLY Uri of the icon that is shown in the ticker and notification Default: res://icon
property id
id?: number;
A unique identifier required to clear, cancel, update or retrieve the local notification in the future Default: 0
property led
led?: string;
ANDROID ONLY ARGB value that you would like the LED on the device to blink Default: FFFFFF
property ongoing
ongoing?: boolean;
ANDROID ONLY Ongoing notifications differ from regular notifications in the following ways: - They are sorted above the regular notifications in the notification panel - They do not have an 'X' close button, and are not affected by the "Clear all" button Default: false
property smallIcon
smallIcon?: string;
ANDROID ONLY Uri of the resource (only res://) to use in the notification layouts. Different classes of devices may return different sizes Default: res://ic_popup_reminder
property sound
sound?: string;
Uri of the file containing the sound to play when an alert is displayed Default: res://platform_default
property text
text?: string;
Second row of the notification Default: Empty string
property title
title?: string;
First row of the notification Default: Empty string (iOS) or the app name (Android)
interface ILocalPackage
interface ILocalPackage extends IPackage {}
Defines a local package.
!! THIS TYPE IS READ FROM NATIVE CODE AS WELL. ANY CHANGES TO THIS INTERFACE NEEDS TO BE UPDATED IN NATIVE CODE !!
property isFirstRun
isFirstRun: boolean;
Indicates if the current application run is the first one after the package was applied.
property localPath
localPath: string;
The local storage path where this package is located.
method install
install: ( installSuccess: SuccessCallback<InstallMode>, errorCallback?: ErrorCallback, installOptions?: InstallOptions) => void;
Applies this package to the application. The application will be reloaded with this package and on every application launch this package will be loaded. On the first run after the update, the application will wait for a codePush.notifyApplicationReady() call. Once this call is made, the install operation is considered a success. Otherwise, the install operation will be marked as failed, and the application is reverted to its previous version on the next run.
Parameter installSuccess
Callback invoked if the install operation succeeded.
Parameter installError
Optional callback inovoked in case of an error.
Parameter installOptions
Optional parameter used for customizing the installation behavior.
interface ImagePickerOptions
interface ImagePickerOptions {}
property height
height?: number;
Max height to allow images to be
property maximumImagesCount
maximumImagesCount?: number;
max images to be selected, defaults to 15. If this is set to 1, upon selection of a single image, the plugin will return it.
property outputType
outputType?: number;
Output type, defaults to 0 (FILE_URI).
property quality
quality?: number;
Quality of images, defaults to 100
property width
width?: number;
Max width to allow images to be
interface ImageResizerOptions
interface ImageResizerOptions {}
property fileName
fileName?: string;
A custom name for the file. Default name is a timestamp (Android and Windows only)
property folderName
folderName?: string;
The name of the folder the image should be put (Android only)
property height
height: number;
The height of the new image
property quality
quality?: number;
Quality given as Number for the quality of the new image (Android and iOS only)
property uri
uri: string;
The URI for the image on the device to get scaled
property width
width: number;
The width of the new image
interface InAppBrowserEvent
interface InAppBrowserEvent extends Event {}
interface InAppBrowserOptions
interface InAppBrowserOptions {}
property allowInlineMediaPlayback
allowInlineMediaPlayback?: 'yes' | 'no';
(iOS Only) Set to yes or no to allow in-line HTML5 media playback, displaying within the browser window rather than a device-specific playback interface. The HTML's video element must also include the webkit-playsinline attribute (defaults to no)
property clearcache
clearcache?: 'yes';
Set to yes to have the browser's cookie cache cleared before the new window is opened.
property clearsessioncache
clearsessioncache?: 'yes';
Set to yes to have the session cookie cache cleared before the new window is opened.
property closebuttoncaption
closebuttoncaption?: string;
(iOS Only) Set to a string to use as the Done button's caption. Note that you need to localize this value yourself.
property disallowoverscroll
disallowoverscroll?: 'yes' | 'no';
(iOS Only) Set to yes or no (default is no). Turns on/off the UIWebViewBounce property.
property enableViewportScale
enableViewportScale?: 'yes' | 'no';
(iOS Only) Set to yes or no to prevent viewport scaling through a meta tag (defaults to no).
property fullscreen
fullscreen?: 'yes';
(Windows only) Set to yes to create the browser control without a border around it. Please note that if location=no is also specified, there will be no control presented to user to close IAB window.
property hardwareback
hardwareback?: 'yes' | 'no';
Set to yes to use the hardware back button to navigate backwards through the InAppBrowser's history. If there is no previous page, the InAppBrowser will close. The default value is yes, so you must set it to no if you want the back button to simply close the InAppBrowser.
property hidden
hidden?: 'yes' | 'no';
Set to yes to create the browser and load the page, but not show it. The loadstop event fires when loading is complete. Omit or set to no (default) to have the browser open and load normally.
property keyboardDisplayRequiresUserAction
keyboardDisplayRequiresUserAction?: 'yes' | 'no';
(iOS Only) Set to yes or no to open the keyboard when form elements receive focus via JavaScript's focus() call (defaults to yes).
property location
location?: 'yes' | 'no';
Set to yes or no to turn the InAppBrowser's location bar on or off.
property mediaPlaybackRequiresUserAction
mediaPlaybackRequiresUserAction?: 'yes' | 'no';
Set to yes to prevent HTML5 audio or video from autoplaying (defaults to no).
property presentationstyle
presentationstyle?: 'pagesheet' | 'formsheet' | 'fullscreen';
(iOS Only) Set to pagesheet, formsheet or fullscreen to set the presentation style (defaults to fullscreen).
property shouldPauseOnSuspend
shouldPauseOnSuspend?: 'yes' | 'no';
(Android Only) Set to yes to make InAppBrowser WebView to pause/resume with the app to stop background audio (this may be required to avoid Google Play issues)
property suppressesIncrementalRendering
suppressesIncrementalRendering?: 'yes' | 'no';
(iOS Only) Set to yes or no to wait until all new view content is received before being rendered (defaults to no).
property toolbar
toolbar?: 'yes' | 'no';
(iOS Only) Set to yes or no to turn the toolbar on or off for the InAppBrowser (defaults to yes)
property toolbarposition
toolbarposition?: 'top' | 'bottom';
(iOS Only) Set to top or bottom (default is bottom). Causes the toolbar to be at the top or bottom of the window.
property transitionstyle
transitionstyle?: 'fliphorizontal' | 'crossdissolve' | 'coververtical';
(iOS Only) Set to fliphorizontal, crossdissolve or coververtical to set the transition style (defaults to coververtical).
property zoom
zoom?: 'yes' | 'no';
(Android Only) set to yes to show Android browser's zoom controls, set to no to hide them. Default value is yes.
interface InstallOptions
interface InstallOptions {}
Defines the install operation options.
property installMode
installMode?: InstallMode;
Used to specify the InstallMode used for the install operation. This is optional and defaults to InstallMode.ON_NEXT_RESTART.
property mandatoryInstallMode
mandatoryInstallMode?: InstallMode;
Used to specify the InstallMode used for the install operation if the update is mandatory. This is optional and defaults to InstallMode.IMMEDIATE.
property minimumBackgroundDuration
minimumBackgroundDuration?: number;
If installMode === ON_NEXT_RESUME, the minimum amount of time (in seconds) which needs to pass with the app in the background before an update install occurs when the app is resumed.
interface IOSPushOptions
interface IOSPushOptions {}
property alert
alert?: boolean | string;
If true the device shows an alert on receipt of notification. **Note**: the value you set this option to the first time you call the init method will be how the application always acts. Once this is set programmatically in the init method it can only be changed manually by the user in Settings>Notifications>App Name. This is normal iOS behaviour.
property badge
badge?: boolean | string;
If true the device sets the badge number on receipt of notification. **Note**: the value you set this option to the first time you call the init method will be how the application always acts. Once this is set programmatically in the init method it can only be changed manually by the user in Settings>Notifications>App Name. This is normal iOS behaviour.
property categories
categories?: CategoryArray;
The data required in order to enable Action Buttons for iOS. Action Buttons on iOS - https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#action-buttons-1
property clearBadge
clearBadge?: boolean | string;
If true the badge will be cleared on app startup.
property gcmSandbox
gcmSandbox?: boolean | string;
Whether to use prod or sandbox GCM setting.
property senderID
senderID?: string;
Maps to the project number in the Google Developer Console. Setting this uses GCM for notifications instead of native.
property sound
sound?: boolean | string;
If true the device plays a sound on receipt of notification. **Note**: the value you set this option to the first time you call the init method will be how the application always acts. Once this is set programmatically in the init method it can only be changed manually by the user in Settings>Notifications>App Name. This is normal iOS behaviour.
property topics
topics?: string[];
If the array contains one or more strings each string will be used to subscribe to a GcmPubSub topic. **Note**: only usable in conjunction with
senderID
.
interface IPackage
interface IPackage {}
Defines a package. All fields are non-nullable, except when retrieving the currently running package on the first run of the app, in which case only the appVersion is compulsory.
!! THIS TYPE IS READ FROM NATIVE CODE AS WELL. ANY CHANGES TO THIS INTERFACE NEEDS TO BE UPDATED IN NATIVE CODE !!
property appVersion
appVersion: string;
property deploymentKey
deploymentKey: string;
property description
description: string;
property failedInstall
failedInstall: boolean;
property isMandatory
isMandatory: boolean;
property label
label: string;
property packageHash
packageHash: string;
property packageSize
packageSize: number;
interface IRemotePackage
interface IRemotePackage extends IPackage {}
Defines a remote package, which represents an update package available for download.
property downloadUrl
downloadUrl: string;
The URL at which the package is available for download.
method abortDownload
abortDownload: ( abortSuccess?: SuccessCallback<void>, abortError?: ErrorCallback) => void;
Aborts the current download session, previously started with download().
Parameter abortSuccess
Optional callback invoked if the abort operation succeeded.
Parameter abortError
Optional callback invoked in case of an error.
method download
download: ( downloadSuccess: SuccessCallback<ILocalPackage>, downloadError?: ErrorCallback, downloadProgress?: SuccessCallback<DownloadProgress>) => void;
Downloads the package update from the CodePush service.
Parameter downloadSuccess
Called with one parameter, the downloaded package information, once the download completed successfully.
Parameter downloadError
Optional callback invoked in case of an error.
Parameter downloadProgress
Optional callback invoked during the download process. It is called several times with one DownloadProgress parameter.
interface LaunchNavigatorOptions
interface LaunchNavigatorOptions {}
property app
app?: string;
name of the navigation app to use for directions. Specify using launchnavigator.APP constants. If not specified, defaults to User Selection.
property appSelectionCancelButton
appSelectionCancelButton?: string;
text to display for the cancel button in the native picker which enables user to select which navigation app to launch. Defaults to "Cancel" if not specified.
property appSelectionDialogHeader
appSelectionDialogHeader?: string;
text to display in the native picker which enables user to select which navigation app to launch. Defaults to "Select app for navigation" if not specified.
property destinationName
destinationName?: string;
nickname to display in app for destination. e.g. "Bob's House".
property enableDebug
enableDebug?: boolean;
If true, debug log output will be generated by the plugin. Defaults to false.
property errorCallback
errorCallback?: Function;
property extras
extras?: any;
a key/value map of extra app-specific parameters. For example, to tell Google Maps on Android to display Satellite view in "maps" launch mode:
{"t": "k"}
property launchMode
launchMode?: string;
(Android only) mode in which to open Google Maps app: "maps" or "turn-by-turn". Defaults to "maps" if not specified. Specify using launchnavigator.LAUNCH_MODE constants.
property start
start?: string | number[];
Start point of the navigation
property startName
startName?: string;
nickname to display in app for start . e.g. "My House".
property successCallback
successCallback?: Function;
property transportMode
transportMode?: string;
Transportation mode for navigation: "driving", "walking" or "transit". Defaults to "driving" if not specified.
interface LibraryItem
interface LibraryItem {}
property albumIds
albumIds?: string[];
property creationDate
creationDate: Date;
property fileName
fileName: string;
property height
height: number;
property id
id: string;
Local id of the photo
property latitude
latitude?: number;
property longitude
longitude?: number;
property photoURL
photoURL: string;
URL of cdvphotolibrary schema.
property thumbnailURL
thumbnailURL: string;
URL of cdvphotolibrary schema.
property width
width: number;
interface MediaError
interface MediaError {}
interface MediaFile
interface MediaFile {}
property fullPath
fullPath: string;
The full path of the file, including the name.
property lastModifiedDate
lastModifiedDate: Date;
The date and time when the file was last modified.
property name
name: string;
The name of the file, without path information.
property size
size: number;
The size of the file, in bytes.
property type
type: string;
The file's mime type
method getFormatData
getFormatData: ( successCallback: (data: MediaFileData) => any, errorCallback?: (err: any) => any) => any;
Retrieves the format information of the media file.
Parameter successCallback
Parameter errorCallback
interface MediaFileData
interface MediaFileData {}
property bitrate
bitrate: number;
The average bitrate of the content. The value is zero for images.
property codecs
codecs: string;
The actual format of the audio and video content.
property duration
duration: number;
The length of the video or sound clip in seconds. The value is zero for images.
property height
height: number;
The height of the image or video in pixels. The value is zero for audio clips.
property width
width: number;
The width of the image or video in pixels. The value is zero for audio clips.
interface Metadata
interface Metadata {}
This interface supplies information about the state of a file or directory.
property modificationTime
modificationTime: Date;
This is the time at which the file or directory was last modified.
property size
size: number;
The size of the file, in bytes. This must return 0 for directories.
interface MusicControlsOptions
interface MusicControlsOptions {}
interface MyLocation
interface MyLocation {}
interface MyLocationOptions
interface MyLocationOptions {}
property enableHighAccuracy
enableHighAccuracy?: boolean;
interface NativeGeocoderForwardResult
interface NativeGeocoderForwardResult {}
Encapsulates format information about a forward geocoding result.
interface NativeGeocoderReverseResult
interface NativeGeocoderReverseResult {}
Encapsulates format information about a reverse geocoding result.
property city
city: string;
The city.
property countryCode
countryCode: string;
The country code.
property countryName
countryName: string;
The country name.
property houseNumber
houseNumber: string;
The house number.
property postalCode
postalCode: string;
The postal code.
property street
street: string;
The street.
interface NativeTransitionOptions
interface NativeTransitionOptions {}
property action
action?: string;
property androiddelay
androiddelay?: number;
property direction
direction?: string;
property duration
duration?: number;
property fixedPixelsBottom
fixedPixelsBottom?: number;
property fixedPixelsTop
fixedPixelsTop?: number;
property href
href?: string;
property iosdelay
iosdelay?: number;
property origin
origin?: string;
property slidePixels
slidePixels?: number;
property slowdownfactor
slowdownfactor?: number;
property winphonedelay
winphonedelay?: number;
interface NotificationEventAdditionalData
interface NotificationEventAdditionalData {}
TODO: document all possible properties (not just Android)
Loosened up with a dictionary notation, but all non-defined properties need to use (map['prop']) notation
Ideally the developer would overload (merged declaration) this or create a new interface that would extend this one so that he could specify any custom code without having to use array notation (map['prop']) for all of them.
property coldstart
coldstart?: boolean;
property collapse_key
collapse_key?: string;
property foreground
foreground?: boolean;
Whether the notification was received while the app was in the foreground
property from
from?: string;
property notId
notId?: string;
index signature
[name: string]: any;
interface NotificationEventResponse
interface NotificationEventResponse {}
property additionalData
additionalData: NotificationEventAdditionalData | any;
An optional collection of data sent by the 3rd party push service that does not fit in the above properties.
property count
count: string;
The number of messages to be displayed in the badge iOS or message count in the notification shade in Android. For windows, it represents the value in the badge notification which could be a number or a status glyph.
property image
image: string;
The path of the image file to be displayed in the notification.
property message
message: string;
The text of the push message sent from the 3rd party service.
property sound
sound: string;
The name of the sound file to be played upon receipt of the notification.
property title
title?: string;
The optional title of the push message sent from the 3rd party service.
interface OSActionButton
interface OSActionButton {}
List of action buttons on the notification.
interface OSBackgroundImageLayout
interface OSBackgroundImageLayout {}
**ANDROID** - If a background image was set, this object will be available.
property bodyTextColor
bodyTextColor: string;
Text color of the body on the notification. ARGB Format.
property image
image: string;
Image URL or name used as the background image.
property titleTextColor
titleTextColor: string;
Text color of the title on the notification. ARGB Format.
interface OSNotification
interface OSNotification {}
property adm_big_picture
adm_big_picture?: string;
property adm_group
adm_group?: string;
property adm_group_message
adm_group_message?: any;
property adm_large_icon
adm_large_icon?: string;
property adm_small_icon
adm_small_icon?: string;
property adm_sound
adm_sound?: string;
property amazon_background_data
amazon_background_data?: boolean;
property android_accent_color
android_accent_color?: string;
property android_group
android_group?: string;
property android_group_message
android_group_message?: any;
property android_led_color
android_led_color?: string;
property android_sound
android_sound?: string;
property android_visibility
android_visibility?: number;
property androidNotificationId
androidNotificationId?: number;
**ANDROID** - Android Notification assigned to the notification. Can be used to cancel or replace the notification.
property app_id
app_id?: string;
property app_ids
app_ids?: string[];
property big_picture
big_picture?: string;
property buttons
buttons?: any;
property chrome_big_picture
chrome_big_picture?: string;
property chrome_icon
chrome_icon?: string;
property chrome_web_icon
chrome_web_icon?: string;
property content_available
content_available?: boolean;
property contents
contents: any;
property data
data?: any;
property delayed_option
delayed_option?: string;
property delivery_time_of_day
delivery_time_of_day?: string;
property displayType
displayType: OSDisplayType;
How the notification was displayed to the user. Can be set to
Notification
,InAppAlert
, orNone
if it was not displayed.
property excluded_segments
excluded_segments?: string[];
property firefox_icon
firefox_icon?: string;
property groupedNotifications
groupedNotifications?: OSNotificationPayload[];
**ANDROID** - Notification is a summary notification for a group this will contain all notification payloads it was created from.
property headings
headings?: any;
property include_amazon_reg_ids
include_amazon_reg_ids?: string[];
property include_android_reg_ids
include_android_reg_ids?: string[];
property include_chrome_reg_ids
include_chrome_reg_ids?: string[];
property include_chrome_web_reg_ids
include_chrome_web_reg_ids?: string[];
property include_ios_tokens
include_ios_tokens?: string[];
property include_player_ids
include_player_ids?: string[];
property include_wp_uris
include_wp_uris?: string[];
property include_wp_wns_uris
include_wp_wns_uris?: string[];
property included_segments
included_segments?: string[];
property ios_badgeCount
ios_badgeCount?: number;
property ios_badgeType
ios_badgeType?: string;
property ios_category
ios_category?: string;
property ios_sound
ios_sound?: string;
property isAdm
isAdm?: boolean;
property isAndroid
isAndroid?: boolean;
property isAnyWeb
isAnyWeb?: boolean;
property isAppInFocus
isAppInFocus: boolean;
Was app in focus.
property isChrome
isChrome?: boolean;
property isChromeWeb
isChromeWeb?: boolean;
property isIos
isIos?: boolean;
property isSafari
isSafari?: boolean;
property isWP
isWP?: boolean;
property isWP_WNS
isWP_WNS?: boolean;
property large_icon
large_icon?: string;
property payload
payload: OSNotificationPayload;
Payload received from OneSignal.
property priority
priority?: number;
property send_after
send_after?: string;
property shown
shown: boolean;
Was notification shown to the user. Will be false for silent notifications.
property small_icon
small_icon?: string;
property tags
tags?: any[];
property template_id
template_id?: string;
property ttl
ttl?: number;
property url
url?: string;
property wp_sound
wp_sound?: string;
property wp_wns_sound
wp_wns_sound?: string;
interface OSNotificationOpenedResult
interface OSNotificationOpenedResult {}
The information returned from a notification the user received.
property action
action: { /** * Was the notification opened normally (`Opened`) or was a button pressed on the notification (`ActionTaken`). */ type: OSActionType; /** * If `type` == `ActionTaken` then this will contain the id of the button pressed. */ actionID?: string;};
property notification
notification: OSNotification;
interface OSNotificationPayload
interface OSNotificationPayload {}
Contents and settings of the notification the user received.
property actionButtons
actionButtons: OSActionButton[];
List of action buttons on the notification.
property additionalData
additionalData?: any;
Custom additional data that was sent with the notification. Set on the dashboard under Options > Additional Data or with the 'data' field on the REST API.
property backgroundImageLayout
backgroundImageLayout?: OSBackgroundImageLayout;
**ANDROID** - If a background image was set this object will be available.
property bigPicture
bigPicture?: string;
**ANDROID** - Big picture image set on the notification.
property body
body: string;
Body of the notification.
property fromProjectNumber
fromProjectNumber?: string;
**ANDROID** - The Google project number the notification was sent under.
property groupKey
groupKey?: string;
**ANDROID** - Notifications with this same key will be grouped together as a single summary notification.
property groupMessage
groupMessage?: string;
**ANDROID** - Summary text displayed in the summary notification.
property largeIcon
largeIcon?: string;
**ANDROID** - Large icon set on the notification.
property launchUrl
launchUrl?: string;
URL to open when opening the notification.
property ledColor
ledColor?: string;
**ANDROID** - Devices that have a notification LED will blink in this color. ARGB format.
property lockScreenVisibility
lockScreenVisibility?: OSLockScreenVisibility;
property notificationID
notificationID: string;
OneSignal notification UUID.
property priority
priority?: number;
property rawPayload
rawPayload: string;
List of action buttons on the notification.
property smallIcon
smallIcon?: string;
**ANDROID** - Small icon resource name set on the notification.
property smallIconAccentColor
smallIconAccentColor?: string;
**ANDROID** - Accent color shown around small notification icon on Android 5+ devices. ARGB format.
property sound
sound: string;
Sound resource to play when the notification is shown.
property title
title: string;
Title of the notification.
interface PayPalConfigurationOptions
interface PayPalConfigurationOptions {}
property acceptCreditCards
acceptCreditCards?: boolean;
If set to NO, the SDK will only support paying with PayPal, not with credit cards. This applies only to single payments (via PayPalPaymentViewController). Future payments (via PayPalFuturePaymentViewController) always use PayPal. Defaults to true
property defaultUserEmail
defaultUserEmail?: string;
Will be overridden by email used in most recent PayPal login.
property defaultUserPhoneCountryCode
defaultUserPhoneCountryCode?: string;
Will be overridden by phone country code used in most recent PayPal login
property defaultUserPhoneNumber
defaultUserPhoneNumber?: string;
Will be overridden by phone number used in most recent PayPal login.
property disableBlurWhenBackgrounding
disableBlurWhenBackgrounding?: boolean;
Normally, the SDK blurs the screen when the app is backgrounded, to obscure credit card or PayPal account details in the iOS-saved screenshot. If your app already does its own blurring upon backgrounding, you might choose to disable this. Defaults to NO.
property forceDefaultsInSandbox
forceDefaultsInSandbox?: boolean;
Sandbox credentials can be difficult to type on a mobile device. Setting this flag to YES will cause the sandboxUserPassword and sandboxUserPin to always be pre-populated into login fields.
property languageOrLocale
languageOrLocale?: string;
If not set, or if set to nil, defaults to the device's current language setting.
Can be specified as a language code ("en", "fr", "zh-Hans", etc.) or as a locale ("en_AU", "fr_FR", "zh-Hant_HK", etc.). If the library does not contain localized strings for a specified locale, then will fall back to the language. E.g., "es_CO" -> "es". If the library does not contain localized strings for a specified language, then will fall back to American English.
If you specify only a language code, and that code matches the device's currently preferred language, then the library will attempt to use the device's current region as well. E.g., specifying "en" on a device set to "English" and "United Kingdom" will result in "en_GB".
property merchantName
merchantName?: string;
Your company name, as it should be displayed to the user when requesting consent via a PayPalFuturePaymentViewController.
property merchantPrivacyPolicyURL
merchantPrivacyPolicyURL?: string;
URL of your company's privacy policy, which will be offered to the user when requesting consent via a PayPalFuturePaymentViewController.
property merchantUserAgreementURL
merchantUserAgreementURL?: string;
URL of your company's user agreement, which will be offered to the user when requesting consent via a PayPalFuturePaymentViewController.
property payPalShippingAddressOption
payPalShippingAddressOption?: number;
For single payments, options for the shipping address. - 0 - PayPalShippingAddressOptionNone: no shipping address applies. - 1 - PayPalShippingAddressOptionProvided: shipping address will be provided by your app, in the shippingAddress property of PayPalPayment. - 2 - PayPalShippingAddressOptionPayPal: user will choose from shipping addresses on file for their PayPal account. - 3 - PayPalShippingAddressOptionBoth: user will choose from the shipping address provided by your app, in the shippingAddress property of PayPalPayment, plus the shipping addresses on file for the user's PayPal account. Defaults to 0 (PayPalShippingAddressOptionNone).
property presentingInPopover
presentingInPopover?: boolean;
If you will present the SDK's view controller within a popover, then set this property to YES. Defaults to NO. (iOS only)
property rememberUser
rememberUser?: boolean;
If set to YES, then if the user pays via their PayPal account, the SDK will remember the user's PayPal username or phone number; if the user pays via their credit card, then the SDK will remember the PayPal Vault token representing the user's credit card.
If set to NO, then any previously-remembered username, phone number, or credit card token will be erased, and subsequent payment information will not be remembered.
Defaults to YES.
property sandboxUserPassword
sandboxUserPassword?: string;
Password to use for sandbox if 'forceDefaultsInSandbox' is set.
property sandboxUserPin
sandboxUserPin?: string;
PIN to use for sandbox if 'forceDefaultsInSandbox' is set.
interface PayPalEnvironment
interface PayPalEnvironment {}
property PayPalEnvironmentProduction
PayPalEnvironmentProduction: string;
property PayPalEnvironmentSandbox
PayPalEnvironmentSandbox: string;
interface PinterestBoard
interface PinterestBoard {}
property counts
counts?: any;
The board’s stats, including how many Pins, followers, user's following and collaborators it has.
property created_at
created_at?: string;
The date the user created the board.
property creator
creator?: PinterestUser;
The first and last name, ID and profile URL of the user who created the board.
property description
description?: string;
The user-entered description of the board.
property id
id?: string;
The unique string of numbers and letters that identifies the board on Pinterest.
property image
image?: any;
The user’s profile image. The response returns the image’s URL, width and height.
property name
name?: string;
The name of the board.
property url
url?: string;
The link to the board.
interface PinterestPin
interface PinterestPin {}
property attribution
attribution?: any;
The source data for videos, including the title, URL, provider, author name, author URL and provider name.
property board
board?: PinterestBoard;
The board that the Pin is on.
property color
color?: string;
The dominant color of the Pin’s image in hex code format.
property counts
counts?: any;
The Pin’s stats, including the number of repins, comments and likes.
property created_at
created_at?: string;
The date the Pin was created.
property creator
creator?: PinterestUser;
The first and last name, ID and profile URL of the user who created the board.
property id
id?: string;
The unique string of numbers and letters that identifies the Pin on Pinterest.
property image
image?: any;
The Pin’s image. The default response returns the image’s URL, width and height.
property link
link?: string;
The URL of the webpage where the Pin was created.
property media
media?: any;
The media type of the Pin (image or video).
property metadata
metadata?: any;
Extra information about the Pin for Rich Pins. Includes the Pin type (e.g., article, recipe) and related information (e.g., ingredients, author).
property note
note?: string;
The user-entered description of the Pin.
property url
url?: string;
The URL of the Pin on Pinterest.
interface PinterestUser
interface PinterestUser {}
property bio
bio?: string;
The text in the user’s “About you” section in their profile.
property counts
counts?: any;
The user’s stats, including how many Pins, follows, boards and likes they have.
property created_at
created_at?: string;
The date the user created their account in ISO 8601 format
property first_name
first_name?: string;
The user’s first name.
property id
id?: string;
The unique string of numbers and letters that identifies the user on Pinterest.
property image
image?: any;
The user’s profile image. The response returns the image’s URL, width and height.
property last_name
last_name?: string;
The user’s last name.
property username
username?: string;
The user’s Pinterest username.
interface PluginConfig
interface PluginConfig {}
property install
install?: string;
Custom install command
property platforms
platforms?: string[];
Supported platforms
property plugin
plugin: string;
Plugin NPM package name
property pluginName
pluginName: string;
Plugin name, this should match the class name
property pluginRef
pluginRef: string;
Plugin object reference
property repo
repo: string;
Github repository URL
interface PositionError
interface PositionError {}
interface PrintOptions
interface PrintOptions {}
property bounds
bounds?: number[] | any;
The Size and position of the print view
property duplex
duplex?: boolean;
Specifies the duplex mode to use for the print job. Either double-sided (duplex:true) or single-sided (duplex:false). Double-sided by default. Only supported on iOS
property grayscale
grayscale?: boolean;
If your application only prints black text, setting this property to true can result in better performance in many cases. False by default.
property landscape
landscape?: boolean;
The orientation of the printed content, portrait or landscape Portrait by default.
property name
name?: string;
The name of the print job and the document
property printerId
printerId?: string;
The network URL of the printer. Only supported on iOS.
interface PushNotification
interface PushNotification {}
method clearAllNotifications
clearAllNotifications: ( successHandler: () => any, errorHandler: () => any) => void;
iOS & android only
Tells the OS to clear all notifications from the Notification Center. successHandler gets called when the api successfully clears the notifications
Parameter successHandler
Parameter errorHandler
method finish
finish: ( successHandler: () => any, errorHandler: () => any, id?: string) => void;
iOS only
Tells the OS that you are done processing a background push notification. successHandler gets called when background push processing is successfully completed.
Parameter successHandler
Parameter errorHandler
Parameter id
method getApplicationIconBadgeNumber
getApplicationIconBadgeNumber: ( successHandler: (count: number) => any, errorHandler: () => any) => void;
iOS only
Get the current badge count visible when the app is not running successHandler gets called with an integer which is the current badge count
Parameter successHandler
Parameter errorHandler
method off
off: { ( event: 'registration', callback: (response: RegistrationEventResponse) => any ): void; ( event: 'notification', callback: (response: NotificationEventResponse) => any ): void; (event: 'error', callback: (response: Error) => any): void; (event: string, callback: (response: EventResponse) => any): void;};
As stated in the example, you will have to store your event handler if you are planning to remove it.
Parameter event
Name of the event type. The possible event names are the same as for the push.on function.
Parameter callback
handle to the function to get removed.
Parameter event
Parameter callback
method on
on: { ( event: 'registration', callback: (response: RegistrationEventResponse) => any ): void; ( event: 'notification', callback: (response: NotificationEventResponse) => any ): void; (event: 'error', callback: (response: Error) => any): void; (event: string, callback: (response: EventResponse) => any): void;};
The event registration will be triggered on each successful registration with the 3rd party push service.
Parameter event
Parameter callback
The event notification will be triggered each time a push notification is received by a 3rd party push service on the device.
Parameter event
Parameter callback
The event error will trigger when an internal error occurs and the cache is aborted.
Parameter event
Parameter callback
Parameter event
Name of the event to listen to. See below(above) for all the event names.
Parameter callback
is called when the event is triggered.
Parameter event
Parameter callback
method setApplicationIconBadgeNumber
setApplicationIconBadgeNumber: ( successHandler: () => any, errorHandler: () => any, count?: number) => void;
iOS & android only
Set the badge count visible when the app is not running
The count is an integer indicating what number should show up in the badge. Passing 0 will clear the badge. Each notification event contains a data.count value which can be used to set the badge to correct number.
Parameter successHandler
Parameter errorHandler
Parameter count
method subscribe
subscribe: ( topic: string, successHandler: () => any, errorHandler?: () => any) => void;
The subscribe method is used when the application wants to subscribe a new topic to receive push notifications.
Parameter topic
: Topic to subscribe to.
Parameter successHandler
Parameter errorHandler
method unregister
unregister: (successHandler: () => any, errorHandler?: () => any) => void;
The unregister method is used when the application no longer wants to receive push notifications. Beware that this cleans up all event handlers previously registered, so you will need to re-register them if you want them to function again without an application reload.
Parameter successHandler
Parameter errorHandler
method unsubscribe
unsubscribe: ( topic: string, successHandler: () => any, errorHandler?: () => any) => void;
The unsubscribe method is used when the application no longer wants to receive push notifications from a specific topic but continue to receive other push messages.
Parameter topic
: Topic to subscribe to.
Parameter successHandler
Parameter errorHandler
interface PushOptions
interface PushOptions {}
interface RegistrationEventResponse
interface RegistrationEventResponse {}
property registrationId
registrationId: string;
The registration ID provided by the 3rd party remote push service.
interface RemoveResult
interface RemoveResult {}
property fileRemoved
fileRemoved: Entry;
property success
success: boolean;
interface RequestAuthorizationOptions
interface RequestAuthorizationOptions {}
interface SafariViewControllerOptions
interface SafariViewControllerOptions {}
property animated
animated?: boolean;
property enterReaderModeIfAvailable
enterReaderModeIfAvailable?: boolean;
property hidden
hidden?: boolean;
property showDefaultShareMenuItem
showDefaultShareMenuItem?: boolean;
property tintColor
tintColor?: string;
property toolbarColor
toolbarColor?: string;
property transition
transition?: string;
property url
url?: string;
interface SerialOpenOptions
interface SerialOpenOptions {}
property baudRate
baudRate: number;
interface SerialPermissionOptions
interface SerialPermissionOptions {}
interface SmsOptions
interface SmsOptions {}
Options for sending an SMS
property android
android?: SmsOptionsAndroid;
property replaceLineBreaks
replaceLineBreaks?: boolean;
Set to true to replace \n by a new line. Default: false
interface SmsOptionsAndroid
interface SmsOptionsAndroid {}
property intent
intent?: string;
Set to "INTENT" to send SMS with the native android SMS messaging. Leaving it empty will send the SMS without opening any app.
interface SpeechRecognitionListeningOptionsAndroid
interface SpeechRecognitionListeningOptionsAndroid {}
property language
language?: string;
used language for recognition (default
"en-US"
)
property matches
matches?: number;
number of return matches (maximum number of matches)
property prompt
prompt?: string;
displayed prompt of listener popup window
property showPopup
showPopup?: boolean;
display listener popup window with prompt (default
true
)
interface SpeechRecognitionListeningOptionsIOS
interface SpeechRecognitionListeningOptionsIOS {}
property language
language?: string;
used language for recognition (default
"en-US"
)
property matches
matches?: number;
umber of return matches (default
5
)
property showPartial
showPartial?: boolean;
Allow partial results to be returned (default
false
)
interface SpinnerDialogIOSOptions
interface SpinnerDialogIOSOptions {}
property overlayOpacity
overlayOpacity?: number;
property textColorBlue
textColorBlue?: number;
property textColorGreen
textColorGreen?: number;
property textColorRed
textColorRed?: number;
interface StreamingAudioOptions
interface StreamingAudioOptions {}
property bgColor
bgColor?: string;
property bgImage
bgImage?: string;
property bgImageScale
bgImageScale?: string;
property errorCallback
errorCallback?: Function;
property initFullscreen
initFullscreen?: boolean;
property successCallback
successCallback?: Function;
interface StreamingVideoOptions
interface StreamingVideoOptions {}
property errorCallback
errorCallback?: Function;
property orientation
orientation?: string;
property successCallback
successCallback?: Function;
interface StripeCardTokenParams
interface StripeCardTokenParams {}
property address_city
address_city?: string;
City
property address_country
address_country?: string;
Country
property address_line1
address_line1?: string;
Address line 1
property address_line2
address_line2?: string;
Address line 2
property address_state
address_state?: string;
State / Province
property currency
currency?: string;
3-letter ISO code for currency
property cvc
cvc?: string;
CVC / CVV
property expMonth
expMonth: number;
Expiry month
property expYear
expYear: number;
Expiry year
property name
name?: string;
Cardholder name
property number
number: string;
Card number
property postal_code
postal_code?: string;
Postal code / ZIP Code
interface SuccessCallback
interface SuccessCallback<T> {}
call signature
(result?: T): void;
interface SyncOptions
interface SyncOptions extends InstallOptions {}
Defines the sync operation options.
property deploymentKey
deploymentKey?: string;
Overrides the config.xml deployment key when checking for updates.
property ignoreFailedUpdates
ignoreFailedUpdates?: boolean;
Optional boolean flag. If set, previous updates which were rolled back will be ignored. Defaults to true.
property updateDialog
updateDialog?: boolean | UpdateDialogOptions;
Used to enable, disable or customize the user interaction during sync. If set to false, user interaction will be disabled. If set to true, the user will be alerted or asked to confirm new updates, based on whether the update is mandatory. To customize the user dialog, this option can be set to a custom UpdateDialogOptions instance.
interface ThemeableBrowserButton
interface ThemeableBrowserButton {}
property align
align?: string;
property event
event?: string;
property image
image?: string;
property imagePressed
imagePressed?: string;
property wwwImage
wwwImage?: string;
property wwwImageDensity
wwwImageDensity?: number;
property wwwImagePressed
wwwImagePressed?: string;
interface ThemeableBrowserOptions
interface ThemeableBrowserOptions {}
property allowInlineMediaPlayback
allowInlineMediaPlayback?: string;
property backButton
backButton?: ThemeableBrowserButton;
property backButtonCanClose
backButtonCanClose?: boolean;
property clearcache
clearcache?: string;
property clearsessioncache
clearsessioncache?: string;
property closeButton
closeButton?: ThemeableBrowserButton;
property closebuttoncaption
closebuttoncaption?: string;
property customButtons
customButtons?: ThemeableBrowserButton[];
property disableAnimation
disableAnimation?: boolean;
property disallowoverscroll
disallowoverscroll?: string;
property enableViewportScale
enableViewportScale?: string;
property forwardButton
forwardButton?: ThemeableBrowserButton;
property fullscreen
fullscreen?: string;
property hardwareback
hardwareback?: string;
property hidden
hidden?: string;
property keyboardDisplayRequiresUserAction
keyboardDisplayRequiresUserAction?: string;
property location
location?: string;
property mediaPlaybackRequiresUserAction
mediaPlaybackRequiresUserAction?: string;
property menu
menu?: { image?: string; imagePressed?: string; title?: string; cancel?: string; align?: string; items?: { event: string; label: string; }[];};
property presentationstyle
presentationstyle?: string;
property shouldPauseOnSuspsend
shouldPauseOnSuspsend?: string;
property statusbar
statusbar?: { color: string;};
property suppressesIncrementalRendering
suppressesIncrementalRendering?: string;
property title
title?: { color?: string; staticText?: string; showPageTitle?: boolean;};
property toolbar
toolbar?: { height?: number; color?: string; image?: string;};
property toolbarposition
toolbarposition?: string;
property transitionstyle
transitionstyle?: string;
property zoom
zoom?: string;
interface ThreeDeeTouchForceTouch
interface ThreeDeeTouchForceTouch {}
interface ThreeDeeTouchQuickAction
interface ThreeDeeTouchQuickAction {}
property iconTemplate
iconTemplate?: string;
Icon template
property iconType
iconType?: string;
Icon type. Case insensitive
property subtitle
subtitle?: string;
Subtitle
property title
title: string;
Title
property type
type?: string;
Type that can be used in the onHomeIconPressed callback
interface ToastOptions
interface ToastOptions {}
property addPixelsY
addPixelsY?: number;
Add negative value to move it up a bit
property data
data?: any;
Pass JSON object to be sent back in success callback
property duration
duration?: number;
Duration in ms to show
property message
message?: string;
Message to display
property position
position?: string;
Position
property styling
styling?: { opacity?: number; backgroundColor?: string; textColor?: string; cornerRadius?: number; horizontalPadding?: number; verticalPadding?: number;};
Styling
interface TranscodeOptions
interface TranscodeOptions {}
property audioBitrate
audioBitrate?: number;
Sample rate for the audio. iOS only. Defaults to 128 kilobits (128000).
property audioChannels
audioChannels?: number;
Number of audio channels. iOS only. Defaults to 2.
property audioSampleRate
audioSampleRate?: number;
Sample rate for the audio. iOS only. Defaults to 44100
property deleteInputFile
deleteInputFile?: boolean;
Delete the original video. Android only. Defaults to false
property fileUri
fileUri: string;
The path to the video on the device.
property fps
fps?: number;
Frames per second of the result. Android only. Defaults to 24.
property height
height?: number;
Height of the result
property maintainAspectRatio
maintainAspectRatio?: boolean;
iOS only. Defaults to true
property optimizeForNetworkUse
optimizeForNetworkUse?: number;
Should the video be processed with quailty or speed in mind. iOS only
property outputFileName
outputFileName: string;
The file name for the transcoded video
property outputFileType
outputFileType?: number;
Instructions on how to encode the video. Android is always mp4
property progress
progress?: (info: number) => void;
Not supported in windows, progress on the transcode. info will be a number from 0 to 100
property saveToLibrary
saveToLibrary?: boolean;
Save the new video the library. Not supported in windows. Defaults to true
property videoBitrate
videoBitrate?: number;
Bitrate in bits. Defaults to 1 megabit (1000000).
property width
width?: number;
Width of the result
interface TrimOptions
interface TrimOptions {}
property fileUri
fileUri: string;
Path to input video.
property outputFileName
outputFileName: string;
Output file name
property progress
progress?: (info: any) => void;
Progress on transcode. info will be a number from 0 to 100
property trimEnd
trimEnd: number;
Time to end trimming in seconds
property trimStart
trimStart: number;
Time to start trimming in seconds
interface TTSOptions
interface TTSOptions {}
interface TwitterConnectResponse
interface TwitterConnectResponse {}
interface UpdateDialogOptions
interface UpdateDialogOptions {}
Defines the configuration options for the alert or confirmation dialog
property appendReleaseDescription
appendReleaseDescription?: boolean;
Flag indicating if the update description provided by the CodePush server should be displayed in the dialog box appended to the update message.
property descriptionPrefix
descriptionPrefix?: string;
Optional prefix to add to the release description.
property mandatoryContinueButtonLabel
mandatoryContinueButtonLabel?: string;
The label of the continue button in case of a mandatory update.
property mandatoryUpdateMessage
mandatoryUpdateMessage?: string;
If a mandatory update is available and this option is set, the message will be displayed to the user in an alert dialog before downloading and installing the update. The user will not be able to cancel the operation, since the update is mandatory.
property optionalIgnoreButtonLabel
optionalIgnoreButtonLabel?: string;
The label of the cancel button in case of an optional update.
property optionalInstallButtonLabel
optionalInstallButtonLabel?: string;
The label of the confirmation button in case of an optional update.
property optionalUpdateMessage
optionalUpdateMessage?: string;
If an optional update is available and this option is set, the message will be displayed to the user in a confirmation dialog. If the user confirms the update, it will be downloaded and installed. Otherwise, the update update is not downloaded.
property updateTitle
updateTitle?: string;
The title of the dialog box used for interacting with the user in case of a mandatory or optional update. This title will only be used if at least one of mandatoryUpdateMessage or optionalUpdateMessage options are set.
interface VideoInfo
interface VideoInfo {}
property bitrate
bitrate: number;
Bitrate of the video in bits per second.
property duration
duration: number;
Duration of the video in seconds.
property height
height: number;
Height of the video in pixels.
property orientation
orientation: 'portrait' | 'landscape';
Orientation of the video. Will be either portrait or landscape.
property size
size: number;
Size of the video in bytes.
property width
width: number;
Width of the video in pixels.
interface VideoOptions
interface VideoOptions {}
Options for the video playback using the
play
function.
property scalingMode
scalingMode?: number;
There are to options for the scaling mode. SCALE_TO_FIT which is default and SCALE_TO_FIT_WITH_CROPPING. These strings are the only ones which can be passed as option.
property volume
volume?: number;
Set the initial volume of the video playback, where 0.0 is 0% volume and 1.0 is 100%. For example: for a volume of 30% set the value to 0.3.
interface VisibleRegion
interface VisibleRegion {}
interface WriteOptions
interface WriteOptions {}
interface ZBarOptions
interface ZBarOptions {}
property camera
camera?: string;
A string defining the active camera when opening the scanner. Possible values: "front", "back" Default: "back"
property drawSight
drawSight?: boolean;
A boolean to show or hide a line in the center of the scanner. Default: true
property flash
flash?: string;
A string defining the state of the flash. Possible values: "on", "off", "auto" Default: "auto"
property text_instructions
text_instructions?: string;
A string representing the instruction text (Android only). Default: "Please point your camera at the QR code."
property text_title
text_title?: string;
A string representing the title text (Android only). Default: "Scan QR Code"
Enums
enum InstallMode
enum InstallMode { IMMEDIATE = 0, ON_NEXT_RESTART = 1, ON_NEXT_RESUME = 2,}
Defines the available install modes for updates.
member IMMEDIATE
IMMEDIATE = 0
The update will be applied to the running application immediately. The application will be reloaded with the new content immediately.
member ON_NEXT_RESTART
ON_NEXT_RESTART = 1
The update is downloaded but not installed immediately. The new content will be available the next time the application is started.
member ON_NEXT_RESUME
ON_NEXT_RESUME = 2
The udpate is downloaded but not installed immediately. The new content will be available the next time the application is resumed or restarted, whichever event happends first.
enum OSActionType
enum OSActionType { Opened = 0, ActionTake = 1,}
member ActionTake
ActionTake = 1
member Opened
Opened = 0
enum OSDisplayType
enum OSDisplayType { None = 0, InAppAlert = 1, Notification = 2,}
How the notification was displayed to the user. Part of OSNotification. See inFocusDisplaying for more information on how this is used.
member InAppAlert
InAppAlert = 1
(**DEFAULT**) - native alert dialog display.
member None
None = 0
notification is silent, or inFocusDisplaying is disabled.
member Notification
Notification = 2
native notification display.
enum OSLockScreenVisibility
enum OSLockScreenVisibility { Public = 1, Private = 0, Secret = -1,}
**ANDROID** - Privacy setting for how the notification should be shown on the lockscreen of Android 5+ devices.
enum SyncStatus
enum SyncStatus { UP_TO_DATE = 0, UPDATE_INSTALLED = 1, UPDATE_IGNORED = 2, ERROR = 3, IN_PROGRESS = 4, CHECKING_FOR_UPDATE = 5, AWAITING_USER_ACTION = 6, DOWNLOADING_PACKAGE = 7, INSTALLING_UPDATE = 8,}
Defines the possible result statuses of the window.codePush.sync operation.
member AWAITING_USER_ACTION
AWAITING_USER_ACTION = 6
Intermediate status - a user dialog is about to be displayed. This status will be reported only if user interaction is enabled.
member CHECKING_FOR_UPDATE
CHECKING_FOR_UPDATE = 5
Intermediate status - the plugin is about to check for updates.
member DOWNLOADING_PACKAGE
DOWNLOADING_PACKAGE = 7
Intermediate status - the update package is about to be downloaded.
member ERROR
ERROR = 3
An error happened during the sync operation. This might be an error while communicating with the server, downloading or unziping the update. The console logs should contain more information about what happened. No update has been applied in this case.
member IN_PROGRESS
IN_PROGRESS = 4
There is an ongoing sync in progress, so this attempt to sync has been aborted.
member INSTALLING_UPDATE
INSTALLING_UPDATE = 8
Intermediate status - the update package is about to be installed.
member UP_TO_DATE
UP_TO_DATE = 0
The application is up to date.
member UPDATE_IGNORED
UPDATE_IGNORED = 2
An optional update is available, but the user declined to install it. The update was not downloaded.
member UPDATE_INSTALLED
UPDATE_INSTALLED = 1
An update is available, it has been downloaded, unzipped and copied to the deployment folder. After the completion of the callback invoked with SyncStatus.UPDATE_INSTALLED, the application will be reloaded with the updated code and resources.
Type Aliases
type AdMobAdSize
type AdMobAdSize = | 'SMART_BANNER' | 'BANNER' | 'MEDIUM_RECTANGLE' | 'FULL_BANNER' | 'LEADERBOARD' | 'SKYSCRAPER' | 'CUSTOM';
type ContactFieldType
type ContactFieldType = | '*' | 'addresses' | 'birthday' | 'categories' | 'country' | 'department' | 'displayName' | 'emails' | 'familyName' | 'formatted' | 'givenName' | 'honorificPrefix' | 'honorificSuffix' | 'id' | 'ims' | 'locality' | 'middleName' | 'name' | 'nickname' | 'note' | 'organizations' | 'phoneNumbers' | 'photos' | 'postalCode' | 'region' | 'streetAddress' | 'title' | 'urls';
type EventResponse
type EventResponse = RegistrationEventResponse | NotificationEventResponse | Error;
type Region
type Region = BeaconRegion | CircularRegion;
type SpeechRecognitionListeningOptions
type SpeechRecognitionListeningOptions = | SpeechRecognitionListeningOptionsIOS | SpeechRecognitionListeningOptionsAndroid;
Package Files (134)
- dist/es5/index.d.ts
- dist/es5/plugins/3dtouch.d.ts
- dist/es5/plugins/actionsheet.d.ts
- dist/es5/plugins/admob.d.ts
- dist/es5/plugins/alipay.d.ts
- dist/es5/plugins/android-fingerprint-auth.d.ts
- dist/es5/plugins/app-update.d.ts
- dist/es5/plugins/appavailability.d.ts
- dist/es5/plugins/appodeal.d.ts
- dist/es5/plugins/apppreferences.d.ts
- dist/es5/plugins/apprate.d.ts
- dist/es5/plugins/appversion.d.ts
- dist/es5/plugins/background-fetch.d.ts
- dist/es5/plugins/background-geolocation.d.ts
- dist/es5/plugins/backgroundmode.d.ts
- dist/es5/plugins/backlight.d.ts
- dist/es5/plugins/badge.d.ts
- dist/es5/plugins/barcodescanner.d.ts
- dist/es5/plugins/base64togallery.d.ts
- dist/es5/plugins/batterystatus.d.ts
- dist/es5/plugins/ble.d.ts
- dist/es5/plugins/bluetoothserial.d.ts
- dist/es5/plugins/brightness.d.ts
- dist/es5/plugins/broadcaster.d.ts
- dist/es5/plugins/browser-tab.d.ts
- dist/es5/plugins/calendar.d.ts
- dist/es5/plugins/call-number.d.ts
- dist/es5/plugins/camera-preview.d.ts
- dist/es5/plugins/camera.d.ts
- dist/es5/plugins/card-io.d.ts
- dist/es5/plugins/clipboard.d.ts
- dist/es5/plugins/code-push.d.ts
- dist/es5/plugins/contacts.d.ts
- dist/es5/plugins/couchbase-lite.d.ts
- dist/es5/plugins/crop.d.ts
- dist/es5/plugins/datepicker.d.ts
- dist/es5/plugins/dbmeter.d.ts
- dist/es5/plugins/deeplinks.d.ts
- dist/es5/plugins/device-feedback.d.ts
- dist/es5/plugins/device.d.ts
- dist/es5/plugins/deviceaccounts.d.ts
- dist/es5/plugins/devicemotion.d.ts
- dist/es5/plugins/deviceorientation.d.ts
- dist/es5/plugins/diagnostic.d.ts
- dist/es5/plugins/dialogs.d.ts
- dist/es5/plugins/emailcomposer.d.ts
- dist/es5/plugins/estimote-beacons.d.ts
- dist/es5/plugins/facebook.d.ts
- dist/es5/plugins/file-chooser.d.ts
- dist/es5/plugins/file-opener.d.ts
- dist/es5/plugins/file.d.ts
- dist/es5/plugins/filepath.d.ts
- dist/es5/plugins/filetransfer.d.ts
- dist/es5/plugins/fingerprint-aio.d.ts
- dist/es5/plugins/firebase.d.ts
- dist/es5/plugins/flashlight.d.ts
- dist/es5/plugins/geofence.d.ts
- dist/es5/plugins/geolocation.d.ts
- dist/es5/plugins/globalization.d.ts
- dist/es5/plugins/google-plus.d.ts
- dist/es5/plugins/googleanalytics.d.ts
- dist/es5/plugins/googlemap.d.ts
- dist/es5/plugins/gyroscope.d.ts
- dist/es5/plugins/headercolor.d.ts
- dist/es5/plugins/health.d.ts
- dist/es5/plugins/hotspot.d.ts
- dist/es5/plugins/http.d.ts
- dist/es5/plugins/httpd.d.ts
- dist/es5/plugins/ibeacon.d.ts
- dist/es5/plugins/imagepicker.d.ts
- dist/es5/plugins/imageresizer.d.ts
- dist/es5/plugins/inappbrowser.d.ts
- dist/es5/plugins/inapppurchase.d.ts
- dist/es5/plugins/insomnia.d.ts
- dist/es5/plugins/instagram.d.ts
- dist/es5/plugins/is-debug.d.ts
- dist/es5/plugins/keyboard.d.ts
- dist/es5/plugins/launch-review.d.ts
- dist/es5/plugins/launchnavigator.d.ts
- dist/es5/plugins/localnotifications.d.ts
- dist/es5/plugins/location-accuracy.d.ts
- dist/es5/plugins/market.d.ts
- dist/es5/plugins/media-capture.d.ts
- dist/es5/plugins/media.d.ts
- dist/es5/plugins/mixpanel.d.ts
- dist/es5/plugins/music-controls.d.ts
- dist/es5/plugins/native-audio.d.ts
- dist/es5/plugins/native-geocoder.d.ts
- dist/es5/plugins/native-page-transitions.d.ts
- dist/es5/plugins/nativestorage.d.ts
- dist/es5/plugins/navigationbar.d.ts
- dist/es5/plugins/network.d.ts
- dist/es5/plugins/nfc.d.ts
- dist/es5/plugins/onesignal.d.ts
- dist/es5/plugins/pay-pal.d.ts
- dist/es5/plugins/photo-library.d.ts
- dist/es5/plugins/photo-viewer.d.ts
- dist/es5/plugins/pin-dialog.d.ts
- dist/es5/plugins/pinterest.d.ts
- dist/es5/plugins/plugin.d.ts
- dist/es5/plugins/power-management.d.ts
- dist/es5/plugins/printer.d.ts
- dist/es5/plugins/push.d.ts
- dist/es5/plugins/rollbar.d.ts
- dist/es5/plugins/safari-view-controller.d.ts
- dist/es5/plugins/screen-orientation.d.ts
- dist/es5/plugins/screenshot.d.ts
- dist/es5/plugins/securestorage.d.ts
- dist/es5/plugins/serial.d.ts
- dist/es5/plugins/shake.d.ts
- dist/es5/plugins/sim.d.ts
- dist/es5/plugins/sms.d.ts
- dist/es5/plugins/socialsharing.d.ts
- dist/es5/plugins/speech-recognition.d.ts
- dist/es5/plugins/spinnerdialog.d.ts
- dist/es5/plugins/splashscreen.d.ts
- dist/es5/plugins/sqlite.d.ts
- dist/es5/plugins/statusbar.d.ts
- dist/es5/plugins/stepcounter.d.ts
- dist/es5/plugins/streaming-media.d.ts
- dist/es5/plugins/stripe.d.ts
- dist/es5/plugins/text-to-speech.d.ts
- dist/es5/plugins/themeable-browser.d.ts
- dist/es5/plugins/toast.d.ts
- dist/es5/plugins/touchid.d.ts
- dist/es5/plugins/twitter-connect.d.ts
- dist/es5/plugins/unique-device-id.d.ts
- dist/es5/plugins/vibration.d.ts
- dist/es5/plugins/video-editor.d.ts
- dist/es5/plugins/video-player.d.ts
- dist/es5/plugins/webintent.d.ts
- dist/es5/plugins/youtube-video-player.d.ts
- dist/es5/plugins/z-bar.d.ts
- dist/es5/plugins/zip.d.ts
Dependencies (1)
Dev Dependencies (32)
- browserify
- canonical-path
- conventional-changelog-cli
- conventional-github-releaser
- cpr
- cz-conventional-changelog
- decamelize
- dgeni
- dgeni-packages
- es6-shim
- glob
- gulp
- gulp-rename
- gulp-replace
- gulp-tslint
- gulp-uglify
- jasmine-core
- karma
- karma-browserify
- karma-jasmine
- karma-phantomjs-launcher
- lodash
- minimist
- mkdirp
- node-html-encoder
- q
- semver
- tsify
- tslint
- tslint-ionic-rules
- typescript
- watchify
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/ionic-native
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/ionic-native)
- HTML<a href="https://www.jsdocs.io/package/ionic-native"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 22947 ms. - Missing or incorrect documentation? Open an issue for this package.