Kony 6.5 Studio API Developer's Guide
Kony Studio 6.5 is a software development kit (SDK) that allows developers to quickly and easily create mobile applications for a variety of platforms, including iOS, Android, and Windows Phone. It provides a comprehensive set of tools and APIs that simplify the development process, allowing developers to focus on building innovative and engaging mobile experiences. With Kony Studio, developers can create applications that are visually appealing, performant, and engaging, while also taking advantage of the latest mobile technologies.
Advertisement
Advertisement
Kony Studio
API Developer's Guide
Release 6.5
Document Relevance and Accuracy
This document is considered relevant to the Release stated on this title page and the document version stated on the Revision History page. Remember to always view and download the latest document version relevant to the software release you are using.
© 2015 by Kony, Inc. All rights reserved 1 of 848
Kony Studio API Developer's Guide
Version 5.0
Copyright © 2012 Kony, Inc.
All rights reserved.
July, 2015
This document contains information proprietary to Kony, Inc., is bound by the Kony license agreements and may not be used except in the context of understanding the use and methods of Kony
Inc, software without prior, express, written permission. Kony, Empowering Everywhere, Kony
MobileFabric, Kony Modeler,and Kony Visualizer are trademarks of Kony, Inc. Microsoft, the Microsoft logo, Internet Explorer, Windows, and Windows Vista are registered trademarks of Microsoft
Corporation. Apple, the Apple logo, iTunes, iPhone, iPad, OS X, Objective-C, Safari, Apple Pay,
Apple Watch and Xcode are trademarks or registered trademarks of Apple, Inc. Google, the Google logo, Android, and the Android logo are registered trademarks of Google, Inc. Chrome is a trademark of Google, Inc. BlackBerry, PlayBook, Research in Motion, and RIM are registered trademarks of
BlackBerry. All other terms, trademarks, or service marks mentioned in this document have been capitalized and are to be considered the property of their respective owners.
© 2015 by Kony, Inc. All rights reserved 2 of 848
Kony Studio API Developer's Guide
Version 5.0
Revision History
Date
07/13/2015
05/19/2015
Document Version Description of Modifications/Release
2.0
Following information is added: l
l
l
Wearables -Kony WatchKit Library
1.0
Following information is added: l
l
l
l
setApplicationCallbacks updated for iOS
© 2015 by Kony, Inc. All rights reserved 3 of 848
Table of Contents
3. Basics of JavaScript Language
3.6 Built-in JavaScript Objects
3.7 Creating own JavaScript Objects
3.8 JavaScript Object Semantics
3.9 JavaScript Function Semantics
3.10 Creating array and hash objects
3.11 OOPSified Syntax in JavaScript API
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
4 of 848
3.16 Accessing widgets and properties
3.17 Dynamic creation of widgets
4.1 kony.application.registerForIdleTimeout
4.2 kony.application.unregisterForIdleTimeout
4.3 kony.application.invalidateSession
4.4 kony.application.getPreviousSessionParams
4.5 kony.application.setApplicationCallbacks
4.6 kony.application.setApplicationInitializationEvents
4.7 kony.application.setApplicationMode
4.8 kony.application.getApplicationMode
4.9 kony.application.getCurrentForm
4.10 kony.application.getPreviousForm
4.11 kony.application.showLoadingScreen
4.12 kony.application.dismissLoadingScreen
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
5 of 848
Kony Studio API Developer's Guide
Version 5.0
4.15 kony.application.openMediaURL
4.16 kony.application.setApplicationBehaviors
4.17 kony.application.setZoomedOutView
4.18 kony.application.disableZoomedOutView
4.20 kony.application.setApplicationLayout
4.21 kony.application.setDefaultTextboxPadding
4.22 kony.application.setCheckBoxSelectionImageAlignment
4.23 kony.application.setRespectImageSizeForImageWidgetAlignment
4.24 kony.application.registerOnKeyPress(values)
4.25 kony.application.beginBackgroundTask
4.26 kony.application.endBackgroundTask
4.27 kony.application.getApplicationState
4.28 Application Settings APIs
5.1 kony.accelerometer.retrieveCurrentAcceleration
5.2 kony.accelerometer.startMonitoringAcceleration
5.3 kony.accelerometer.stopMonitoringAcceleration
© 2015 by Kony, Inc. All rights reserved
6 of 848
Kony Studio API Developer's Guide
Version 5.0
7.4 Background Fetch and Background Transfers APIs
7.5 Supported Versions and Platforms
7.6 kony.backgroundjob.registerBackgroundFetch
7.7 kony.backgroundjob.setBackgroundFetchCompletionStatus
7.8 kony.backgroundjob.setBackgroundFetchInterval
7.9 Long Running Network Tasks
7.13 Session Configuration API
8.1 kony.application.setApplicationBadgeValue
8.2 kony.application.getApplicationBadgeValue
8.5 kony.application.setAppMenuBadgeValue
© 2015 by Kony, Inc. All rights reserved
7 of 848
8.6 kony.application.getAppMenuBadgeValue
9.6 com.kony.PeripheralManager
10.1 kony.application.setBMState
10.2 kony.application.resetBMState
10.3 kony.application.addBMState
10.4 kony.application.removeBMState
10.5 kony.application.getBMState
11.1 kony.camera.releaseRawBytes
12.1 kony.application.createSettingsMenu
12.2 kony.application.setCurrentSettingsMenu
12.3 kony.application.getCurrentSettingsMenu
12.4 kony.application.addSettingsMenuItemAt
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
8 of 848
12.5 kony.application.removeSettingsMenuItemAt
13.7 kony.crypto.retrievePublicKey
13.12 kony.crypto.createPBKDF2Key()
13.13 kony.crypto.createHMacHash()
14.2 loadFunctionalModuleAsync
15.1 kony.location.getCurrentPosition
15.2 kony.location.watchPosition
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
9 of 848
16.4 addGestureRecognizerForAllForms
16.5 removeGestureRecognizerForAllForms
18.1 kony.hybrid.executeFunctionInNativeContext
18.2 kony.hybrid.executeFunctionInSPAContext
18.3 kony.hybrid.executeFunctionInTCContext
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
10 of 848
20.2 kony.i18n.getCurrentLocale
20.3 kony.i18n.getSupportedLocales
20.4 kony.i18n.getCurrentDeviceLocale
20.5 kony.i18n.setResourceBundle
20.6 kony.i18n.updateResourceBundle
20.7 kony.i18n.isResourceBundlePresent
20.8 kony.i18n.isLocaleSupportedByDevice
20.9 kony.i18n.getLocalizedString
20.10 kony.i18n.deleteResourceBundle
20.11 kony.i18n.setDefaultLocaleAsync
20.12 kony.i18n.setCurrentLocaleAsync
21.1 kony.lang.setUncaughtExceptionHandler
21.2 kony.lang.getUncaughtExceptionHandler
22.1 kony.application.setAppTile
22.2 kony.application.setSecondaryTile
22.3 kony.application.removeSecondaryTile
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
11 of 848
24.2 Enabling Mobile First APIs in Kony Studio
25.1 Asynchronous Network Calls
25.2 kony.net.invokeServiceAsync
25.3 Cancel Asynchronous Network Call
25.4 Checking Network Availability
25.5 Registering for Network Status Change Notifications
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
12 of 848
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
13 of 848
28.7 kony.os.startSecureTransaction
28.8 kony.os.endSecureTransaction
28.10 kony.os.hasAccelerometerSupport
28.12 kony.os.deviceInfo().httpheaders
28.14 kony.os.hasCameraSupport
28.16 kony.os.hasOrientationSupport
28.17 kony.os.getDeviceCurrentOrientation
28.20 kony.os.removeAllMetaTags
29.3 kony.phone.openMediaGallery
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
14 of 848
29.5 kony.phone.addCalendarEvent
29.6 kony.phone.findCalendarEvents
29.7 kony.phone.removeCalendarEvent
31.1 kony.stream.registerDataStream
31.2 kony.stream.deregisterDataStream
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
15 of 848
32.1 Distinction between string primitives and string objects
32.3 kony.string.equalsIgnoreCase
32.9 kony.string.isAsciiAlphaNumeric
32.11 kony.string.containsChars
32.12 kony.string.containsOnlyGivenChars
32.13 kony.string.containsNoGivenChars
32.14 kony.string.isValidEmail
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
16 of 848
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
17 of 848
35.3 kony.theme.setCurrentTheme
35.5 kony.theme.createThemeFromJSONString
35.6 kony.theme.isThemePresent
35.8 kony.theme.getCurrentThemeData
35.9 kony.theme.getCurrentTheme
37. Guidelines for using Threading APIs
39.1 Supported Platforms and Devices
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
18 of 848
40.3 Introduction to Constructor - WorkerThread()
40.13 Using Worker Threads Feature
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
19 of 848
43.4 Determination Of Column Affinity
43.6 Column Affinity Behavior Example
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 20 of 848
1. Preface Kony Studio API Developer's Guide
Version 5.0
1. Preface
Kony Studio is an integrated development environment (IDE) for rapid development and deployment of mobile applications. Kony Studio is provided as a plug-in to Eclipse , an open-source environment.
The IDE offers you an easy to learn and use visual development environment to design and develop the mobile applications. The primary element of Kony Studio is a visual developer panel that is used to design the application forms in a device independent wire-frame format.
All the Kony supported devices, development languages, and browsers are listed at, Supported
Devices and Browsers.
1.1 Purpose
This document explains the Application Program Interface (API) used in Kony Studio and also provides procedural information to use them to achieve functionality.
1.2 Intended Audience
This document is targeted at developers who use Kony Studio to develop applications.
1.3 Formatting Conventions
The following are the formatting conventions used throughout the document:
Click here
© 2015 by Kony, Inc. All rights reserved 21 of 848
1. Preface Kony Studio API Developer's Guide
Version 5.0
Conventions
Monospace
Italic
Bold
URL
Explanation l
User input text, system prompts, and responses l
File path l
Commands l
Program code l
File names.
l
Emphasis l
Names of books and documents l
New terminology.
l
Windows l
Menus l
Buttons l
Icons l
Fields l
Tabs l
Folders.
Active link to a URL.
Provides helpful hints or additional information.
Note:
Important:
Highlights actions or information that might cause problems to systems or data.
© 2015 by Kony, Inc. All rights reserved 22 of 848
1. Preface Kony Studio API Developer's Guide
Version 5.0
1.4 Related Documents
Document
Kony Server Installation
Guides
Kony Studio Installation
Guide
Kony Widget User Guide
Purpose
This guide will help you understand the server installation procedure.
This guide will help you understand the Kony Studio installation procedure.
This guide will help you understand the widgets and their functionality in Kony Studio.
1.5 Contact Us
We welcome your feedback on our documentation. Write to us at [email protected]
.
For technical questions, suggestions, comments or to report problems on Kony's product line, contact [email protected]
.
© 2015 by Kony, Inc. All rights reserved 23 of 848
2. Introduction Kony Studio API Developer's Guide
Version 5.0
2. Introduction
The API reference guide comprises of all the non GUI APIs that you can use on Kony Studio. The non
GUI APIs enable you to perform multiple operations on an application, such as performing various operations on tables, manipulating strings, or invoking a service. The APIs are categorized in this guide by the corresponding namespaces. For example, all the APIs which have the namespace kony.i18n.<xyz> are present in the Internationalization section.
The Kony API library consists of the following: l
String Library: The string Library has APIs that you can use to manipulate strings. The namespace is kony.string.
l
Standard Kony: The generic APIs with the namespace kony.
l
Window Library: The APIs with the namespace kony.ui using which you can invoke alerts.
l
Internationalization: The i18n APIs enable you to design or develop an application in such a way that it supports various languages and regions. The namespace for internationalization is kony.i18n.
l
Timer: The APIs in this library provide you the ability to schedule the execution of a function block at regular intervals. The namespace for Timer API is kony.timer.
l
Push Notification: Push Notifications APIs enable you to initiate a message delivery to a device without receiving a request. The namespace for Push API is kony.push.
l
Phone: The APIs in this chapter provide you the ability to access the default applications of the underlying platform on the mobile device and perform operations. The namespace for Phone
API is kony.phone.
l
OS: This chapter comprises all the APIs with the namespace kony.os.
l
Application: During the lifecycle of an application, the mobile device usually triggers several events. The APIs in this chapter allow you to listen to these events and override them with
© 2015 by Kony, Inc. All rights reserved 24 of 848
2. Introduction Kony Studio API Developer's Guide
Version 5.0
application specific functionality. The chapter comprises all the APIs with the namespace kony.application.
l
Streaming : Streaming is a feature that is capable of listening to a continuous data stream and use the data. The data is available on Streaming Servers. The common use of streaming is to utilize the multimedia from an external source (like audio or video) in your application. Streaming data uses different protocols to fetch the data. The chapter comprises all the APIs with the namespace kony.stream.
l
Cryptography: Cryptography is the process of securing the information. It can be defined as the conversion of data into scrambled text (concealing its readability and meaning) and deciphering it using a key. This data can be sent across safely over public and private networks. The chapter comprises all the APIs with the namespace kony.crypto.
l
Network: The Network APIs enable you to invoke service calls or cancel network calls. The chapter comprises all the APIs with the namespace kony.net.
l
Data Access: The Data Access APIs comprise the WebSQL APIs and the Local Storage APIs and you can store and manipulate data on the device or database. The chapter comprises all the APIs with the namespace kony.db and kony.store.
l
Accelerometer: The Accelerometer APIs allow you to capture the device motion acceleration in
X, Y, Z directions and also provide out of the box mechanisms to register for shake gestures event. The chapter comprises of all the APIs with the name kony.accelerometer.
l
Hybrid: Kony Platform provides complete flexibility to choose different packaging and deployment modes according to the needs of the application. This chapter comprises all the
APIs with the namespace kony.hybrid.
l
Live Tiles: Live Tiles enable you to represent an application as a tile on the Start Screen of your device. You can launch the application using a Live Tile. This chapter comprises of all the APIs that enable you to add Live tiles. The namespace of all the APIs in this chapter is kony.application.
l
Wearables : Wearables are body-borne miniature electronic devices such as an Apple Watch and Android Wear. Using an Apple Watch and Android Wear, you can access information
© 2015 by Kony, Inc. All rights reserved 25 of 848
2. Introduction Kony Studio API Developer's Guide
Version 5.0
quickly without glancing at your phone. When you pair a watch with your phone, you can keep track of calendar appointments, notifications and more from your watch. Based on the action associated with the notification, you can interact with your phone.
l
Mobile First APIs : Kony provides Mobile First APIs that allows you to use native APIs of iOS and Android platforms in Kony Studio. The native APIs are provided as JavaScript APIs.
2.1 Platform Availability
The following table provides all the platforms that are supported:
MOBILE
— iPhone
— Android
— BlackBerry l
BlackBerry 10 Z10 l
BlackBerry 10 Q10 l
BlackBerry 10 A10 l
BlackBerry JDE 7.0:
Touch l
BlackBerry JDE 7.0:
Bold
✔
✔
✔
✔
✔
✔
✔
Native
✔ ✔
HTML5
SPA
✔
✔
✔
✔
Web
Server Side Mobile
Web
✔
Hybrid
✔
✔
✔
© 2015 by Kony, Inc. All rights reserved 26 of 848
2. Introduction Kony Studio API Developer's Guide
Version 5.0
l
BlackBerry JDE 7.0:
Touch only l
BlackBerry JDE 7.0:
Curve l
BlackBerry JDE 7.0:
Storm l
BlackBerry JDE 6.0:
Torch l
BlackBerry JDE 5.0:
Storm l
BlackBerry JDE 5.0:
Bold l
BlackBerry JDE 5.0:
Pearl 3G l
BlackBerry JDE 5.0:
8800
— Windows Phone 8
— Windows Phone 7.5
— Non Touch Devices l
Windows Phone 7.5
✔
✔
✔
✔
✔
✔
✔
✔
✔
✔
Native
HTML5
SPA
✔
✔
✔
Web
Server Side Mobile
Web
Hybrid
© 2015 by Kony, Inc. All rights reserved 27 of 848
2. Introduction Kony Studio API Developer's Guide
Version 5.0
l
BlackBerry 6.0 & other
— Other Advanced Devices
— Basic Devices with JS
(BJS)
— Basic Devices
TABLET
— iPad
— Android Tab
— Windows 8 l x86 l x64 l
ARM
DESKTOP
— Desktop Web
— Windows 7 / Kiosk l x86
✔
✔
✔
✔
✔
✔
✔
✔
✔
✔
Native
✔
HTML5
SPA
✔
✔
✔
✔
✔
✔
✔
✔
✔
Web
Server Side Mobile
Web
Hybrid
✔
✔
✔
© 2015 by Kony, Inc. All rights reserved 28 of 848
2. Introduction l x64
Kony Studio API Developer's Guide
Version 5.0
Native
HTML5
SPA
✔
Web
Server Side Mobile
Web
Hybrid
© 2015 by Kony, Inc. All rights reserved 29 of 848
3. Basics of JavaScript Language Kony Studio API Developer's Guide
Version 5.0
3. Basics of JavaScript Language
This document does not cover the fundamentals of JavaScript, nor does it act as a tutorial on
JavaScript. This document only discusses the items relevant to the Kony APIs.
Any valid JavaScript as per the European Computer Manufacturers Association (ECMA) standard should work and any constraints and additional notes are captured under each section.
The information provided in the following URL can help as a reference tutorial for the JavaScript language: http://docstore.mik.ua/orelly/webprog/jscript/index.htm
This section covers the following topics: l
l
l
l
l
o
How is "undefined" treated in Kony APIs?
l
o
Handling primitives and default type conversions
l
Creating own JavaScript Objects
3.1 ECMAScript
JavaScript is an implementation of European Computer Manufacturers Association (ECMA) Script
Language standard. ECMA-262 is the official JavaScript standard. ECMA-262 has three versions and
JavaScript should be compliant with ECMA v3.
The following Mozilla Developer Network can act as JavaScript reference:
© 2015 by Kony, Inc. All rights reserved 30 of 848
3. Basics of JavaScript Language Kony Studio API Developer's Guide
Version 5.0
https://developer.mozilla.org/en/JavaScript/Reference#About_this_Reference
Note: JavaScript is case-sensitive.
3.2 OOPs
l
JavaScript is an Object-Oriented Programming Language.
l
Object consists of properties and methods.
l
You can define your own Objects and make your own variable types.
3.3 Variables
l
JavaScript variables are either local or global.
l
Undeclared variables (without "var" prefix like "x=5") are by default global.
// a globally-scoped variable var a=1;
// global scope function one(){ alert(a);
}
// local scope function two(a){ alert(a);
}
// local scope again function three(){ var a = 3;
© 2015 by Kony, Inc. All rights reserved 31 of 848
3. Basics of JavaScript Language Kony Studio API Developer's Guide
Version 5.0
} alert(a);
// Intermediate: no such thing as block scope in javascript function four(){ if(true){ var a=4;
} alert(a); // alerts '4', not the global value of '1'
}
3.4 Primitive Data Types
JavaScript has three primitive data types. As JavaScript is a loosely typed language, a variable type is determined at runtime by the type of value it contains.
l string l numeric l boolean
Important: Octal literals should be avoided in JavaScript Code. Numbers prefixed with 0 will be treated as octal numbers by most of the Javascript Engines but some throw an exception. If you want to parse the octal number from string variable use parseInt with radix parameter."
3.5 Special Data Types
There are two special data types in JavaScript: l null l undefined
© 2015 by Kony, Inc. All rights reserved 32 of 848
3. Basics of JavaScript Language Kony Studio API Developer's Guide
Version 5.0
In JavaScript, "null" is considered as an object type and hence it is not a primitive type but a value of type object. It is a special type in JavaScript, as the data type of a variable is known at run time.
"undefined" is a type when a variable is never defined.
But both "null" and "undefined" represent non-existence. That means: l
(null == undefined) is true in JavaScript, but l
(null === undefined) is false because their types are different.
Note: === looks for type matching. The Kony API's expect "null" as an argument.
Important: For optional parameters ensure that you pass an empty datatype of the optional parameter in the API signature.
3.5.1 How is "undefined" treated in Kony APIs?
Platforms do not distinguish between "undefined" and "null".
Note: When undefined data types are passed to Kony APIs, it is treated as null. Kony APIs never return undefined data types. The type "undefined" is not available on underlying platforms. Thus
"underlying" is mapped to null.
3.6 Built-in JavaScript Objects
l
String - Create a string object by placing a text in double quotes or single quotes.
l
Date - Create using "new" operator like
var today = new Date();
l
Array - Create an array using "new" operator like
var myarray = new Array();
or a literal array like:
var myarray = ["a", "b", "c"];
© 2015 by Kony, Inc. All rights reserved 33 of 848
3. Basics of JavaScript Language Kony Studio API Developer's Guide
Version 5.0
l
Boolean - Boolean object to represent true or false and converts non-boolean value to boolean.
var myboolean = new Boolean()
l
Math - A "Math" object for mathematical tasks, contains math constants like Math.PI, and methods like:
Math.sqrt(16)
l
RegExp - A "RegExp" object to search for pattern of characters in a given text.
var patt = new RegExp(pattern, modifiers)
or simply
var patt=/pattern/modifier;
3.6.1 Handling Primitives and Default Type Conversions l
When primitives string, boolean are passed to the methods where String, Boolean objects are expected, then Kony APIs, by default, implicitly wraps the primitive string inside String object and boolean inside Boolean object.
l string and boolean primitives, and String and Boolean objects can be used inter-operably.
l
Some of the built-in JavaScript objects such as Date, RegExp can be used as part of the
JavaScript logic that developer writes, but none of the Kony APIs respect these JavaScript types in the initial versions of JavaScript Kony APIs.
l
Implicit conversions - string, number, and boolean are mutually exchangeable wherever possible. Kony APIs will implicitly try converting these types as required and as expected.
l
Any exceptions to these implicit conversions are mentioned in the APIs section against each
API.
l
For example, "4.5" as string can be passed to API where number is expected and API does the required conversion if it is convertible.
3.7 Creating own JavaScript Objects
In any Object-Oriented Programming Language, you can define and create your own objects.
Creating direct instance of an object
© 2015 by Kony, Inc. All rights reserved 34 of 848
3. Basics of JavaScript Language Kony Studio API Developer's Guide
Version 5.0
Approach 1: (new operator) personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue";
Approach 2: (object literals) personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Creating an object constructor
Create a function that constructs objects: this.age=age; function Person(firstname,lastname,age,eyecolor)
{ this.firstname=firstname; this.lastname=lastname; this.eyecolor=eyecolor;
//a method this.newlastname=newlastname;
} function newlastname(new_lastname)
{ this.lastname=new_lastname;
}
Create new instances from the object constructor like this: var myFather=new Person("John","Doe",50,"blue"); var myMother=new Person("Sally","Rally",48,"green");
© 2015 by Kony, Inc. All rights reserved 35 of 848
3. Basics of JavaScript Language Kony Studio API Developer's Guide
Version 5.0
Note: All the above styles of creating the JavaScript object are valid.
© 2015 by Kony, Inc. All rights reserved 36 of 848
Kony Studio API Developer's Guide
Version 5.0
3.8 JavaScript Object Semantics
Note: The Objects and Widgets that Kony APIs create and return, acts as first class JavaScript object with the exceptions mentioned in the section.
Limitations mentioned in this section are not applicable for the user defined custom JavaScript objects.
But it is important to be aware of these limitations in order to write a uniform, consistent codebase, which treats custom JavaScript objects and JavaScript objects that Kony API returns similarly.
This section covers the following topics: l
l
l
l
Functions Inside the JavaScript Object
l
Adding Properties and Methods Dynamically
l
l
l
l
l
3.8.1 Prototype Inheritance
JavaScript's prototype mechanism simplifies the process of adding custom properties and methods to all instances of an object.
© 2015 by Kony, Inc. All rights reserved 37 of 848
Kony Studio API Developer's Guide
Version 5.0
function Person(firstname,lastname,age,eyecolor)
{ this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor;
}
//create an instance object of person var myFather=new Person("John","Doe",50,"blue");
//custom property added to person object myFather.profession="CEO";
In the above code, "profession" is a custom property added to person object instance and with this way the property exists only for that instance of the object. For other instances of the person object, say
myMother.profession
would return as "undefined".
myFather.prototype.profession="CEO";
In the above code, the keyword "prototype" just before the custom property will make the property exist in all instances of an object.
Note: None of the objects and widgets that Kony APIs return can be inherited through prototypical inheritance. Doing so may lead to unexpected results and behavior is undefined.
However the custom JavaScript objects that developers write are expected to have support for prototype property, allowing developers to use inheritance for the custom JavaScript objects that they author.
3.8.2 Enumerating Properties
Any JavaScript object can be iterated for its properties as below:
© 2015 by Kony, Inc. All rights reserved 38 of 848
Kony Studio API Developer's Guide
Version 5.0
var obj = { key1: 12, key2: "Jim"}; for (prop in obj)
{ alert(prop + ' = ' + obj[prop]);
}
Any of the objects and widgets that Kony JavaScript APIs return can be iterated as above. When container widgets such as box, form, scrollbox are iterated, it should list out not only its own properties but also list out the child widgets like they were directly the properties of the container widgets.
3.8.3 Associative arrays
In JavaScript, objects are also associative arrays (or hashes). For example, in the below code: var obj = { key1: 12, key2: "Jim"}; obj.key1 // is one way to access the property obj['key1'] //is associative array of accessing the properties.
Properties of the any of the objects and widgets that Kony JavaScript APIs return can be accessed in both the above styles.
3.8.4 Functions Inside the JavaScript Object
JavaScript Objects is a collection of properties. These properties can either be primitive data types, other objects, or functions.
var obj = { key1: 12, key2: "Tom", doubleKey1 : function()
{
"return key1 * 2"
}
};
Now doubleKey1 is a function that can be invoked as:
© 2015 by Kony, Inc. All rights reserved 39 of 848
Kony Studio API Developer's Guide
Version 5.0
obj.doubleKey1();
Developers can have the functions inside the JavaScript object as needed and even pass it to the
Kony APIs as demanded and required by the Kony APIs.
3.8.5 Adding Properties and Methods Dynamically
Note: All the JavaScript objects that are created or returned from Kony APIs do not allow dynamically adding, removing properties and methods. If the developer chooses to do so, the behavior is undefined.
Dynamically adding, removing properties and methods are possible only for the user defined custom
JavaScript Objects.
For example, the below code will work only for user defined JavaScript objects, but not for the objects that Kony API returns.
var obj = { key1: 12, key2: "Tom"}; delete obj.key1;
3.8.6
toString() method
All the JavaScript Objects created and returned through Kony APIs will respond to toString method by returning the stringfied JSON representation of the object.
Note: If JavaScript Object returned by Kony APIs contain any methods, then both the method and corresponding key are ignored in having them in the JSON representation returned by the toString.
User defined JavaScript objects will have default implementation of toString method unless the toString method is redefined to return the strings appropriately.
© 2015 by Kony, Inc. All rights reserved 40 of 848
Kony Studio API Developer's Guide
Version 5.0
3.8.7
this keyword
JavaScript has a different concept of what the special name this refers to than most other programming languages do.
this always refers to the "owner" of the function we're executing, or rather, to the object that a function is a method of. In general, the object bound to this in the current scope is determined by how the current function was called, it can't be set by assignment during execution, and it can be different each time the function is called.
The link below helps you to understand how "this" behaves in different contexts.
https://developer.mozilla.org/en/JavaScript/Reference/Operators/this
Kony platform ensures that in the event callbacks or event handlers, " this" always refers to the widget that raised the event. In the example below " this" is referring to the button (with id foo) as it is the button that would be calling the onClick callback when the event occurs.
function handleClick(button)
{ print(this.id); // will print foo as "this" is referring to the button that raised the event.
} var button = new kony.ui.Button({"id":"foo",onClick=handleClick},{},
{});
3.8.8 instanceof, typeof instanceof operator should work on all custom JSObjects and also the objects that platform returns.
typeof operator will not distinguish custom kony objects and when used, it returns only an object.
For example, the following is a valid statement:
© 2015 by Kony, Inc. All rights reserved 41 of 848
Kony Studio API Developer's Guide
Version 5.0
function testInstanceOfandTypeOf()
{ var color1 = new String("green"); var res1 = color1 instanceof String; // returns true because instance of checks for the object type var color2 = "coral"; //no type specified var res2 =color2 instanceof String; // returns false (color2 is not a String object) var res3 = typeof color1; //typeof returns a string representing the type of its operand.
var res4 = typeof typeof color1 ; alert("res1 :"+res1 +"\n res2 :"+res2 +"\nres3 :" +res3 +
"\nres4 :" + res4);
}
3.8.9 Unsupported Methods
The following methods of the JavaScript Object are not supported by the JavaScript objects that are created and returned by Kony APIs.
l toLocaleString l valueOf l hasOwnProperty l isPrototypeOf
Note: User defined JavaScript objects will still respond to the above, but it is recommended not to use these methods for a uniform cross-platform behavior.
© 2015 by Kony, Inc. All rights reserved 42 of 848
Kony Studio API Developer's Guide
Version 5.0
3.8.10 Unsupported Properties
Following properties of the JavaScript Object are not supported by the JavaScript objects that are created and returned by Kony APIs.
l constructor
Note: User defined JavaScript objects will still respond to the above, but it is recommended not to use these methods for a uniform cross-platform behavior.
© 2015 by Kony, Inc. All rights reserved 43 of 848
Kony Studio API Developer's Guide
Version 5.0
3.9 JavaScript Function Semantics
All the functions that Kony API accepts and returns should be valid JavaScript Function with all the semantics with the exceptions mentioned in the section.
This section covers the following topics: l
l
l
The apply( ) and call( ) Methods
3.9.1 Nested Functions and Closures
Nested functions and closures are allowed as it is first class feature of the JavaScript language. Every function in JavaScript can be closure and can have nested functions as required.
The following URL will help in the understanding of closures and nested functions: http://blog.morrisjohns.com/javascript_closures_for_dummies
Functions that contain the nested functions can be passed to the Kony APIs (as a callback to the events) and the underlying platforms use the ECAM-262 v3 compatible engine to execute the functions. Closures can also be passed to the Kony APIs (as a callback to the events.
3.9.2
length function
Function should support the length function which indicates the number of arguments that it takes.
Following code fragments explain how to access the length property: var f = function(x) {}; f.length // returns 1
arguments.callee.length
is another way of accessing the expected number of arguments for the function.
© 2015 by Kony, Inc. All rights reserved 44 of 848
Kony Studio API Developer's Guide
Version 5.0
function checkArgs(x,y,z)
{ var actual_passed_args = arguments.length; var expected_args = arguments.callee.length; if(actual_passed_args != expected_args)
{
//do something
}
}
3.9.3 The apply( ) and call( ) Methods
Every JavaScript function will have apply and call methods which can be used to invoke the functions with arguments dynamically and also passing the context (this) in which the function to be executed.
JavaScript
Note: Objects that Kony API creates and returns can be passed as context or one of the arguments. Functions exposed by the Kony APIs cannot be invoked through apply and call methods.
© 2015 by Kony, Inc. All rights reserved 45 of 848
Kony Studio API Developer's Guide
Version 5.0
3.10 Creating array and hash objects
All collections will either be Arrays or Hash objects.
Arrays are created in JavaScript as shown below: var myarray = new Array();
Or are literal arrays such as: var myarray = ["a", "b", "c"];
Hashes are created as JavaScript objects as described in the basics section of JavaScript.
3.10.1 Array methods
Below are some of the array methods that can be created using Kony APIs.
l push l pop l unshift l shift l toString l splice l slice l concat l join
© 2015 by Kony, Inc. All rights reserved 46 of 848
l sort l reverse
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 47 of 848
Kony Studio API Developer's Guide
Version 5.0
3.11 OOPSified Syntax in JavaScript API
3.11.1 Widget Creation API
Widget creation API follows the "new" syntax: frmDealerDetails = new kony.ui.form2(basicConf, layoutConf, pspConf);
3.11.2 Method Invocation
Method access occurs in the oopsified way and the JavaScript syntax for adding widgets to a form is as follows: frmDealerDetails.add(hBox11, hBox22);
© 2015 by Kony, Inc. All rights reserved 48 of 848
Kony Studio API Developer's Guide
Version 5.0
3.12 Exceptions
This section covers the following topics: l
l
l
l
3.12.1 JavaScript Native Exceptions:
JavaScript natively supports the following error objects as per the ECMA specification: l
Error l
EvalError l
RangeError l
ReferenceError l
SyntaxError l
TypeError l
URIError
Error - A generic error class which is a super class of all other specific error classes in
JavaScript. This is the error class that programmers typically use to throw exceptions. All other subclass errors are thrown by the JavaScript engines.
EvalError - This error is thrown when there is illegal use of Eval() function.
RangeError - It is thrown when a numeric value is not in its valid range.
ReferenceError - It is thrown when you attempt to access a variable that does not exist.
© 2015 by Kony, Inc. All rights reserved 49 of 848
Kony Studio API Developer's Guide
Version 5.0
SyntaxError - It is thrown when certain functions experience syntax errors like RegExp(),
Function(), eval().
TypeError - It is thrown when the value is not of the type required for the context.
Accessing a property of null or undefined values can cause this error. Accessing an undefined method for a class can also throw this error. It is also thrown when a function is called with too many arguments specified.
URIError - It is thrown when there is an error in decoding a URI.
As per ECMA spec, all the above error types have two properties: name - The type of the exception. All subclasses, by default, populate this property with value as its Constructor name, which is TypeError class will populate name with
"TypeError".
message - A string describing the exception.
The above native exceptions are thrown by the JavaScript engine in scenarios when trying to access a missing property, or trying to invoke an undefined method.
Throw Statement:
In JavaScript, a developer can throw an error using the "throw" statement and the same can be caught using the try/catch block.
For example, to throw an exception, the JavaScript statement is as follows: throw new Error("You have an exception"); or you can throw any Primitive type like String, number and boolean: or throw "You have an exception"; throw 1001;
© 2015 by Kony, Inc. All rights reserved 50 of 848
Kony Studio API Developer's Guide
Version 5.0
or even any JavaScript object can be thrown using throw statements: throw new MyError("errorcode", "name", "message");
//MyError is your own custom JavaScript object, need not be one of the native JavaScript error types.
3.12.2 Kony Error
As JavaScript throw statements support any JavaScript object which can be caught in the try/catch block, Kony APIs leverage this capability to throw the custom error object in case of errors.
Kony APIs throw this custom type of error object in different scenarios, in addition to the above native
JavaScript error types.
Kony APIs throw a custom error object (JavaScript Object) called KonyError and will have the below properties: l errorCode - the error code to represent a specific exception type. This is additional and you will not find this in JavaScript Native exceptions.
l name - the name of the error, similar property as in the native Error object. This will be predefined value from the platform with meaningful names representing the error / exception.
For example, "MissingMandatoryParameter" for errorcode 121, "InvalidInputValue" for errorcode 122 etc.
l message - the error message, similar property as in native Error object.
As Kony APIs cannot throw any error other than KonyError, developers are expected to distinguish the errors based on the name and error code properties.
Please note that KonyError is not a replacement for the error callbacks that are available in the Kony
APIs. Any error callbacks present in the API continue to be the same.
3.12.2.1 Error Names and Codes
The following are the Error Names with corresponding codes and descriptions:
© 2015 by Kony, Inc. All rights reserved 51 of 848
Kony Studio API Developer's Guide
Version 5.0
Error - thrown when there is a generic error.
l
100 - invalid type of parameters.
l
101 - invalid number of arguments.
l
102 - invalid input - thrown when the input is invalid based on the context.
l
103 - invalid operation - thrown when the operation is invalid based on the context.
l
104 - not supported error - thrown when the method is not supported at all.
l
105 - index out of range.
l
106 - unknown error.
WidgetError - All widget related error codes are wrapped in this error object type. Various error conditions related to Widget creation will be covered through the following error codes: l
1100 - Not a widget error.
l
1101 - Widget with duplicate ID error when widget is added to the hierarchy.
l
1102 - Widget cannot be created due to invalid input data.
l
1103 - Same widget instance is added to multiple hierarchies.
l
1104 - Widget cannot be created due to insufficient data (mandatory parameters missing)
NetworkError - All network related error codes are wrapped in this error object type. Various error conditions related to network will be covered through the following error codes: l
1000 i18nError - All error codes thrown by the Internationalization APIs. Various error conditions related to i18n will be covered through the following error code: l
1300
© 2015 by Kony, Inc. All rights reserved 52 of 848
Kony Studio API Developer's Guide
Version 5.0
ContactsError - All error codes thrown by the Contact APIs. Various error conditions related to
Contact will be covered through the following error code: l
1400
DataStoreError - All error codes thrown by the DataStore APIs. Various error conditions related to
DataStore will be covered through the following error code: l
1500
LocationError - All error codes thrown by the location based service APIs. Various error conditions related to LocationError will be covered through the following error code: l
1600
PushNotificationError - All error codes thrown by the Push Notification APIs. Various error conditions related to Push Notification will be covered through the following error code: l
1700 - Unable to connect to push service - Push Notification Service (PNS) is not available.
l
1701 - Registration failed by PNS - Account related or device restrictions (thrown by kony.push.register() API during an onfailureregistration callback).
l
1702 - Deregistration failed - Unable to close channel or PNS internal error while deregistration
(thrown by kony.push.deRegister() API during an onfailurederegistration callback).
l
1703 - Duplicate Registration (thrown by kony.push.register() API during an onfailureregistration callback).
l
1704 - Platform Specific issue. Complete details are available in the error message. JavaScript
Example: Received payload but payload is in incorrect format etc.
© 2015 by Kony, Inc. All rights reserved 53 of 848
Kony Studio API Developer's Guide
Version 5.0
PropertyAccessError - All error codes thrown by the Push Notification APIs. Various error conditions related to property access will be covered through the following error code: l
1800 - No such property exists. Thrown when a non-existent property is accessed.
l
1801
SkinError - All error codes thrown when there is an error related to the skins.
l
1900
CryptoError - All error codes thrown by Crypto API. Various error conditions related to CryptoError will be covered through the following error code: l
2001 - unsupported algorithm.
l
2002 - invalid key strength specified.
l
2003 - insufficient buffer provided for specified operation.
l
2004 - memory allocation failure.
l
2005 - input data did not encode or encrypt properly.
l
2006 - specified name already exists.
l
2007 - key with the specified unique ID is not found.
PhoneError - All error codes thrown by Phone API.
Various error conditions related to Phone Error will be covered through the following error code.
l
2100: Unable to send the Message.
l
2101 - Insufficient Permissions.
© 2015 by Kony, Inc. All rights reserved 54 of 848
Kony Studio API Developer's Guide
Version 5.0
l
2102 - Cannot open mail, mail not configured.
l
2103 - Cannot open media gallery.
StreamingError - All error codes thrown by Streaming API. Various error conditions related to Stream
Error will be covered through the following error code.
l
2201 - Streaming identifier does not exist.
Note: The actual streaming error is returned in the callback function.
Please refer to the API section for error details. Each API mentions the error name and the error code that it throws.
3.12.2.2 Accessing the Kony Error
While mapping the Native Exceptions that are thrown by underlying platforms to the JavaScript
Exception, it was found that for some platforms like BlackBerry, it is not consistent with other implementations.
try
{
….
} catch ( e )
{ if (e instanceof KonyError) alert("A Kony error"); else (e instanceof EvalError) alert("A JS Eval Eror");
}
© 2015 by Kony, Inc. All rights reserved 55 of 848
Kony Studio API Developer's Guide
Version 5.0
The above code snippet could have been ideal from the developer's perspective, but due to limitations in BlackBerry in mapping the native Java exceptions to JavaScript, the recommended cross platform means of accessing the Kony Error objects is as follows: try
{
….
} catch ( e )
{ var err = kony.getError(e); if (err instanceof KonyError) alert("A Kony error"); else (err instanceof EvalError) alert("A JS Eval Eror");
} kony.getError will give you access to the actual error that is thrown by the JavaScript Engine or by the underlying platforms.
Please refer the Kony APIs section for the respective type of error object, error codes and the defined name against each API.
© 2015 by Kony, Inc. All rights reserved 56 of 848
Kony Studio API Developer's Guide
Version 5.0
3.13 Skins
l
The skins need to be predefined and bundled with the application. This is in similar lines with how you create CSS files and refer in JavaScript scripts.
l
Skins are created per widget. Every skin will also have widget type information which indicates the widget for which the skin is created.
l
Skin parameters may vary based on the widget type for which the skin is defined.
l
Skins are allowed to be defined externally in a text file represented in JSON format. These external files will be bundled along with the application and individual platforms take care of loading the skins from these files as needed.
l
Skins always referred in JavaScript through a string identifier which uniquely represents the skin definition.
l
Skins are Immutable and there is no API defined in JavaScript to get handle to the actual skin and modify skins programmatically.
l
In future, the Skin APIs to get handle over the existing skins, modify and create the skins will be introduced.
l
Keys in the JSON skin remain same as that of what we have today (in Kony IDE) and we will add new skin keys going forward to align with CSS.
Note: window.createSkin API in JavaScript is no more required. All widget creation APIs take skin as string identifier and the code generation component generates the global string identifiers corresponding to each skin.
3.13.1 JSON format to represent skins
Follow the below format to define a skin in JSON format:
© 2015 by Kony, Inc. All rights reserved 57 of 848
Kony Studio API Developer's Guide
Version 5.0
{
//An outer JSON array with all skin's grouped to define a theme
"skinid 1": { wType: "label", font_size:"10", background_ color:"#fffff1", …font_style:"none"},
"skinid 2": {wType: "button", font_weight:"bold",font_ color:"000000",...font_style:"Arial"},
.........
"skinid n": {wType: "form", font_weight:"bold",font_ color:"000000",...font_style:"Arial"}
}
The outer JSON object with nested structure represents a theme with skinid's as properties. The value of skins is another JSON object with array of key value pairs.
wType is the standard property of the skin which indicates the type of widget for which the skin is defined.
3.13.2 Themes
Theme is set of skin definitions associated with a name (unique identifier) and present in a file.
In Kony APIs, themes are referred through the name of the theme.
l
Each theme should be maintained in a different file with a theme id as the filename and with a
.theme extension. For example, theme file name for "red" theme id should be "red.theme".
l
There should be a "default.theme" file existing in every application bundle representing a default theme for an application. Presence of "default" theme is a must in the application bundle.
l
The "default" theme must contain all the skin definitions that are used as a part of the application. Referring to a skin which doesn't exist in the theme will result in an error.
l
All specific theme definitions should contain skins that are always a subset of the skins defined in
"default" theme.
© 2015 by Kony, Inc. All rights reserved 58 of 848
Kony Studio API Developer's Guide
Version 5.0
l
If "default.theme" is missing then no skins are applied explicitly, which result in the system default skins available in individual platforms.
l
In each theme, one can store the metadata (additional key, values) relevant for the theme using the standard key "metadata" and the same can be read programmatically using theme APIs.
For example, the "default.theme" file defining two button skins appears as follows:
{
"gradroundfocusbtn":
{ wType: "button"
"bg_type": "two",
"background_style": "vg",
"background_gradient_top_color": "96beff00",
"background_gradient_bottom_color": "ffffff00",
"font_color": "00000000",
"border_color": "b7d2ff00",
"border_width": 1,
"border_style": "rc"
},
"gradroundbtn":
{
"bg_type": "two",
"background_style": "vg",
"background_gradient_top_color": "ffffff00",
"background_gradient_bottom_color": "96beff00",
"font_color": "00000000",
"border_color": "8db9fa00",
"border_width": 1,
"border_style": "rc"
}
© 2015 by Kony, Inc. All rights reserved 59 of 848
Kony Studio API Developer's Guide
Version 5.0
}
3.13.3 Theme level fallback
If a theme is set and the theme does not exist, then the theme is not loaded and application will continue with the current theme. There is no fallback at the theme level.
Please refer to the theme related APIs to set a theme as current theme.
3.13.4 Skin level fallback
If referred skin does not exist in the current set theme, then system will fall back to the default theme to find out the referred skin, if it is present.
For example, a skin id "labelSkin" not found in the current theme, say "red.theme" then the system should fall back and look for the skin id in "default.theme" as default is the superset of skins.
When the referred skin is not found even in "default.theme", then system should throw SkinError.
Note: The fall back has to happen at the skin level but not at the individual property of the skin.
3.13.5 Overriding themes and skins for each platform
Platform specific theming or overriding the themes per platform basis is a must have feature. Currently
IDE takes care of allowing skins to be overridden per platforms basis and packages them appropriately. With JavaScript as additional language, now the developer has a choice of using the
IDE or manually coding the complete application. This requirement of hand coding application in
JavaScript makes it all the more important to have a proper application folder structure and file naming conventions especially for managing platform specific nuances like skinning etc.
© 2015 by Kony, Inc. All rights reserved 60 of 848
Kony Studio API Developer's Guide
Version 5.0
3.14 Preprocessor statements
Preprocessor statements are handled by the compiler (or preprocessor) before the program is actually compiled. All # statements are processed first, and once this substitution has taken place by the preprocessor, the program is bundled with the native executable.
Important: Avoid using comments which follow the preprocessor pattern. For e.g. a comment starting with //# will result into an error.
//#define <identifier>
Defines an identifier.
//#undef <identifier>
Removes a defined identifier, or does nothing if the identifier is not defined.
//#ifdef <identifier>
Tests whether an identifier is defined, and parses the code block until either a #endif or #else directive is reached.
//#ifndef <identifier>
Tests whether an identifier is not defined, and parses the code block until either a #endif or #else directive is reached.
//#else
A code block executed when #ifdef or #ifndef return false. Code is parsed until a #endif directive is reached.
© 2015 by Kony, Inc. All rights reserved 61 of 848
Kony Studio API Developer's Guide
Version 5.0
//#endif
Ends a code block.
3.14.1 Predefined Identifiers
Following are the predefined identifiers that can be used by the JavaScript developers and in addition developers also can create more identifiers through #define.
Windows l
Mobile 8 – “winphone8” l
Mobile below 8 – “winmobile” l
Tablet – “windows8” l
Desktop windows – “desktop_kiosk”
Android iOS l
Mobile – “android” l
Tablet – “tabrcandroid” l
Mobile –“iphone” l iPad – “ipad”
BlackBerry l
BB - "bb" l
BB10 - "bb10"
© 2015 by Kony, Inc. All rights reserved 62 of 848
SPA l
SPA iPhone - "spaip" l
SPA Android - "spaan" l
SPA BB - "spabb" l
SPA Windows - "spawindows" l
SPA winphone8 -"spawinphone8" l
SPA BB Non Touch - "spabbnth" l
SPA iPad - "spaipad" l
SPA Android Tab - "spatabandroid" l
SPA Windows Tablet - "spatabwindows" l
SPA Playbook - "spaplaybook"
Desktop Web l
Desktopweb - "desktopweb"
Thin Client l
TC iPhone - "xadvip" l
TC Android - "xadvand" l
TC BB - "xadvbb" l
TC BB Non Touch - "xadvnth" l
TC Palm - "xadvpalm" l
TC Basic - "basic" l
TC BJS - "bjs"
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
63 of 848
Kony Studio API Developer's Guide
Version 5.0
3.15 Margins and Paddings
Margins: Defines the space around a widget. You can use this option to define the top, left, right, and bottom distance between the widget and the next element.
Paddings: Defines the space between the content of the widget and the widget boundaries. You can use this option to define the top, left, right, and bottom distance between the widget content and the widget boundary.
© 2015 by Kony, Inc. All rights reserved 64 of 848
Kony Studio API Developer's Guide
Version 5.0
3.15.1 Margins for all platforms
Margins and paddings are taken as % relative to the parent width across the platforms. It is very similar to how BlackBerry and Mobile Web treat the margins and paddings as of Kony Platform version 4.1.
For internal calculations, individual platforms have to consider the real physical pixels / resolution of the device.
This % based margins and paddings should allow developers to provide one set of margins and paddings to ensure the uniform look & feel across the platforms.
3.15.2 Ability to override per platform basis
By following percentage based margins and paddings, developers can ensure that uniform look & feel with one set of margins and paddings across the platforms. However, the IDE will allow overriding the margins and paddings for each platform.
© 2015 by Kony, Inc. All rights reserved 65 of 848
Kony Studio API Developer's Guide
Version 5.0
3.16 Accessing widgets and properties
Every widget is a JavaScript Object and follows the JavaScript Object semantics, except a few as mentioned in
JavaScript Object Semantics . Widget properties can be accessed with the "." notation or
with "[]" notation very similar to how JavaScript Object properties can be accessed.
For example, var label1=form1.label1; var value=label1.text;
Alternatively same can be retrieved using "[]" notation.
var label1 = form1["label1"]; var value = label1["text"];
To access the widgets and the properties, it is not necessary to refer through complete hierarchy but individual widgets can be accessed directly if you have the handle to the widget.
For example,
"text property" of the label1 can be accessed directly without referring the complete hierarchy if you have a handle to label1 .
label1.text or label1["text"];
Above is applicable even to the boxes which are set as the headers, footers of the Form.
3.16.1 Avoiding the box hierarchy
While accessing the widgets and properties by referring the complete hierarchy you can choose to completely avoid the boxes to be mentioned in the referred path.
© 2015 by Kony, Inc. All rights reserved 66 of 848
Kony Studio API Developer's Guide
Version 5.0
For example, in the below hierarchy:
You can access the widget in the following ways: form1.box1.label1.text
form1.label1.text
form1.box1.box2.label2.text
form1.label2.text
Mixed mode is not allowed, which means either you completely avoid the box hierarchy to refer a widget or mention the complete hierarchy including all boxes to reach the widget.
form1.box1.label2
is not a valid format.
© 2015 by Kony, Inc. All rights reserved 67 of 848
Kony Studio API Developer's Guide
Version 5.0
3.17 Dynamic creation of widgets
Widgets can be created dynamically in any JavaScript module and added to the form hierarchy. It is not necessary to have all the widget creation as a part of addWidgets (form lifecycle method) method.
addWidgets allows you to organize the code such that all the widget creation occurs in one place. But on a need basis one can create new widgets and add them to the form hierarchy in any JavaScript module.
Widgets can be dynamically added or removed from the form hierarchy and these changes reflect on the form when the form becomes visible. If changes are on a currently visible form, then changes are reflected immediately.
Note: Adding a widget to a form or box hierarchy that is already a part of the another widget hierarchy leads to undefined behaviors.
3.17.1 Duplicate Widget IDs
Widgets when added to the form hierarchy should ensure that widget ID (identifiers) is unique in the form hierarchy. Widgets with duplicate ID are not allowed with in the same form hierarchy.
Adding Widgets with duplicate IDs will result in undefined behavior and platforms may throw widget error.
3.17.2 Adding same widgets to multiple hierarchies
Adding the same widget to multiple hierarchies is not allowed.
Before adding a widget, developers have to ensure that a widget is not already present as a part of any of the existing widget hierarchies (forms, boxes). If the widget is present, developers have to explicitly remove the widget from the hierarchy and add it the new widget hierarchy.
© 2015 by Kony, Inc. All rights reserved 68 of 848
Kony Studio API Developer's Guide
Version 5.0
3.17.3 Modifying the widget hierarchy
Widgets in the hierarchy can be removed and new widgets can be added through the Kony APIs such as add etc., but existing widgets in the hierarchy cannot be reassigned / modified directly.
For example, frm1.label1 = new kony.ui.label(..) // is in correct and will throw
Widget Error.
frm1.label1 = null // is in correct and may throw Widget Error.
3.17.4 Forms, Popups creation, and destruction
Forms and Popups are top level container widgets. New forms and popups can be created on need basis and shown as needed.
Destroying forms and popups can happen through destroy method and all the semantics as described in the destroy API are applicable.
Note: Directly assigning the null to the forms and popups will lead to memory leaks and as a guideline assigning null to forms and popup should be avoided.
Please refer the destroy API of form and popup.
© 2015 by Kony, Inc. All rights reserved 69 of 848
Kony Studio API Developer's Guide
Version 5.0
3.18 Backward compatibility
Note: Any new methods, properties and deprecations introduced in JavaScript.
3.18.1 Margins and Paddings
For example, margins, paddings in the new JavaScript platform will be treated as % relative to the parent. But when run in backward compatibility mode then they retain the behavior of Kony Platform version 4.1.
In backward compatibility mode - all the margins and paddings will be as it was in version 4.1 even for the new widgets and new forms that will be added to the project.
3.18.2 App menu related methods
New app menu APIs are introduced in JavaScript API. Old App menu related methods as supported in version 4.1 should be supported as is for the backward compatibility except for camelCase change in
API names.
Developer should be able to use either new APIs or old set of APIs but mixing them in a single project will lead to undefined behavior.
3.18.3 Headers and Footers
In new Kony APIs, headers and footers attached to the form can be accessed just like any other box as long as the developer has the handle to the box representing the header or footer.
For backward compatibility, the previous usage of the headers and footers as of version 4.1 should be retained as is. That is app.headers.*. Developer should be able to use either new way of accessing or old way but mixing both the styles in one project is not recommended, as it will lead to undefined behavior..
© 2015 by Kony, Inc. All rights reserved 70 of 848
Kony Studio API Developer's Guide
Version 5.0
3.18.4 Content Alignment
Content Alignment property now takes all possible 9 values. For backward compatibility it can also take the old values such as "left", "right", and "center".
3.18.5 Flattening the box hierarchy
For backward compatibility, platforms have to support flattening the box hierarchy and avoid developers to mention the box hierarchy while accessing the widgets.
For example in the below hierarchy: form1->box1->label1 form1->box2->label2
Following is allowed for the backward compatibility: form1.box1, from1.box2, form1.label1, form1.label2
3.18.6 Widget Level methods
All the old widget methods are available in JavaScript as well. The naming convention has been changed as per the JavaScript standards.
3.18.7 os.platform() os.platform() API has been deprecated and the same API is broken into multiple, easy to use methods such as deviceInfo and hasXXXSupported methods. For backward compatibility, all platforms will support os.platform API as is.
© 2015 by Kony, Inc. All rights reserved 71 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4. Application APIs
During the lifecycle of an application, the mobile device usually triggers several events. The APIs in this chapter allow you to listen to these events and override them with application specific functionality.
It is recommend that you register for application events during the application load event of the project or masterdataload event of the startup form. This chapter consists of the APIs with the namespace kony.application.
l
kony.application.registerForIdleTimeout
l
kony.application.unregisterForIdleTimeout
l
kony.application.invalidateSession
l
kony.application.getPreviousSessionParams
l
kony.application.setApplicationCallbacks
l
kony.application.setApplicationInitializationEvents
l
kony.application.setApplicationMode
l
kony.application.getApplicationMode
l
kony.application.getCurrentForm
l
kony.application.getPreviousForm
l
l
l
l
kony.application.setApplicationBehaviors
l
kony.application.showLoadingScreen
l
kony.application.dismissLoadingScreen
© 2015 by Kony, Inc. All rights reserved 72 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l
kony.application.setZoomedOutView
l
kony.application.disableZoomedOutView
l
l
kony.application.setApplicationLayout
l
kony.application.setDefaultTextboxPadding
l
kony.application.setCheckBoxSelectionImageAlignment
l
kony.application.setRespectImageSizeForImageWidgetAlignment
l
kony.application.registerOnKeyPress
l
kony.application.beginBackgroundTask
l
kony.application.endBackgroundTask
l
kony.application.getApplicationState
4.1 kony.application.registerForIdleTimeout
This API specifies if the application must timeout after a defined period of inactivity (time difference between the current device time and the last time you clicked on any user interface component) and also specifies the action after the timeout interval.
Important: l
You must enable the forms for idletimeout by setting the property for enabledForIdleTimeout as
True in the IDE. The idletimeout event is triggered only when the user is on a form that is enabled for idletimeout.
l
When the idletimeout event is triggered, the user is navigated to the home screen with an alert message.
© 2015 by Kony, Inc. All rights reserved 73 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l
In BJS devices, to validate registerForIdleTimeout, an event must be triggered once time out is occurred.
4.1.1 Use Case
You can use this API typically in financial applications when you want to log the user out automatically after a specific period of inactivity. This way, you can ensure that there is no un-authorized access to the application or to the sensitive information like account number, credit card numbers, and so on.
4.1.2 Signature
JavaScript: kony.application.registerForIdleTimeout(
,
)
4.1.3 Input Parameters timeoutValue [Number] - Mandatory.
The timeout value in minutes.
callback [Function] - Mandatory.
The function that must be executed after the timeout has occurred. The callback function has the logic to display the current form. The function can be changed during runtime.
Note: Current form is the Form that was being displayed on the device screen when the timeout occurred.
4.1.4 Return Values
None.
© 2015 by Kony, Inc. All rights reserved 74 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.1.5 Implementation Details
The idletimeout event is triggered only once for every call to
registerForIdleTimeout
API and this event is not fired again until the next call to the API. The idletimeout event unregisters itself automatically when the event is fired. When the event unregisters itself, the application can register again for idletimeout.
The following are a few scenarios:
Scenario 1 idletimeout event is triggered after the specified time interval, but the user is on a form that is not enabled for idletimeout. In this case, the function associated with the event is executed as soon as the user navigates to the form that is enabled for idletimeout.
Note: In this case, the form that the user is trying to navigate to is never shown as the idletimeout event takes precedence.
Scenario 2 idletimeout event is triggered and the user is on a form enabled for idletimeout. In this case, the associated function is executed immediately.
Scenario 3
The application is registered for idle time out and the user tries to register again for idletimeout. In this case, the latter call to the
registerForIdleTimeout
API has no affect and is ignored.
Scenario 4
The application is registered for idletimeout but none of the forms in the application are enabled for idletimeout. In this case, this API has no affect and the behavior of the application is undefined.
Each underlying platform handles the idletimeout event differently:
© 2015 by Kony, Inc. All rights reserved 75 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
iPhone l
When the application is running in the background, no logic is executed. However, the timers keep running and the idletimeout event is triggered in the background. But the function is executed immediately when the application comes to foreground.
Note: When the application comes to foreground, you will suddenly notice the function of the idletimeout event getting executed.
Android l
When you press the device Back button to go out of the application, the underlying OS destroys the UI activity. In such cases, the idletimeout event is fired only when the application comes to the foreground.
l
When you navigate out of the application using the device Home button, the underlying OS pauses the UI activity but does not destroy it. In such cases, the idletimeout event is fired immediately in the background.
BlackBerry l
The underlying OS triggers the idletimeout event when the application is in background. The associated function of the idletimeout event also gets executed when the application is in background.
Symbian l
The underlying platform runs the timer and triggers the idletimeout event even when the application is in background. The function associated with the event is executed as soon as the application comes to the foreground.
Mobile Web l
In Mobile Web applications, the timer is not active when the application goes into background or sleep mode. When the application comes into foreground, the timer starts running and the
idletimeout
triggers after the specified time interval.
© 2015 by Kony, Inc. All rights reserved 76 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.1.6 Rules and Restrictions
This API is applicable only when the Form property Enable Time Out is set to true. For more information about Enable Time Out property, see Kony Widget User Guide.
4.1.7 Exceptions
An error is thrown if input is invalid or does not follow the expected structure.
102-Invalid input error
4.1.8 Platform Availability
Available on all platforms.
4.1.9 JavaScript Example function test()
{
//Logic for the callback function registerForIdleTimeout
} function registerForIdleTimeout()
{ kony.application.registerForIdleTimeout(1, test);
}
4.2 kony.application.unregisterForIdleTimeout
This API specifies that the application must not timeout after a defined period of inactivity (time difference between the current device time and the last time you clicked on any user interface component). This API unregisters the application from idletimeout.
© 2015 by Kony, Inc. All rights reserved 77 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.2.1 Use Case
This API must be used in case you do not want to track the idle time, i.e., do not want to logout even if the application is inactive for a specific time interval.
4.2.2 Signature
JavaScript: kony.application.unregisterForIdleTimeout()
4.2.3 Input Parameters
The API does not have any input parameters.
4.2.4 Return Values
None.
4.2.5 Rules and Restrictions
This API is applicable only when the Form property Enable Time Out is set to true. For more information about Enable Time Out property, see Widget User Guide.
4.2.6 Platform Availability
Available on all platforms.
4.2.7 JavaScript Example function unregisterForIdleTimeout()
{ kony.application.unregisterForIdleTimeout(); alert("====unRegister======");
}
© 2015 by Kony, Inc. All rights reserved 78 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.3 kony.application.invalidateSession
This API explicitly invalidates a session on Mobile Web.
Important: This API is applicable only on Mobile Web platforms
4.3.1 Use Case
You can use this API for Financial applications where you want to completely invalidate the session on execution of specific functions. For example, logout function. When the user logs out from the application, you can invoke this API to invalidate the current session and initiate a new session before navigating to any other form. In this case, all the session data is cleared.
4.3.2 Signature
JavaScript: kony.application.invalidateSession(
,
)
4.3.3 Input Parameters formName [Handle to the form] - Optional
Specifies the form to which the application must navigate after the session is invalidated params [Function] - Optional
Specifies a table of parameters that you want to pass to the new session
4.3.4 Return Values
This API navigates to the specified form or remains on the same form if there is no form specified.
© 2015 by Kony, Inc. All rights reserved 79 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.3.5 Rules and Restrictions
When the current session is invalidated, the Mobile Web framework will start the application lifecycle again. This API invokes appinit and then navigates the user to the startup form or any form that is associated with the logout function.
4.3.6 Platform Availability
Available on Mobile Web.
4.3.7 JavaScript Example
//The following function is for invalidateSession API function invalidateSession()
{
//invalidating the session kony.application.invalidateSession();
}
4.4 kony.application.getPreviousSessionParams
This API retrieves the previous session parameters in the application life cycle.
Important: You must use the kony.application.invalidateSession("frmName", sessionParams)
API before using kony.application.getPreviousSessionParams API.
4.4.1 Signature
JavaScript: kony.application.getPreviousSessionParams()
© 2015 by Kony, Inc. All rights reserved 80 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.4.2 Input Parameters
This API does not have any parameters.
4.4.3 Return Values listOfParams [Array]
Returns a table of the previous session parameters that is passed from the invalidateSession API.
4.4.4 Platform Availability
Available on Mobile Web
4.4.5 JavaScript Example
//The following function is for getPreviousSessionParams API
//You must use the invalidateSession("frmName", sessionParams) API before using getPreviousSessionParams API. function invalidateSession()
{
//invalidating the session var sessionParams = {}; sessionParams ["category"] = "news"; sessionParams ["country"] ="US"; kony.application.invalidateSession("frmName", sessionParams);
} function getPreviousSessionParams()
{
//Collecting all the params in to an object var mySessionParams = kony.application.getPreviousSessionParams(); kony.print("mySessionParams are"+mySessionParams);
}
© 2015 by Kony, Inc. All rights reserved 81 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.5 kony.application.setApplicationCallbacks
This API captures the callback events for various states of the application which include: l onactive - state which indicates that the mobile device is active and application is running l oninactive - state which indicates that the mobile device is inactive and application is running l onbackground - state which indicates that the application is active and running in the background.
For more information on iOS application behavior on background, click here l onforeground - state which indicates that the application is active and running in the foreground l onappterminate - state which indicates that the application is terminated and not running.
l onkeyboardchange - state which indicates whether a keyboard is deployed for an application.
l onpowersourcechange - state which indicates whether if a power source is attached to a device.
l onnetworkchange - this is specific to Mango. This state occurs whenever there is a change in the following: o
Status - Indicates the status of the device. The different statuses are Connected,
Disconnected, Roaming or Unknown.
o
Network- Indicates the network available on the device. The network statuses are
Wireless80211, Ethernet, MobileBroadbandGSM, MobileBroadbandCDMA, or None.
o
Date - Indicates the date on which the event occurs.
Note: Android supports only onbackground and onforeground states.
© 2015 by Kony, Inc. All rights reserved 82 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
onapplicationopenurl -To support interprocess communication (IPC) message authentication, Kony provides an application callback
onapplicationopenurl
. The
onapplicationopenurl
callback is used if an application needs to authenticate another application. To use this callback, applications must register with it. The
onapplicationopenurl
callback takes
sourceApplication
,
url
, and
annotation (via
UIDocumentInteractionController)
as input parameters. If the developer chooses to process the commands/information, True must be returned. If the developer chooses to ignore the commands/information passed, then False must be returned.
4.5.1 Signature
JavaScript : kony.application.setApplicationCallbacks(
)
4.5.2 Input Parameters callbacks [Object] - Mandatory
Specifies an Object with key as appstate and value as the callback function for the corresponding appstate. The following are the different appstates possible: l onappterminate: This state which indicates that the application is terminated and not running.
Callbacks specific to Android l onbackground: This state which indicates that the application is active and running in the background.
l onforeground: This state which indicates that the application is active and running in the foreground.
Callbacks specific to Windows
© 2015 by Kony, Inc. All rights reserved 83 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l onkeyboardchange - This state indicates whether a keyboard is deployed for an application.
l onpowersourcechange - This state indicates whether a power source is attached to a device.
l onnetworkchange - This state occurs whenever there is a change in the following: o
Status: Indicates the status of the device. The different statuses are Connected,
Disconnected, Roaming or Unknown.
o
Network: Indicates the network available on the device. The network statuses are
Wireless80211, Ethernet, MobileBroadbandGSM, MobileBroadbandCDMA, or None.
o
Date: Indicates the date of the event.
Callbacks specific to iOS l onactive - This state occurs when there is an incoming SMS, phone call, or anything else that interrupts the automatic lock of the mobile device.
l oninactive - This state occurs when the application is idle for a specific time interval.
l shouldAllowExtensions - You can use extensions to enable a specific task beyond your app functionality and make available to users while they are using other apps or the system. This callback provides a mechanism to enable or disable the extensions in iOS framework. Following are the input parameter and return values of this callback: l string - [Mandatory - Specifies the entensionID that contains the identifier to identify the extension.
l
Return values - Returns a boolean value. If true is returned, the extension is enabled. If false is returned, the extension is disabled. By default, all the extensions are enabled.
Note: Extensions are available from iOS8 and above versions.
© 2015 by Kony, Inc. All rights reserved 84 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
//Sample code function shouldAllowExtensions(extensionID)
{ if (extensionID == "com.apple.keyboard - service")
{ accessed return true; //will allow the keyboard extension to be
}
return false;
} l onlowmemory - This state indicates that the app received a memory warning from the system.
l onapplicationopenurl - To support interprocess communication (IPC) message authentication,
Kony provides an application callback
onapplicationopenurl
. The
onapplicationopenurl
callback helps a developer do some authentication when an app is opened from an already running app. To use this callback, applications must register with it. The
onapplicationopenurl
callback takes
sourceApplication
,
url
, and
annotation (via UIDocumentInteractionController)
as input parameters. If the developer processes the commands/information,
True
must be returned. If the developer ignores the commands/information passed, then
False
must be returned.
This callback accepts the following arguments:
© 2015 by Kony, Inc. All rights reserved 85 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l sourceApplication - String – Mandatory - The application that requests to open a URL.
l url - String – Mandatory - The URL that is to be opened.
l annotation - Dictionary - Mandatory - If the URL refers to a file that is opened through a document interaction controller, then the source application can send information contained in this dictionary. Otherwise, this value is nil. The receiving app must know about the keys of the dictionary sent.
l
Return Value - True or False.
l onwatchrequest - This method is used to handle the requests coming from Apple WatchKit
Extension. The dictionary object is a dictionary of value pairs and represents the context for request to be processed.
This callback accepts the following arguments: l userInfo- [Dictionary] This parameter is mandatory. A dictionary of key value pairs.
l replyObject- [JSObject]- This parameter is mandatory. This object is used to send the response asynchronously. To send the response we should call a method
(executeWithReply) on this JSObject. The method accepts a key value pairs that form the response to be sent back.
//Sample code for onwatchrequest callback method.
function jsfunction(userInfo, replyObj)
{
if (userInfo["requestName"]=="getData"){
var responseDict={"key1":"value1","key2":"value2" };
replyObj.executeWithReply(responseDict);
}
}
© 2015 by Kony, Inc. All rights reserved 86 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
Note: It is possible to that execution of this call back might happen while the application is in the background. It is suggested to check the application state and perform UI updates in the phone application only when the application is running in the foreground.You may use getapplicationstate APIs.
l onactivityrequest - This method is used to handle the handoff activity request that are sent to the application.
This callback accepts the following arguments: l activityName - [String] This parameter is mandatory. A string that represents the name of the activity.
l activityInfo - [Dictionary] This parameter is mandatory. A dictionary containing custom user information.
This callback method returns a boolean (true/false) value that indicates the request handle status.
//Sample code for onactivityrequest callback method.
function jsfunction(activityName, activityInfo)
{
if (activityName =="continueActivity"){
// use activityInfo dictionary to continue the past activity on the iPhone
return true;
}
return false;
} l onpreactivityrequest - This method is used to ask the receiving application, whether it wants to continue the handed off activity. If this callback method returns true, then the onactivityrequest callback method gets invoked where the receiving app gets a chance to continue the handed off activity.
© 2015 by Kony, Inc. All rights reserved 87 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
This callback accepts the following arguments: l activityName - [String] This parameter is mandatory. A string that represents the name of the activity.
If this callback method returns true, then the you notify the user that the receiving app wants to continue the activity on the device. If the callback method returns false, then iOS notifies the user to continue activity on the device.
//Sample code for onpreactivityrequest callback method.
function jsfunction(activityName)
{
if (activityName =="continueActivity"){
return true;
}
return false;
}
4.5.3 Return Values
None.
4.5.4 Exceptions
An error is thrown if input is invalid or does not follow the expected structure.
l
100 - Invalid type pf parameters.
l
101 - Invalid number of arguments.
l
102 - Invalid input error
4.5.5 Platform Availability
Available on all platforms except Desktop Web, SPA, and Mobile Web.
© 2015 by Kony, Inc. All rights reserved 88 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.5.6 JavaScript Example
//onactive function function test()
{ alert("===============Test executed=======");
}
//oninactive function function test1()
{ alert("===============Test1 executed=======");
}
//onbackground function function test2()
{ alert("===============Test2 executed=======");
}
//onforeground function function test3()
{ alert("===============Test3 executed=======");
}
//onappterminate function function test4()
{ alert("===============Test4 executed=======");
}
© 2015 by Kony, Inc. All rights reserved 89 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
//setcallbackfunction function setCallBacks()
{ alert("===============setApplicationCallbacks executed======="); var callbacksObj =
{onactive:test,oninactive:test1,onbackground:test2,onforeground:test
3,onappterminate:test4}; kony.application.setApplicationCallbacks(callbacksObj);
}
//onapplicationopenurl kony.application.setApplicationCallbacks
({onapplicationopenurl:callbackFunction});
Example 1.
function callbackFunction (sourceApplicaion, url, annotation)
{v ar flag = false; if (sourceApplication == "AppOne" && url == "appTwo://….")
{f lag = true;
}r eturn flag;
}
Example 2.
function callbackFunction (sourceApplicaion, url, annotation)
{v ar flag = false; if (annotation) //annotation can be nil as well… refer parameter description…
{i f (annotation[key1] == 10)
{f
© 2015 by Kony, Inc. All rights reserved 90 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
lag = true;
}}r eturn flag;
}
//onWatchRequest sample code function jsfunction(requestObject){ return <returnValue>;
} kony.application.setApplicationCallbacks({onwatchrequest: jsfunction}) requestObject – is a dictionary of key value pairs.
Returnvalue – Any JS Object consisting of numbers, strings and boolean data types.
4.6 kony.application.setApplicationInitializationEvents
This API is used to configure all initialization events such as, preappinit, postappinit, init, appservice, showstartupform and so on. The application lifecycle is as follows:
Important: This API must be invoked only once during the application lifecycle. You should NOT invoke this API as part of the application lifecycle, because Kony Studio will generate the code that invokes the API automatically. Invoking this API multiple times will result in an undefined behavior.
© 2015 by Kony, Inc. All rights reserved 91 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.6.1 Signature
JavaScript:
kony.application.setApplicationInitializationEvents( callbacks
)
4.6.2 Input Parameters callbacks [Object] - Mandatory
Is a Hash table which comprises of the following key value pairs: l preappinit[params]:This is an existing event that the developer registers in the IDE per application basis. This event consists of any logic that needs to be executed before the initialization of forms, skins, and any other application initialization
© 2015 by Kony, Inc. All rights reserved 92 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
activities. For e.g loading the i18n resource bundles dynamically etc.
l init[params]: init is generated by the code and consists of the form and skin initialization data.
l postappinit[params]: Is an existing event that the developer registers in the IDE per application basis. Developers use this function to define logic that needs to be executed before the first form is shown and after the application is initialized.
Note: postappinit can return a form handle. If postappinit returns a form handle, then the platform shows the form returned from the postappinit callback, otherwise the platform invokes the showstartupform function.
l appservice[params]:The closure provided against appservice will be invoked by the platform in a sequence. This function also returns the form handle.
Note: appservice can return a form handle. If appservice returns a form handle, then the platform shows the form returned from the appservice callback. If appservice does not return a form handle, the platform invokes the showstartupform function.
Note: If both postappinit and appservice return the form handle then, the form returned by app service is given priority by the platforms.
l showstartupform[params]: This is a method invoked by the platform to show the startup form, as indicated in the IDE.
Note: This event is invoked only when postappinit returns a nil. If appservice returns a form handle, showstartupform is not invoked.
l deeplink[params]: This method is Thinclient/SPA specific and if appservice event is provided, then this event will be ignored.
© 2015 by Kony, Inc. All rights reserved 93 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.6.3 Return Values
None.
4.6.4 Exceptions l
102 - InvalidInputError: An error is thrown if input is invalid.
l
100- TypeError: An error is thrown when the type is invalid.
4.6.5 Platform Availability
Available on all platforms.
4.6.6 JavaScript Example
//onactive function function test()
{ alert("===============Test excuted=======");
}
//oninactive function function test1()
{ alert("===============Test1 excuted=======");
}
//onbackground function function test2()
{ alert("===============Test2 excuted=======");
}
© 2015 by Kony, Inc. All rights reserved 94 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
//onforeground function function test3()
{ alert("===============Test3 excuted=======");
}
//onappterminate function function test4()
{ alert("===============Test4 excuted=======");
}
//setAppInitialization function function setAppInitializationEvents()
{ kony.application.setApplicationInitializationEvents({init:test, preappinit:test1, postappinit:test2, appservice:test3, showstartupform:test4, deeplink:test5}); alert("===============setAppInitializationEvents excuted=======");
}
4.7 kony.application.setApplicationMode
This API enables you to set the application mode to Native, Hybrid, or Wrapper.
4.7.1 Signature
JavaScript: kony.application.setApplicationMode(Integer constant)
© 2015 by Kony, Inc. All rights reserved 95 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.7.2 Input Parameters
Integer Constant l
1: constants.APPLICATION_MODE_NATIVE
l
2: constants.APPLICATION_MODE_HYBRID
l
3: constants.APPLICATION_MODE_WRAPPER
4.7.3 Return Values
None
4.7.4 Special Considerations
This API should be called only in preappinit or before the execution of preappinit. If this API is invoked elsewhere in the program, it is invalid and leads to undefined behavior.
4.7.5 Exceptions
Error
4.7.6 Platform Availability
Available on all platforms.
4.7.7 JavaScript Example function setApplicationMode()
{ kony.application.setApplicationMode(APPLICATION_MODE_NATIVE);
}
© 2015 by Kony, Inc. All rights reserved 96 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.8 kony.application.getApplicationMode
This API enables you to get the application mode.
4.8.1 Signature
JavaScript: kony.application.getApplicationMode()
4.8.2 Input Parameters
None
4.8.3 Return Values
Integer Constant l
1: constants.APPLICATION_MODE_NATIVE
l
2: constants.APPLICATION_MODE_HYBRID
l
3: constants.APPLICATION_MODE_WRAPPER
4.8.4 Special Considerations
This API should be called only in preappinit or before the execution of preappinit. If this API is invoked elsewhere in the program, it is invalid and leads to undefined behavior.
4.8.5 Exceptions
Error
4.8.6 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 97 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.8.7 JavaScript Example function getApplicationMode()
{ kony.application.getApplicationMode();
}
4.9 kony.application.getCurrentForm
This API returns a handle to the current form. The form handle is useful when you are sending analytics to the analytic engine.
Note: For iOS, kony.application.getCurrentForm() returns the form id of current form. This rule does not apply for form used as cameraOverlay.
4.9.1 Use Case
You can use this API in the following scenarios:
1. When you want to send analytics to the analytic engine.
2. When you want to use the handle to the current form in any other function.
4.9.2 Modeled After
None
4.9.3 Signature
JavaScript : kony.application.getCurrentForm()
© 2015 by Kony, Inc. All rights reserved 98 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.9.4 Input Parameters
None
4.9.5 Return Values currentForm - Object
This API returns the current form.
4.9.6 Rules and Restrictions
The following are the guidelines applicable for the API: l
If you invoke this API in the
preshow
method of the application, it does not have any affect.
l
If you invoke this API in the
appinit
method of the application, nil is returned.
4.9.7 UI Behavior
None
4.9.8 Platform Availability
Available on all platforms.
4.9.9 JavaScript Example function getCurrentForm()
{
//Get the current form var currentForm = kony.application.getCurrentForm();
//Alert the current form alert("currentForm is::"+currentForm);
}
© 2015 by Kony, Inc. All rights reserved 99 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.10 kony.application.getPreviousForm
This API returns a handle to the previous form.
4.10.1 Use Case
You can use this API in the following scenarios:
1. When you want to send analytics to the analytic engine.
2. When you want to use the handle to the current form in any other function.
4.10.2 Modeled After
None
4.10.3 Signature
JavaScript: kony.application.getPreviousForm()
4.10.4 Input Parameters
None
4.10.5 Return Values previousForm-Object
API returns the previous form handle.
4.10.6 Rules and Restrictions
The following are the guidelines applicable for the API:
© 2015 by Kony, Inc. All rights reserved 100 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l
If you invoke this API in
preshow
event of the application, you get unpredictable results.
l
If you invoke this API in the
appinit
method of the application, nil is returned.
l
If you use the Back button on the mobile web browser, this API does not return the handle to the previous form.
l
If you use this API on the first form of the application it returns null/nil.
4.10.7 UI Behavior
None
4.10.8 Platform Availability
Available on all platforms.
4.10.9 JavaScript Example function getPreviousForm()
{
//Get the Previous form var previousForm = kony.application.getPreviousForm();
//Alert the Previous form alert("previousForm is::"+previousForm);
}
4.11 kony.application.showLoadingScreen
This API allows you to display a loading screen (following a certain color schema) to the user while another action is in progress. The loading screen can be defined in such a way it can either block the
UI or does not block the UI. Typically, the loading screen is a semi-transparent screen over-laid on the current form.
© 2015 by Kony, Inc. All rights reserved 101 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.11.1 Use Case
You can use this API to display a loading screen to the end user with a specific skin attached to it in the following scenarios: l on invoking a service l on executing a user-defined function that takes some time for execution.
4.11.2 Signature
JavaScript: kony.application.showLoadingScreen(
,
,
isBlocked , showProgressIndicator
,
4.11.3 Input Parameters skin [skin identifier] - Mandatory
The skin to be applied to the loading screen. All the skin attributes supported by different platforms are applicable. This is a reference to an existing skin. If it is nil, the native platform skin is applied.
text [String] - Mandatory
The text to be displayed when displaying the loading screen. For example, "Searching flights...". If it is nil, no text is displayed.
position [String] - Mandatory
Indicates the position of the loading screen, whether it should occupy the entire screen or just the center of the screen. The possible values for position are : l constants.LOADING_SCREEN_POSITION_FULL_SCREEN (default) l constants.LOADING_SCREEN_POSITION_ONLY_CENTER.
Note: Currently only center and fullscreen are supported.
© 2015 by Kony, Inc. All rights reserved 102 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
isBlocked [Boolean] - Mandatory
Indicates if the UI should be blocked.
l true - no click and scroll is allowed on the UI. The Back button on the device also does not work. true is the default value.
l false - click and scroll is allowed(UI is not blocked) and back button of the device also works.
If nothing is specified, default value is used.
showProgressIndicator [Boolean] - Mandatory
Indicates if the progress indicator should be displayed.
l true - displays the progress indicator. true is the default value.
l false - does not display the progress indicator.
Note: The progress indicator is a set of animating images.
properties [Object] - Mandatory
Indicates the platform specific properties to be applied to the loading screen.
Note: You must pass this parameter as nil on all platforms except BlackBerry and iPhone platform.
The following are the key-value pairs to be passed in the table for BlackBerry:
JavaScript enableMenuKey
(boolean)
Description if true the menu key is enabled and user is able to select the menu items.
© 2015 by Kony, Inc. All rights reserved 103 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
enableBackKey
(boolean)
If true the Back button on the device is enabled and user is able to execute the default back behavior as defined by the application.
Important: These key-value pairs are applicable only on
BlackBerry platform.
The following are the key-value pairs to be passed in the table for iPhone:
JavaScript shouldShowLabelInBottom
(boolean/string) separatorHeight(number)
Description
To display the text content at the bottom or the top side of the activity indicator.
Default value is false. If string "true" is passed to this property then it will display the content at the bottom of the activity indicator.
Height between the activity indicator and text to be displayed.
Default height is 30px. Should be greater than 0.
Important: These key-value pairs are applicable only on iPhone platform.
progressIndicatorColor
(String)
Color is applied for progress indicator when it is shown. (Optional)
Note: Only "white" and "gray" colors are supported. Default is white. White and gray values are not case sensitive.
© 2015 by Kony, Inc. All rights reserved 104 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
progressIndicatorType
(Constant)
Set the type of progress indicator. The following types are provided: l constants.PROGRESS_INDICATOR_TYPE_SMALL
l constants.PROGRESS_INDICATOR_TYPE_BIG
l constants.PROGRESS__INDICATOR_TYPE_DEFAULT
(Default value)
Note: progressIndicatorType:constants.PROGRESS_
INDICATOR_TYPE_BIG with "progressIndicatorColor:GREY" is not supported in iOS platform.
The following are the key-value pairs to be passed in the table for all platforms except BlackBerry and iPhone:
JavaScript progressIndicatorColor
(String)
Description
Color is applied for progress indicator when it is shown. (Optional)
Note: All colors with RGBA (Hex code) are supported, but for
"white" and "gray" you can pass it as a string value. Color value should be similar to the value provided in the theme.
4.11.4 Return Values
None.
4.11.5 Platform Availability
Available on all platforms except Mobile Web.
© 2015 by Kony, Inc. All rights reserved 105 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.11.6 JavaScript Example
//Invoking showLoadingScreen on BlackBerry platform.
kony.application.showLoadingScreen
("loadskin","LoadingScreen",constants.
LOADING_SCREEN_POSITION_ONLY_CENTER, false,true,{enableMenuKey:true, enableBackKey:true});
//Invoking showLoadingScreen on iPhone platform.
kony.application.showLoadingScreen(null, "testf", constants.LOADING_SCREEN_POSITION_ONLY_CENTER, false, true, { shouldShowLabelInBottom: "true", separatorHeight: 200, progressIndicatorType : constants.PROGRESS_INDICATOR_TYPE_SMALL, progressIndicatorColor : "Gray"} )
//Invoking showLoadingScreen on other platform.
kony.application.showLoadingScreen
("loadskin","LoadingScreen",constants.
LOADING_SCREEN_POSITION_ONLY_CENTER, false,true,{enableMenuKey:true, enableBackKey:true, progressIndicatorColor : "ffffff77"})
4.12 kony.application.dismissLoadingScreen
This API provides you the ability to dismiss the loading screen displayed earlier. If there is no loading screen, this API has no affect.
4.12.1 Signature
JavaScript: kony.application.dismissLoadingScreen()
© 2015 by Kony, Inc. All rights reserved 106 of 848
4. Application APIs
4.12.2 Input Parameters
None
4.12.3 Return Values
None.
4.12.4 Platform Availability
Available on all platforms except Mobile Web.
4.12.5 JavaScript Example kony.application.dismissLoadingScreen();
4.13 kony.application.exit
This API terminates the application.
4.13.1 Signature
JavaScript: kony.application.exit()
4.13.2 Input Parameters
None
4.13.3 Return Values
None.
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 107 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.13.4 Platform Availability
Available on all platforms except for Server side Mobile Web and Desktop Web. SPA supports only iPhone, iPad, and Windows 8 Tablet.
4.13.5 JavaScript Example function exit()
{ try{ kony.application.exit();
} catch(Error)
{
"+Error); alert("Exception While getting exiting the application :
}
}
4.14 kony.application.openURL
This API opens the web page at the specified URL in the native browser of the mobile device.
4.14.1 Use Case
You can use this API when you want to access an external web page within the application. With this
API, you can open a web page without using a browser widget in your application.
4.14.2 Signature
JavaScript: kony.application.openURL(
)
© 2015 by Kony, Inc. All rights reserved 108 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.14.3 Input Parameters
URL [String] - Mandatory
Specifies the URL that points to the external web page
4.14.4 Return Values
None.
4.14.5 Implementation Details
When you use this API, the behavior of the application is as follows on different platforms: iPhone
Platform Behavior l
On 4.0 and above versions, the application opens the specified
URL in the native browser and the application goes into background l
On versions below 4.0, the application opens the specified URL in the native browser and the application exits l
For opening the maps application of iOS, please using following
URLs: l
For iOS 5 : http://maps.google.com/maps l
For iOS 6: http://maps.apple.com/maps
Android
BlackBerry
The application opens the specified URL in the native browser and the application goes into background
The application opens the specified URL in the native browser and the application goes into background
© 2015 by Kony, Inc. All rights reserved 109 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
Platform
Windows
Phone/Windows
Kiosk/Mango
SPA
Behavior
The application opens the specified URL in the native browser and the application exits
Symbian
Palm l
The URL opens in the browser l
The application redirects the existing browser instance to the new URL
The application opens the specified URL in the native browser and the application goes into background
The application opens the specified URL in the native browser and the application goes into background
4.14.6 Platform Availability
Available on all Rich Client platforms.
4.14.7 JavaScript Example
//The following function is for openURL API function openURL()
{
//Accessing an external web page : http://www.google.com
kony.application.openURL("http://www.google.com")
}
© 2015 by Kony, Inc. All rights reserved 110 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.15 kony.application.openMediaURL
This API launches the native media player and starts playing the media (audio or video) at the specified URL. The media server provides the appropriate media content depending upon the device
(for example, Blackberry, iPhone, etc). This API is not applicable on SPA.
4.15.1 Use Case
You can use this API when you want to access and use multimedia from an external URL or server.
4.15.2 Signature
JavaScript: kony.application.openMediaURL(
)
4.15.3 Input Parameters
URL [String] - Mandatory
Specifies the URL that points to the audio/video file
4.15.4 Return Values
None.
4.15.5 Implementation Details
This API assumes that the media is available at the specified URL. The API does not check for the availability of the media at the specified location. The responsibility lies on the developer to ensure that appropriate media is available at the referred URL.
Any errors related to the type of media or the availability of the media are handled by the native media player. The errors are not propagated back to the application.
Note: For more information on media formats, see:
© 2015 by Kony, Inc. All rights reserved 111 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l
Android: http://developer.android.com/guide/appendix/media-formats.html
You have to provide an absolute path of the video file in the URL. For example, http://www.boisestatefootball.com/sites/default/files/videos/original/01%20-%20coach%20pet e%20bio_4.mp4
or the URL should be in 'rtsp' format if it is a YouTube video.
l iPhone: Apple Documentation l
Windows Phone (7.5 and 8.0): http://msdn.microsoft.com/enus/library/windowsphone/develop/ff462087(v=vs.105).aspx
l
Windows 8 tablet: Supported File Types
4.15.6 Platform Availability
Available on all platforms except BlackBerry 10 and Windows 7 / Kiosk.
4.15.7 JavaScript Example function openMediaURL()
{
//Launching the native media player and starts playing the media
(audio or video) at the
URL:"http://www.boisestatefootball.com/sites/default/files/videos/or iginal/01%20-%20coach%20pete%20bio_4.mp4" kony.application.openMediaURL
("http://www.boisestatefootball.com/sites/default/files/videos/origi nal/01%20-%20coach%20pete%20bio_4.mp4");
}
4.16 kony.application.setApplicationBehaviors
This API enables you to specify if:
© 2015 by Kony, Inc. All rights reserved 112 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l
The pre-show and post show events are invoked if you press Back option on a mobile device.
l
The pop-up is modal (requires interaction before it can return to the parent application).
l
The app menu needs to be updated when pre-show and post show events are invoked if you press the Back option on a mobile device.
App menu has to be configured in pre-show/post show of each form, if each form has separate app menu buttons/items. But on some Kony platforms, pre-show and post show events are triggered when user navigates back using Back option and on some other platforms, those events are not triggered. If pre-show/post show event is not triggered, form cannot update its app menu. In this scenario, ideally, form must retain its app menu which is set earlier.
To ensure consistency while porting application across platforms, the setapplicationbehavior API enables you to set the default behavior of pre-show and post show events, a pop-up, and app menu.
Note: This API can only be called in post-appinit() method.
4.16.1 Signature
JavaScript: kony.application.setApplicationBehaviors(
4.16.2 Input Parameters
Objectbehaviors [Object] - Mandatory
The object includes the following key-value pairs: l invokePreshowPostShowEventsOnDeviceBack [Boolean] : Specifies if the pre-show or postshow events are triggered if the user presses the Back option on a mobile device.
l isPopupModel [Boolean] : Specifies if the pop-up is modal (requires interaction before it can return to the parent application). The value set as the property for a pop-up takes precedence over the value set dynamically.
l retainSpaceOnHide [Boolean] : Specifies if the space allocated for a widget is retained when the widget is
© 2015 by Kony, Inc. All rights reserved 113 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
made invisible. Applicable on widgets placed in a percentage container.
Important: l
Limitation in Windows channel: when retainSpaceOnHide is true and widget isVisible property is false, top, and bottom margins will not be considered for invisible widget.
l
When visibility of widget is changed and when retainSpaceOnHide is True, there must not be any change in the width of HBox or % scrollBox. Height changes to the max height of the visible child widget.
l
When retainSpaceOnHide property is made False, inconsistency among platforms is observed. If any of the widgets placed inside a container are made invisible, then some platforms will retain the space and some platforms will not retain the space. To overcome this inconsistency or to retain the space in all platforms, retainSpaceOnHide property must be configured to True. The default value of retainSpaceOnHide property is True.
l restoreformstateondeviceback [ Boolean]: Specifies whether the default behavior of form app menu state is retained when the user presses the Back option.
l hideDefaultLoadingIndicator [ Boolean]: If enabled (true), it hides the default loading indicator that appears when background operation is performed. For example, executing onClick() callback function of Button widget if a button is clicked.
Important: The hideDefaultLoadingIndicator property is available only on Android Platform and it is supported from Kony Android plug-in GA 5.0.32 onwards.
l adherePercentageStrictly [ Boolean]: By default, this parameter is set to True.
Note: SPA and Desktop Web supports only adherePercentageStrictly property.
l defaultIndicatorColor [String]: Set color for the progress indicator. An Hex code or a word can be used to set the color. The words can only be used for two colors white and grey, and these
© 2015 by Kony, Inc. All rights reserved 114 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
words are not case sensitive.
Note: The defaultIndicatorColor property is only support for Android and Windows. Default color might vary for each platform as it picks from application theme, form color or predefined color.
l hideDefaultLoadingIndicator [Boolean]: Set as True to hide the loading indicator, and set as
False to show the loading indicator.
l hideStatusBar [Boolean]: Set as True to hide the status bar, and set as False to show the status bar. Default value is True. This is an optional parameter.
Important: The hideStatusBar property is available only on Windows (8 and later versions)
Platform and it is supported in Kony Studio GA 5.6.4.11 and in GA 6.0.2.3.
l marginsIncludedInWidgetContainerWeight [Boolean]: Set to True to apply margin calculations.
Margins are calculated based on width of the parent box.
Note: The margin change is applicable only for percentage boxes.
l skinImageScaleMode [Constant]: Available on Windows Phone 8 or 8.1, Windows 8, and
Desktop Kiosk o skinImageScaleMode [Constant] – Optional o skinImageScaleMode accepts the following constants: o constants.SKIN_IMAGE_SCALE_MODE_DEFAULT
o constants.SKIN_IMAGE_SCALE_MODE_NONE
o constants.SKIN_IMAGE_SCALE_MODE_FILL
o constants.SKIN_IMAGE_SCALE_MODE_UNIFORM
© 2015 by Kony, Inc. All rights reserved 115 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
o constants.SKIN_IMAGE_SCALE_MODE_UNIRFORMTOFILL
l
SKIN_IMAGE_SCALE_MODE_DEFAULT: This mode renders the
Images provided to the skin according to the existing, default behavior.
l
SKIN_IMAGE_SCALE_MODE_NONE: This mode does not scale the Images provided to the skin. In case the image is larger than the control, the widget expands to the size of the image, else, the image occupies it’s actual height within the control.
l
SKIN_IMAGE_SCALE_MODE_FILL: The image is scaled to fill the size of the widget in this mode. It’s aspect ratio is not preserved.
© 2015 by Kony, Inc. All rights reserved 116 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l
SKIN_IMAGE_SCALE_MODE_UNIFORM: The image is scaled to fill the size of the widget while ensuring it’s aspect ratio is preserved.
l
SKIN_IMAGE_SCALE_MODE_UNIFORMTOFILL: The image is resized to fill the widget dimensions while preserving the native aspect ratio. If the aspect ratio of the widget differs from that of the image, the image is clipped to fit in the destination.
© 2015 by Kony, Inc. All rights reserved 117 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
Example: kony.application.setApplicationBehavior
s({skinImageScaleMode:constants.SKIN_IMAGE_
SCALE_MODE_DEFAULT}); l
Usage Guidelines or Restrictions or Examples: In Kony Platform, height cannot be fixed for most of the widgets. Hence, for the widgets, for which the height is not fixed, the image skin will expand and the widget’s size will grow for the modes: FILL, UNIFORM and
UNIFORMTOFILL. This flag is usually set in Pre-AppInit or Post-
Appinit before the widgets are rendered. In the scenario where the flag is modified after any of the widgets are rendered, there will be no change in the widgets which have already been rendered. The change will be reflected by the widgets which have not been rendered yet.
l isScrollEventsAsync [Boolean]: All scroll events are executed asynchronously. If visual changes and calculations are done based on scroll properties and events (such as content scroll offset). It is recommended to set isScrollEventsAsync to False and execute the scroll events synchronously.
o
Default Value: True o
Platform Availability: Windows Phone 8 and 8.1
© 2015 by Kony, Inc. All rights reserved 118 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l isLowLevelEventsAsync [Boolean]:
onTouchStart
,
onTouchMove
,
onTouchEnd
, and
onTouchCancel
are classified as low-level events. If these events are required to be executed synchronously, then isLowLevelEventsAsync must be set to False.
o
Default Value: True o Platform Availability: Windows Phone 8 and 8.1
l enableRedrawRegions [Boolean]: All gesture events are executed asynchronously. By setting
isGestureEventsAsync
to False, the gesture events are executed synchronously.
o
Default Value: True o Platform Availability: Windows Phone 8 and 8.1
l skipEscapeHTML [Boolean]: Set as true to allow HTML tags in label widget and for backward compatibility.
Following are the Windows 7 specific properties available in setApplicationBehaviour API.
Note: All the properties must be passed as a key value pairs under Windows 7 Key.
l backOnEsc: If set to True, allows the user to go back to previous form by pressing Escape key. If the user is on the first form, the operation is ignored. Default value is False.
Note: If you are using onDeviceBack property on the form, the app will override the backOnEsc property and gives priority to onDeviceBack property.
l minWidth: Allows to set minimum width of the main window.
l maxWidth: Allows to set maximum width of the main window.
l minHeight: Allows to set minimum height of the main window.
l maxHeight: Allows to set maximum height of the main window.
© 2015 by Kony, Inc. All rights reserved 119 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l popupAsDialog: If this property is set to True, all the pop-ups will be displayed outside the main window. If set to False, pop-up displays embedded in main window. Default value is False.
l saveState: If set to true, location and size of the main window will be saved between application session. Default is false.
Note: If the setApplicationBehaviour API is called multiple times, latest settings are considered and all old settings are overridden.
Following are the BlackBerry 10 specific properties available in setApplicationBehaviour API.
l contextMenuHandler [Boolean]: This enables or disables the appearance of Menu (with action items) from right side when you do a long press on the form. Set as true to enable this property and set as false to disable. By default, the value is true.
l defaultPaddingEnabled [Boolean]: This enables or disables the default padding for the button.
Set as true to enable this property and set as false to disable. By default, the value is true.
Note: The contextMenuHandler and defaultPaddingEnabled properties are available only on BlackBerry 10 platform and are supported from Kony Studio 5.6 onwards.
4.16.3 Return Values
None
4.16.4 Platform Availability
Available on all platforms
4.16.5 JavaScript Example
//The Application must to call kony.application.setApplicationBehaviors(appTable)
© 2015 by Kony, Inc. All rights reserved 120 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
//in post-appinit() methods.
function setApplicationBehaviors()
{
//Controlling the behaviours by setting invokePreshowPostShow
//EventsOnDeviceBack as true,isPopupModel as true,and retainSpaceOnHide as true.
kony.application.setApplicationBehaviors
({invokePreshowPostShowEventsOnDeviceBack:true, isPopupModel:true, retainSpaceOnHide:true,
"hideDefaultLoadingIndicator":true});
} var obj =
{ windows7:
{ backOnEsc:true, minWidth:300, maxWidth:1000, minHeight:400, maxHeight:800, popupAsDialog:true, saveState:true,
}
} kony.application.setApplicationBehaviors(obj);
© 2015 by Kony, Inc. All rights reserved 121 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
var inputParamTable = {}; inputParamTable["isScrollEventsAsync"] = false; inputParamTable["isLowLevelEventsAsync"] = false; inputParamTable["isGestureEventsAsync"] = false; kony.application.setApplicationBehaviors(inputParamTable);
4.17 kony.application.setZoomedOutView
You can design a user interface to be displayed to the end user when you zoom out of an application.
This API enables you to set a form to be shown to the user when a zoom out gesture is performed.
This API is introduced to support the Semantic Zoom feature introduced with Windows 8. For more information about Semantic zoom,zoomed in, and zoomed out views, refer http://msdn.microsoft.com/en-us/library/windows/apps/hh465319.aspx
.
4.17.1 Signature
JavaScript: kony.application.setZoomedOutView(
)
© 2015 by Kony, Inc. All rights reserved 122 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.17.2 Input Parameters formid [Widget Reference] - Mandatory
Specifies the id of the form to be displayed when the user zooms out of the application.
4.17.3 Return Values
None.
4.17.4 Platform Availability
Windows 8
4.17.5 JavaScript Example
//Zooming out of a an application and displaying a form with an id myForm1 on zoomout function zoomout()
{ kony.application.setZoomedOutView(myForm1);
}
4.18 kony.application.disableZoomedOutView
This API enables you to disable a zoomed out view set for an application using the previous API.
4.18.1 Signature
JavaScript: kony.application.disableZoomedOutView()
4.18.2 Input Parameters
None
© 2015 by Kony, Inc. All rights reserved 123 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.18.3 Return Values
None.
4.18.4 Platform Availability
Windows 8
4.18.5 JavaScript Example
//Disabling zoomout on an application function zoomout()
{ kony.application.disableZoomedOutView();
}
4.19 kony.application.zoomIn
This API enables you to zoom in on an application programmatically. If the application is already zoomed in, this API has no effect.
4.19.1 UseCase
Suppose your application is in a zoomed out state where the contacts associated with that letter is displayed. You can use this API to view all the contacts alphabeticallyand present the data using the letters of the alphabet.
4.19.2 Signature
JavaScript: kony.application.zoomIn()
© 2015 by Kony, Inc. All rights reserved 124 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.19.3 Input Parameters
None
4.19.4 Return Values
None.
4.19.5 Platform Availability
Windows 8
4.19.6 JavaScript Example
//Enabling zoomin on an application function zoomIn()
{ kony.application.zoomIn();
}
4.20 kony.application.setApplicationLayout
This API specifies if the application must have a layout from "left to right" or "right to left".
4.20.1 UseCase
To support Arabic kind of languages, all the widgets on a form must be layout from right to left. This
API impacts only horizontal layout.
4.20.2 Signature
JavaScript: kony.application.setApplicationLayout(
© 2015 by Kony, Inc. All rights reserved 125 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.20.3 Input Parameters layoutDirection [Constant] - Mandatory
Specifies the layout direction for the content and the widgets of an application.
l constants.APPLICATION_LAYOUT_RIGHT2LEFT
l constants.APPLICATION_LAYOUT_LEFT2RIGHT
4.20.4 Return Values
None
4.20.5 Implementation Details
There is no direct API available to change the application layout to support both "Left2Right" and
"Right2Left" languages. App developers have to spend huge amount of time in redesigning the UI for both locales, setting the margins/paddings and in setting "contentAlignment" for all widgets on all forms. This API is simple solution to change the application layout based on locale.
This API can be called in appservice/preappinit/postappinit after checking the current locale or this should be called after the locale is changed successfully with "setCurrentLocaleAsync()".
4.20.6 Exceptions
An error is thrown if input is invalid or does not follow the expected structure.
102 - Invalid input error
101 - Insufficient arguments passed
4.20.7 Platform Availability
Available on Windows 8, Windows Phone 8, and Windows Phone 7.5 (Mango).
© 2015 by Kony, Inc. All rights reserved 126 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.20.8 JavaScript Example
If an application supports English and Arabic languages, app developer can invoke below snippet anywhere in appservice or preappinit or postappinit.
function setApplicationLayoutBasedOnLocale()
{ if(kony.i18n.getCurrentLocale() == "en_US")
{ kony.application.setApplicationLayout(constants.APPLICATION_LAYOUT_
LEFT2RIGHT);
}else
{
}
} kony.application.setApplicationLayout(constants.APPLICATION_LAYOUT_
RIGHT2LEFT);
4.21 kony.application.setDefaultTextboxPadding
This API customizes the default paddings applied for a Textbox. Generally, default padding is appended to padding applied through layout configurations of the widget.
4.21.1 Signature
JavaScript: kony.application.setDefaultTextboxPadding(
)
4.21.2 Input Parameters bool [Boolean] - Mandatory
Indicates if the default padding is set.
© 2015 by Kony, Inc. All rights reserved 127 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l
True - Default padding is applied to textbox widgets.
l
False - No default padding is applied to textbox widgets.
4.21.3 Return Values
None
4.21.4 Platform Availability
Available on iPhone and iPad.
4.21.5 JavaScript Example kony.application.setDefaultTextboxPadding(false);
4.22 kony.application.setCheckBoxSelectionImageAlignment
This API is used to set the alignment of the checkBox selection image.
4.22.1 Signature
JavaScript: kony.application.setCheckBoxSelectionImageAlignment(
)
4.22.2 Input Parameters
SelectionImageAlignment [String] - Mandatory
One of the following string can be provided: l constants.CHECKBOX_SELECTION_IMAGE_ALIGNMENT_LEFT - Image will be aligned to left.
l constants.CHECKBOX_SELECTION_IMAGE_ALIGNMENT_RIGHT - Image will be aligned to right.
© 2015 by Kony, Inc. All rights reserved 128 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.22.3 Return Values
None
4.22.4 Exceptions
If input is invalid, an error is displayed.
4.22.5 Platform Availability
Available on iPhone and iPad.
4.22.6 JavaScript Example kony.application.setCheckBoxSelectionImageAlignment
(constants.CHECKBOX_SELECTION_IMAGE_ALIGNMENT_RIGHT);
4.23 kony.application.setRespectImageSizeForImageWidgetAlignment
This API sets the ImageWidget width to minimum or maximum according to available width or image width in absence of reference width. If ImageWidget is smaller than the available width, it is aligned using the widget alignment rules.
4.23.1 Signature
JavaScript: kony.application.setRespectImageSizeForImageWidgetAlignment(
4.23.2 Input Parameters bool [Boolean] - Mandatory
Indicates if the default padding is set.
© 2015 by Kony, Inc. All rights reserved 129 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
l
True - Sets the ImageWidget width to minimum.
l
False - Sets the ImageWidget width to maximum.
4.23.3 Return Values
None
4.23.4 Implementation Details
If this API is not used, the Image widget width is always the given width and image is center aligned.
4.23.5 Platform Availability
Available on iPhone and iPad.
4.23.6 JavaScript Example kony.application. setRespectImageSizeForImageWidgetAlignment (true);
4.24 kony.application.registerOnKeyPress(values)
This API allows the user to hook any closure with key press event. It expects an object with key-value pair. This API is exposed for Windows 7 platform.
4.24.1 JavaScript Example function keyPress(keycode)
{ kony.print("DONE!!!" + keycode)
} function callRegisterOnKeyPress()
© 2015 by Kony, Inc. All rights reserved 130 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
{ var values = {
"Ctrl+C": keyPress,
"Ctrl+X": keyPress,
"Ctrl+V": keyPress,
"Esc": keyPress
}; kony.application.registerOnKeyPress(values);
}
/*
4.25 kony.application.beginBackgroundTask
In some scenarios apps are launched in the background to perform some long running task. A typical example, could be when a watch app requests its parent app (phone app) for some information, the phone app is launched in the background. If the phone app needs to run a long running task in order to serve the requirement of the watch app, it is recommended to start a background task. This API ensures iOS does not suspend the phone app when running in the background that take too much time or resources for execution.
This API is used when you want to run a long running or the asynchronous task in the background of the phone app. When the long running task is completed, you must end the background task using the
API kony.application.endBackgroundTask.
4.25.1 Signature
JavaScript: kony.application.beginBackgroundTask(taskID, callback)
4.25.2 Input Parameters taskID [String] - Mandatory
Specifies the unique identifier for the task.
© 2015 by Kony, Inc. All rights reserved 131 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
callback [function] - Optional
Specifies the callback that gets executed in the background before iOS suspends the app. You can use this callback to save information or clean up resources before your app gets suspended.
4.25.3 Return Values
This API returns taskID as a number that is used as an input for kony.application.endBackgroundTask
API.
4.25.4 Platform Availability
Available on iPhone and iPad.
4.25.5 JavaScript Example function ExpirationHandlercallback(){
//your logic to clear resources or save data.
} function jsfunction(userInfo, replyObj)
{ var taskID = kony.application.beginBackgroundTask("TaskName",
ExpirationHandlercallback);
//Long running task.
kony.application.endbackgroundTask(taskID);
}
© 2015 by Kony, Inc. All rights reserved 132 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.26 kony.application.endBackgroundTask
This API is invoked when you are done with an execution of long running tasks in the background. The return value of the API kony.application.beginBackgroundTask is used as the input parameter for this API.
4.26.1 Input Parameters taskID [Number] - Mandatory
Specifies the identifier returned by the kony.application.beginBackgroundTask API.
4.26.2 Return Values
None
4.26.3 Platform Availability
Available on iPhone and iPad.
4.26.4 JavaScript Example function ExpirationHandlercallback(){
//your logic to clear resources or save data.
} function jsfunction(userInfo, replyObj)
{ var taskID = kony.application.beginBackgroundTask("TaskName",
ExpirationHandlercallback);
© 2015 by Kony, Inc. All rights reserved 133 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
//Long running task.
kony.application.endbackgroundTask(taskID);
}
4.27 kony.application.getApplicationState
iOS prohibits UI updates when the app is running in the background. Using this API you can check whether the app is running in the background or not to make UI updates. The possible application states are active, inactive, or background.
4.27.1 Signature
JavaScript: kony.application.getApplicationState()
4.27.2 Input Parameters
None
4.27.3 Return Values
This API returns the following constant values: l
APPLICATION_STATE_ACTIVE l
APPLICATION_STATE_INACTIVE l
APPLICATION_STATE_BACKGROUND
4.27.4 Platform Availability
Available on iPhone and iPad.
© 2015 by Kony, Inc. All rights reserved 134 of 848
4. Application APIs Kony Studio API Developer's Guide
Version 5.0
4.27.5 JavaScript Example
//Sample code to get the application state function util() { var appState = kony.application.getApplicationState(); if (appState = constants.APPLICATION_STATE_BACKGROUND) { kony.print(appState);
}
}
© 2015 by Kony, Inc. All rights reserved 135 of 848
Kony Studio API Developer's Guide
Version 5.0
4.28 Application Settings APIs
This feature allows the developer to enable application level settings so that the end users of an application can modify configurations and change the application behavior. This property is currently only applicable on iPhone platform. For more information on Application settings refer Kony Studio
User's Guide.
For instance developers can choose to set the following for an application: l define views for widgets.
l to configure the themes.
Using the application setting APIs, you can read and write the values the end user has set for an application.
4.28.1 kony.application.settings.read
This API allows you to read the configurations associated with a specified key. This is an asynchronous call.
4.28.1.1 Use Case
This API must be used in case you want to read the user-defined values such as preferred locations.
4.28.1.2 Signature
JavaScript : kony.application.settings.read (
onsuccesscallback , onfailureback
)
4.28.1.3 Input Parameters key[String] - Mandatory
Specifies the key for which you want to read the settings. The settings are read from the application settings file that is bundled along with the application binary.
© 2015 by Kony, Inc. All rights reserved 136 of 848
Kony Studio API Developer's Guide
Version 5.0
onsuccesscallback [Function] - Mandatory
Specifies the callback function that must be executed when a key-value is read successfully. The callback function has the following signature: onsuccess(key,value) - Mandatory
Value can be boolean, string, double, or an object.
An object is returned only when Display option is multi-select.
onfailurecallback [Function] - Mandatory
Specifies the callback function that must be executed when there is an error in fetching the app setting. This callback function receives the error code and the error message. The callback function has the following signature: onfailure(errorcode,errormessage)
4.28.1.4 Return Values
This API asynchronously returns the settings for a key by invoking onsuccess callback and does not return any values directly.
4.28.1.5 Rules and Restrictions
This API is applicable only when the application settings are set.
4.28.1.6 Platform Availability
Available only on iPhone
4.28.1.7 JavaScript Example
//The below four functions are callback functions for kony.application.
settings.read API function onsuccesscallback(key,value)
© 2015 by Kony, Inc. All rights reserved 137 of 848
Kony Studio API Developer's Guide
Version 5.0
{
//Write Your Logic here
} function onfailureback(errorcode,errormessage)
{ alert("err is :"+errormessage);
} function onsuccesscallbackR(key,value)
{
//Write Your Logic here
} function onfailurebackR(errorcode,errormessage)
{ alert("Err is :"+errormessage);
} function read()
{
//Read the settings kony.application.settings.read
("key1", onsuccesscallback, onfailureback) kony.application.settings.read
("key2", onsuccesscallbackR, onfailurebackR)
}
4.28.2 kony.application.settings.write
This API allows you to write the values to the specified key with the given value. New keys cannot be introduced with this API. When the value for the specified key is modified using this API, the changes should reflect in the application settings at the device level. This is an asynchronous call.
© 2015 by Kony, Inc. All rights reserved 138 of 848
Kony Studio API Developer's Guide
Version 5.0
4.28.2.1 Signature
JavaScript:
kony.application.settings.write ( key
,
value, onsuccesscallback , onfailurecallback )
4.28.2.2 Input Parameters key[String] - Mandatory
Specifies the unique key. The key that you specify must exist. You cannot introduce a new key.
value [String] - Mandatory
Specifies the value to be set for a key. The existing value would be replaced with the new value.
Value can be boolean, string, double, or an object.
An object is returned only when "Display option" is multi-select.
onsuccesscallback [Function] - Mandatory
Specifies the callback function that must be executed when the new value is updated against the specified key. The callback function has the following signature: onsuccess(key,value)
Value can be boolean, string, double, or an object.
An object is returned only when " Display option" is multi-select.
onfailurecallback [Function] - Mandatory
Specifies the callback function that must be executed when there is an error in updating the configuration. This callback function receives the error code and the error message. The callback function has the following signature: onfailures(errorcode,errormessage)
4.28.2.3 Return Values
This API asynchronously returns the values by invoking on success and does not return any values
© 2015 by Kony, Inc. All rights reserved 139 of 848
Kony Studio API Developer's Guide
Version 5.0
directly.
4.28.2.4 Rules and Restrictions
This API is applicable only when the application settings are set.
4.28.2.5 Platform Availability
Available only on iPhone
4.28.2.6 JavaScript Example
//The below four functions are callback functions for kony.application.
settings.write API function onsuccesscallbackw(key,value)
{
//Write Your Logic here
} function onfailurebackw(errorcode,errormessage)
{ alert("Error is :"+errormessage);
} function onsuccesscallbackWrite(key,value)
{
//Write Your Logic here
} function onfailurebackWrite(errorcode,errormessage)
{ alert("Error is :"+errormessage);
} function write()
© 2015 by Kony, Inc. All rights reserved 140 of 848
Kony Studio API Developer's Guide
Version 5.0
{
//Write the settings kony.application.settings.write("key1","Message1", onsuccesscallbackw, onfailurebackw); kony.application.settings.write("key2","Message2", onsuccesscallbackWrite, onfailurebackWrite);
}
© 2015 by Kony, Inc. All rights reserved 141 of 848
5. Accelerometer APIs Kony Studio API Developer's Guide
Version 5.0
5. Accelerometer APIs
The Accelerometer APIs allow you to capture the device motion acceleration in X, Y, Z directions and also provide out of the box mechanisms to register for shake gestures event.
The following diagram shows the standard co-ordinate system that is used in indicating the X, Y, Z values:
The following table describes the co-ordinate system to be used for the accelerometer APIs:
Axis
X
Description
Float value indicating the magnitude of acceleration/ force along the X-Axis
Value positive
Direction
Towards the right when the device is facing you negative Towards the left when the device is facing you
© 2015 by Kony, Inc. All rights reserved 142 of 848
5. Accelerometer APIs Kony Studio API Developer's Guide
Version 5.0
Y
Z
Float value indicating the magnitude of acceleration/force along the Y-Axis
Float value indicating the magnitude of acceleration/force along the Z-Axis positive Towards the top of the top of the device
Towards the bottom of the device negative positive negative
The axis coming out from the device screen (towards you) when the device is facing you
The axis coming out from the device back (away from you) when the device is facing you
Important: X, Y, Z are measured in terms of G, where G denotes the standard gravitational force.
G = 9.80665 m/s
2
(meters per seconds square). For example, if x=1, its actual value is 1G, i.e.,
9.80665 m/s
2
.
When a device is laying still with its back on a horizontal surface, each acceleration event has approximately the following values: l
X = 0 l
Y = 0 l
Z = -1
X, Y, Z can also have negative values based on the direction in which the device is positioned.
Note: The accelerometer APIs are applicable only when
os.platform
().hasaccelerometer
returns true.
This chapter explains the following APIs: l
kony.accelerometer.retrieveCurrentAcceleration
l
kony.accelerometer.startMonitoringAcceleration
© 2015 by Kony, Inc. All rights reserved 143 of 848
5. Accelerometer APIs Kony Studio API Developer's Guide
Version 5.0
l
kony.accelerometer.stopMonitoringAcceleration
l
kony.accelerometer.registerAccelerationEvents
l
kony.accelerometer.unregisterAccelerationEvents
You can view a video on using Accelerometer API at: http://docs.kony.com/video_ tutorials/default.htm#Accelerometer.htm%3FTocPath%3D_____5 .
5.1 kony.accelerometer.retrieveCurrentAcceleration
This API allows you to retrieve the current device acceleration. The specified callback functions are invoked asynchronously and this API returns the value immediately without waiting for actual retrieval of the device acceleration data. This is an asynchronous API.
5.1.1 Signature
JavaScript: kony.accelerometer.retrieveCurrentAcceleration (
5.1.2 Input Parameters onSuccessCallback [Function] - Mandatory
Specifies the callback function that must be executed when retrieving the current device acceleration is successful.
The callback function has the following signature: onSuccessCallback(accelerometerdata) l accelerometerdata [Table] - This table has the following key-value pairs: o x [Number] - contains the x co-ordinate as a floating point value o y [Number] - contains the y co-ordinate as a floating point value o z [Number] - contains the z co-ordinate as a floating point value
© 2015 by Kony, Inc. All rights reserved 144 of 848
5. Accelerometer APIs Kony Studio API Developer's Guide
Version 5.0
o timestamp [Number] - specifies the number of milli seconds elapsed since the start of the
Unix Epoch. The standard Unix Epoch is 00:00:00 UTC on 1 January 1970. The timestamp does not reflect the frequency at which the device can retrieve the accelerometer data, because the device capability (in terms of frequency) can vary from one platform to the other.
onFailureCallback [Function] - Mandatory
Specifies the callback function that must be executed when the API call fails in retrieving the current device location. This callback function does not have any input parameters.
You can define the logic that must be executed in this function.
5.1.3 Return Values
None.
5.1.4 Platform Availability
Available on all platforms except BlackBerry 10, SPA, Desktop Web, Windows 7/Kiosk, and Mobile
Web.
5.1.5 JavaScript Example
//retrieve current acceleration request
// onsuccesscallback
// This method accepts an 'accelerometerdata' object, which contains the current device acceleration values function onsuccesscallback(accelerometerdata)
{ kony.print("X: " + accelerometerdata.x +"Y: " + accelerometerdata.y
© 2015 by Kony, Inc. All rights reserved 145 of 848
5. Accelerometer APIs Kony Studio API Developer's Guide
Version 5.0
+"Z: " + accelerometerdata.z +"Timestamp: " + accelerometerdata.timestamp );
}
// onfailurecallback function onfailurecallback(error)
{ kony.print("code: " + error.code +"message: " + error.message);
} function retrieveCurrentAcceleration()
{
// Current acceleration request.
kony.accelerometer.retrieveCurrentAcceleration (onsuccesscallback, onfailurecallback);
}
5.2 kony.accelerometer.startMonitoringAcceleration
This API allows you to start monitoring the device acceleration or motion. When there is a change in the device acceleration values when the device moves, the callback functions are invoked. The callback functions are invoked asynchronously and this API returns immediately without waiting for the device initialization for accelerometer. This is an asynchronous API.
5.2.1 Signature
JavaScript : kony.accelerometer.startMonitoringAcceleration
(
,
© 2015 by Kony, Inc. All rights reserved 146 of 848
5. Accelerometer APIs Kony Studio API Developer's Guide
Version 5.0
5.2.2 Input Parameters onSuccessCallback [Function] - Mandatory
Specifies the callback function that must be executed when monitoring the device acceleration is successful.
The callback function has the following signature: onSuccessCallback(accelerometerdata) l accelerometerdata [Table] - This table has the following key-value pairs: o x [Number] - contains the x co-ordinate as a floating point value o y [Number] - contains the y co-ordinate as a floating point value o z [Number] - contains the z co-ordinate as a floating point value o timestamp [Number] - specifies the number of milli seconds elapsed since the start of the
Unix Epoch. The standard Unix Epoch is 00:00:00 UTC on 1 January 1970. The timestamp does not reflect the frequency at which the device can retrieve the accelerometer data, because the device capability (in terms of frequency) can vary from one platform to the other.
onFailureCallback [Function] - Mandatory
Specifies the callback function that must be executed when the API call fails. This callback function does not have any input parameters.
You can define the logic that must be executed in this function.
configData [Object] - Mandatory
Specifies the configuration parameters for the monitoring operation. This table has the following key-value pairs: l frequency [Number] - Specifies the time interval in which accelerometer data needs to be retrieved. The frequency is specified in milli seconds. For example, if
© 2015 by Kony, Inc. All rights reserved 147 of 848
5. Accelerometer APIs Kony Studio API Developer's Guide
Version 5.0
the frequency is 2 milli seconds, the accelerometer data is retrieved after every 2 milli seconds.
The default value of frequency must be "200" milliseconds minimum. Any negative value specified in the frequency reverts to the default value i.e., 200ms.
l onchange [Boolean] - If this value is set to true, the number set in frequency is not respected and the onsucesscallback event is invoked whenever the device is in motion. If this value is set to false, the onsuccesscallback event is invoked in the time interval specified in the frequency parameter is used. The Default value for onchange is false.
Note: If you set onchange as false, it is necessary to specify a frequency value or the onsuccesscallback function will never be invoked.
5.2.3 Return Values
None.
5.2.4 Platform Availability
Available on all platforms except BlackBerry 10, SPA, Desktop Web, Windows 7/Kiosk, and Mobile
Web.
5.2.5 JavaScript Example
//Start monitoring request
// onsuccesscallback
// This method accepts an 'accelerometerdata' object, which containsthe current device acceleration values
© 2015 by Kony, Inc. All rights reserved 148 of 848
5. Accelerometer APIs Kony Studio API Developer's Guide
Version 5.0
function onsuccesscallback(accelerometerdata)
{ kony.print("X: " +accelerometerdata.x +"Y: " +accelerometerdata.y
+"Z:
" +accelerometerdata.z +"Timestamp: " +accelerometerdata.timestamp
);
}
//onfailure callback function onfailurecallback(error)
{ kony.print("code: " + error.code +"message: " + error.message);
} function startMonitoringAcceleration()
{
// Start monitor acceleration request.
kony.accelerometer.startMonitoringAcceleration(onsuccesscallback, onfailurecallback,{frequency:10, onchange:false});
}
© 2015 by Kony, Inc. All rights reserved 149 of 848
5. Accelerometer APIs Kony Studio API Developer's Guide
Version 5.0
5.3 kony.accelerometer.stopMonitoringAcceleration
This API allows you to stop the device monitoring activity if it is active. You can start monitoring the device motion using accelerometer.
startmonitoringacceleration API.
5.3.1 Signature
JavaScript: kony.accelerometer.stopMonitoringAcceleration()
5.3.2 Input Parameters
None.
5.3.3 Return Values
None
5.3.4 Platform Availability
Available on all platforms except BlackBerry 10, SPA, Desktop Web, Windows 7/Kiosk, and Mobile
Web.
5.3.5 JavaScript Example function stopMonitoringAcceleration()
{
//stop the device monitoring activity if it is active kony.accelerometer.stopMonitoringAcceleration();
}
© 2015 by Kony, Inc. All rights reserved 150 of 848
Kony Studio API Developer's Guide
Version 5.0
5.4 Accelerometer Events
A developer can register and perform an appropriate action when a shake event occurs.
The shake event is generated by the platform.
Note: Currently, shake is the only event that is supported.
5.4.1 kony.accelerometer.registerAccelerationEvents
This API allows you to register for the acceleration events such as 'shake'. This event is triggered only at the end of the shake event indicating that device motion has occurred. The precision with which a shake event can be recognized may vary per platform and depends on the device capability. This is an asynchronous API.
5.4.1.1 Signature
JavaScript: kony.accelerometer.registerAccelerationEvents(
5.4.1.2 Input Parameters events [Object] - Mandatory
Specifies a hash table with the type of events. This table has the following key-value pairs: l shake [Function] - Specifies a callback function with no arguments.
For example, {"shake":onshake} where function onshake ()
// write your logic here end;
5.4.1.3 Return Values
None.
© 2015 by Kony, Inc. All rights reserved 151 of 848
Kony Studio API Developer's Guide
Version 5.0
5.4.1.4 Platform Availability
Available on all platforms except BlackBerry 10, SPA, Desktop Web, Windows 7/Kiosk, and Mobile
Web.
5.4.1.5 JavaScript Example
//Defining shake function function onshake()
{ kony.print("Shake called");
} function registerAccelerationEvents()
{
//register acceleration events
//Defining the event object var events = {shake:onshake};
//Registering Shake event kony.accelerometer.registerAccelerationEvents(events);
}
5.4.2 kony.accelerometer.unregisterAccelerationEvents
This API allows you to de-register for the specified acceleration event types. This is an asynchronous
API.
© 2015 by Kony, Inc. All rights reserved 152 of 848
Kony Studio API Developer's Guide
Version 5.0
5.4.2.1 Signature
JavaScript : kony.accelerometer.unregisterAccelerationEvents(
5.4.2.2 Input Parameters
JavaScript: eventTypes [Array] - Mandatory
5.4.2.3 Return Values
None.
5.4.2.4 Platform Availability
Available on all platforms except BlackBerry 10, SPA, Desktop Web, Windows 7/Kiosk, and Mobile
Web.
5.4.2.5 JavaScript Example function unregisteraccelerationevents()
{
//stop acceleration request kony.accelerometer.unregisteraccelerationevents({"shake"});
}
© 2015 by Kony, Inc. All rights reserved 153 of 848
6. Alert API Kony Studio API Developer's Guide
Version 5.0
6. Alert API
This chapter explains non GUI APIs that are part of the kony.ui namespace.
6.1 kony.ui.Alert
This API provides you the ability to add alerts in the application. The alerts are of the following types: l information - an informative message is displayed on the screen. This message can be in turn a warning or a success message.
l confirmation - a confirmation message with Yes and No options is displayed on the screen.
l error - an error message is displayed on the screen.
All the alerts are modal in nature, i.e., the user cannot proceed with other UI operations unless the alert is dismissed.
6.1.1 Signature
JavaScript
,
6.1.2 JavaScript Parameters basicConfig [Object] - Mandatory basicConfig is an object with the following configuration properties: l message [String] - Mandatory: The message to be shown when an alert is thrown.
l alertType [Number] - Mandatory: Denotes the type of the alert. The possible values are as follows: o
ALERT_TYPE_CONFIRMATION o
ALERT_TYPE_ERROR
© 2015 by Kony, Inc. All rights reserved 154 of 848
6. Alert API Kony Studio API Developer's Guide
Version 5.0
o
ALERT_TYPE_INFO l alertTitle [String] - Optional: Title of the alert.
l yesLabel [String] - Optional: Text to be displayed for the Yes label. If the text for the Yes label is not provided, individual platforms display default values.
l noLabel [String] - Optional: Text to be displayed for the No label. If the text for the No label is not provided, individual platforms display default values.
l alertIcon [String] - Optional: Icon to be displayed to visually indicate the type of alert like - Info,
Error, Confirmation. This parameter is not supported on iPhone.
l alertHandler [Read / Write Event] - Mandatory: JavaScript function that should get called when alert is dismissed either through "yes" label button or through "no" label button.
pspConfig [Object] - Mandatory pspConfig is an object with platform specific configuration properties.
l ondeviceback [Write Event] - Optional: JavaScript function that should get called when alert is open and the device back button is pressed.
Note: Supported on Windows Phone 8, Windows Phone 7.5 (Mango) channels and not supported on Windows Kiosk and Windows 8 channels.
{
} var pspConf = {ondeviceback:func1}; var confirmationAlert = kony.ui.Alert(basicConf, pspConf); function func1() kony.print("Example function on device back");
© 2015 by Kony, Inc. All rights reserved 155 of 848
6. Alert API Kony Studio API Developer's Guide
Version 5.0
Note: The configuration properties should be passed only in the respective configuration objects otherwise they are ignored.
l contentAlignment: Used to align content of an alert. Following are the values of this property: o contants.ALERT_CONTENT_ALIGN_LEFT // default o constants.ALERT_CONTENT_ALIGN_CENTER
o constants.ALERT_CONTENT_ALIGN_RIGHT
l iconPosition: It is used to align and alert title icon. Following are the values of this property: o constants.ALERT_ICON_POSITION_LEFT // default o constants.ALERT_ICON_POSITION_RIGHT
Note: Click
to view a JavaScript example to create an alert using
contentAlignment
and
iconPostion
parameters.
6.1.3 Return Values
None.
6.1.4 API Usage
Invoking this API multiple times in the same action sequence leads to an erroneous behavior.
This API should be invoked at the end of a function as a best practice.
6.1.5 Implementation Details
The following are the behavioral aspects of alerts on various platforms:
© 2015 by Kony, Inc. All rights reserved 156 of 848
6. Alert API Kony Studio API Developer's Guide
Version 5.0
RichClient
In all native implementations alert is non blocking, i.e. the execution of any logic defined after the alert definition continues without the alert confirmation.
Important: Alert images are not supported on Windows 8 tablet.
Android
Android platform supports display of multiple alerts each time the kony.ui.Alert API is invoked. On device back, the alert gets dismissed and also the alert handler is raised.
For CONFIRMATION type alert, the alert callback is invoked with cancel flag. For example, false
Boolean argument.
For INFO & ERROR type alert, the alert callback is invoked with true argument.
iPhone iPhone does not support displaying image icons based on the alert types: info,confirmation, error.
"\n" as a newline character in the alert messages supported for iPhone Platform
Mobile Web/SPA/Desktop Web l
For advanced Mobile Web devices like iPhone, Android, and Palm Pre, alerts are displayed as popups. For basic devices, the alerts are displayed in a new page.
l
For all platforms you cannot customize alert icons/yes or no labels/ look and feel.
l
Titles of the alerts are provided by the browser and you cannot modify them. The alert title attribute does not apply for Mobile Web. Usually, the title on the alert will be the IP address or the domain name of the application.
l
Confirmation alerts in the basic devices will be displayed in another form.
l
If the alert message is nil, alert is not displayed.
© 2015 by Kony, Inc. All rights reserved 157 of 848
6. Alert API Kony Studio API Developer's Guide
Version 5.0
l
In case of all platforms, the execution of the logic defined after alert is blocked until the user clicks "yes" or "no".
6.1.6 Important Considerations
For JavaScript conversion, an alert has to be created using another variant constructor,i.e an Indexed argument constructor.
kony.ui.Alert(message, alertHandler, alertType, yesLabel, noLabel, alertTitle, pspConf).
6.1.7 Platform Availability
Available on all platforms.
Limitation in BlackBerry 10
Native dialog alert does not support icon.
6.1.8 JavaScript Example
//Defining basicConf parameter for alert var basicConf = {message: "This is an info alert",alertType: constants.
ALERT_TYPE_INFO,alertTitle: "infoWithoutImage",yesLabel:"yes", noLabel: "no", alertHandler: handle2};
//Defining pspConf parameter for alert var pspConf = {};
//Alert definition var infoAlert = kony.ui.Alert(basicConf,pspConf);
© 2015 by Kony, Inc. All rights reserved 158 of 848
6. Alert API Kony Studio API Developer's Guide
Version 5.0
function handle2(response)
{ frm6.show();
} var pspConfig = {"iconPosition" : constants.ALERT_CONTENT_ALIGN_
CENTER,
"contentAlignment":constants.ALERT_ICON_POSITION_LEFT } ; var alert = kony.ui.Alert({
"message": "Hello Alert",
"alertType": constants.ALERT_TYPE_ERROR,
"alertTitle": "I'm Alert",
"yesLabel": "Yes",
"noLabel": "",
"alertIcon": "",
"alertHandler": null
}, pspConfig);
Alerts are displayed on some platforms as follows:
Windows Phone Mango BlackBerry STORM
© 2015 by Kony, Inc. All rights reserved 159 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
7. Background Jobs
Background Jobs feature in Kony Platform includes
and
7.1 Background Fetch
You can allow the application to fetch data from a network on regular basis while it is in a background state, with the background fetch capability in iOS7. This data can be utilized to keep the content of the application up-to-date and present it to the user when the user launches or re-opens the application.
Also, the capability to support long running HTTP/HTTPS tasks like downloading large files if the application is in background state is supported.
l
In iOS version 7 and above, an app that retrieves content regularly from a network can ask the system for background execution time to check for new content.
l
An application developer who wishes to perform a background fetch can enable this feature in
Kony Studio IDE and register for the feature using
kony.backgroundjob.registerBackgroundFetch
. This API can be used to register predefined fetch job that can handle tasks like file download, upload, or a custom task.
l
kony.net.HttpRequest
API supports background transfers. Tasks like upload or download from the network (HTTP/HTTPS) that are active even when the app is in background or suspended state is available in iOS7.
7.2 Background Transfers
The purpose of the background transfer service is to allow long running network downloads or uploads to take place even when the associated application is placed in the background. Background transfers are supported in HTTP and HTTPS protocols.
Following are the features in Background Transfer: l
Uploads and downloads are managed by iOS l
Unlike background fetch, background transfers have unlimited time.
© 2015 by Kony, Inc. All rights reserved 160 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
l
It can be put in the queue anytime (foreground and background).
l
App is woken up to handle authentication challenges, errors if any, or completion of the job.
l
Background transfer tasks can be paused and resumed.
l
Only HTTP and HTTPS protocols are supported.
7.3 Background Fetch Workflow
iOS7 introduces the
Background Fetch
API which allows an app to get updated content when the app is in background. iOS7 schedules the background fetch events based on the app usage so that the content is always up-to-date when user opens the application. iOS7 provides 30 seconds time frame for the app to wake up, fetch new data, update its interface, and go back to sleep.
If the Background Fetch feature is enabled in an app, the system wakes the app in the background from time to time and lets it go online to fetch new data with a goal to refresh its content. In this way the app is always up-to-date and users do not have to wait any more when they launch it.
The system determines how frequent the application can perform a background fetch and depends on the following factors: l
If network connectivity is available at that particular time.
l
Is the device awake.
l
Data and time the application has taken in its previous attempt to perform a background fetch.
The iOS system gives power to an application to schedule Background Fetch. Background Fetch can also be used to perform tasks internally in the app. Only synchronous tasks must be performed in background fetch, other than long running Background Transfers that are asynchronous. After the task is done
setBackgroundFetchCompletionStatus
must be called, passing a result that indicates whether content is available.
Invoking
setBackgroundFetchCompletionStatus
tells the system that it can move the app back to the suspended state and evaluate its power usage.
© 2015 by Kony, Inc. All rights reserved 161 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
Apps that download small amounts of content quickly and accurately reflect when they had content to download are more likely to receive execution time in the future than apps that take longer to download their content.
It is advisable to use Background Transfers supported by
kony.net.HttpRequest
in fetch task to optimally utilize the execution time provided in the Fetch task.
7.4 Background Fetch and Background Transfers APIs
Background Fetch APIs
Following are the APIs for Background Jobs:
1.
kony.backgroundjob.registerBackgroundFetch
2.
kony.backgroundjob.setBackgroundFetchCompletionStatu
3.
kony.backgroundjob.setBackgroundFetchInterval
Background Transfer
APIs
Following are the
Background Transfer APIs :
1.
2.
3.
4.
7.5 Supported Versions and Platforms
The Background Job feature: l
Available in Kony iOS platform versions above 5.6.2.
l
Supports iOS7 and the platforms above.
l
Supported only in JavaScript.
© 2015 by Kony, Inc. All rights reserved 162 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
7.6 kony.backgroundjob.registerBackgroundFetch
registerBackgroundFetch can be used to register a background fetch job. A JavaScript function that can be invoked whenever the system schedules the fetch task. The app is woken up after the specified amount of fetchInterval.
Note: At the end of the background fetch job, you must invoke the
kony.backgroundjob.setBackgroundFetchCompletionStatus
passing a result that indicates whether content is available or not.
7.6.1 Signature
JavaScript: kony.backgroundjob.registerBackgroundFetch ( backgroundCallBack , fetchInterval )
7.6.2 Input Parameters backgroundCallBack [Function] - Mandatory
This callback is to be executed when the system invokes the app for a fetch job when the app is in background.
fetchInterval [Number] / [Constant] - Optional
Indicates the minimum time interval in seconds which must elapse before system can invoke the app for next fetch job .This is an optional parameter and value that is specified is only indicative and might not have any real effects on the scheduling frequency, as system decides the actual interval.
Possible values are:
1. constants.BACKGROUND_TASK_FETCH_INTERVAL_MINIMUM
* This is the default value. System decides the fetch interval depending on the usage prediction for the app.
2. constants.BACKGROUND_TASK_FETCH_INTERVAL_NEVER
© 2015 by Kony, Inc. All rights reserved 163 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
Disable background task. Set the time interval to constants.BACKGROUND_TASK_
FETCH_INTERVAL_NEVER so that the job is no longer scheduled for running.
3. Time in seconds. (Negative values are not accepted).
7.6.3 Return Values
<N.A> or “NONE".
7.6.4 Exceptions and Error Handling
1. If no arguments or less number of arguments than the mandatory number of arguments are provided, it raises an exception and throws a “KonyError” JS Object with the following attributes: errorCode: 4001.
name: "BackgroundJobError".
message: "registerBackgroundFetch: MissingMandatoryParameters."
2. If arguments type does not match the allowed type, it raises an exception and throws a
KonyError JavaScript Object with the following attributes: errorCode: 4002.
name: "BackgroundJobError".
message: "registerBackgroundFetch: InvalidParameters."
7.6.5 Platform Availability
Available in iOS Platform.
7.6.6 JavaScript Example function backgroundFetchCallBack() {
© 2015 by Kony, Inc. All rights reserved 164 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
//fetch handler invoked whenever the system invokes the App for a fetch job
// do something here
// in the end of the handler setBackgroundFetchCompletionStatus() need
// to be called mandatorily other wise system might termitane the app.
// task completion status.
//1. constants.BACKGROUND_TASK_STATUS_NEW_DATA
//2. constants.BACKGROUND_TASK_STATUS_FAILED
//3. constants.BACKGROUND_TASK_STATUS_NO_NEW_DATA
var completionStatus = constants.BACKGROUND_TASK_STATUS_NEW_DATA; kony.backgroundjob.setBackgroundFetchCompletionStatus
(completionStatus);
};
//Fetch interval
//1. constants.BACKGROUND_TASK_FETCH_INTERVAL_MINIMUM
//2. constants.BACKGROUND_TASK_FETCH_INTERVAL_NEVER
//3. Time in seconds. (Negative values are not accepted).
var fetchInterval = constants.BACKGROUND_TASK_FETCH_INTERVAL_
MINIMUM;
//register background fetch job kony.backgroundjob.registerBackgroundFetch
(backgroundFecthCallBack, fetchInterval);
© 2015 by Kony, Inc. All rights reserved 165 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
7.7 kony.backgroundjob.setBackgroundFetchCompletionStatus
One must call this method in the end of
backgroundCallBack
passing a result that indicates whether content was available or not. This method intimates the system of the completion status of the background fetch job that has been scheduled.
Executing this call tells the system that it can move the app back to the suspended state and evaluate its power usage. Apps that download small amounts of content quickly and accurately display when they have content to download are more likely to receive execution time in the future than apps that take longer to download their content
Failure to call this method results in undefined behavior and could cause the app to be terminated by the system. If an error arises during invoking this API, default value:
constants.BACKGROUND_
TASK_STATUS_FAILED
will be set.
7.7.1 Signature
JavaScript: kony.backgroundjob.setBackgroundFetchCompletionStatus(
)
7.7.2 Input Parameters completionStatus [constant] - Mandatory
This is a mandatory parameter. Possible values are as follows
1. constants.BACKGROUND_TASK_STATUS_NEW_DATA
This tells the system that the fetch was successful and internally, the system then updates the apps UI(if the fetch resulted in UI change) in the background. This new UI is presented to the user once the app is brought to fore ground. The snapshot of the new UI is also presented when the user tries to switch apps using the App switcher.
2. constants.BACKGROUND_TASK_STATUS_FAILED
© 2015 by Kony, Inc. All rights reserved 166 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
This tells the system that the fetch was unsuccessful. UI is not updated and the task will be run later based on the available system resources.
3. constants.BACKGROUND_TASK_STATUS_NO_NEW_DATA
This intimates the system the fetch did not result in any new data, UI is not updated and the job is run after any point later in time but not before fetchInterval.
7.7.3 Return Values
<N.A> or “NONE".
7.7.4 Exceptions
1. If no arguments or less number of arguments than the mandatory number of arguments are provided, it raises an exception and throws a “KonyError” JS Object with the following attributes: errorCode: 4001.
name: "BackgroundJobError".
message: "setBackgroundFetchCompletionStatus:
MissingMandatoryParameters."
2. If arguments type does not match the allowed type, it raises an exception and throws a
“KonyError” JS Object with the following attributes: errorCode: 4002.
name: "BackgroundJobError".
message: "setBackgroundFetchCompletionStatus:
InvalidParameters."
3. If an error arises during invoking of this API, default value: constants.BACKGROUND_TASK_
STATUS_FAILED will be set.
© 2015 by Kony, Inc. All rights reserved 167 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
7.7.5 Platform Availability
Available in iOS Platform.
7.7.6 JavaScript Example function backgroundFecthCallBack() {
//fetch handler invoked whenever the system invokes the App for a fetch job
// do something here
// in the end of the handler setBackgroundFetchCompletionStatus() need
// to be called mandatorily other wise system might termitane the app.
// task completion status.
//1. constants.BACKGROUND_TASK_STATUS_NEW_DATA
//2. constants.BACKGROUND_TASK_STATUS_FAILED
//3. constants.BACKGROUND_TASK_STATUS_NO_NEW_DATA
var completionStatus = constants.BACKGROUND_TASK_STATUS_NEW_DATA; kony.backgroundjob.setBackgroundFetchCompletionStatus
(completionStatus);
};
//Fetch interval
//1. constants.BACKGROUND_TASK_FETCH_INTERVAL_MINIMUM
© 2015 by Kony, Inc. All rights reserved 168 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
//2. constants.BACKGROUND_TASK_FETCH_INTERVAL_NEVER
//3. Time in seconds. (Negative values are not accepted).
var fetchInterval = constants.BACKGROUND_TASK_FETCH_INTERVAL_
MINIMUM;
//register background fetch job kony.backgroundjob.registerBackgroundFetch
(backgroundFecthCallBack, fetchInterval);
7.8 kony.backgroundjob.setBackgroundFetchInterval
This method sets the fetch interval for the background fetch job scheduled.
7.8.1 Signature
JavaScript: kony.backgroundjob.setBackgroundFetchInterval(
)
7.8.2 Input Parameters fetchInterval [Number]/[Constant] - Mandatory
Indicative minimum time interval in seconds that should elapse before system can invoke the app for next fetch job. This is only indicative and may not have any real effects on the scheduling frequency, as system decides the actual interval.
Possible values are:
1. constants.BACKGROUND_TASK_FETCH_INTERVAL_MINIMUM
This is the default value. System decides the fetch interval depending on the usage prediction for the app.
2. constants.BACKGROUND_TASK_FETCH_INTERVAL_NEVER
© 2015 by Kony, Inc. All rights reserved 169 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
Disable background task. Set the time interval to constants.BACKGROUND_TASK_FETCH_
INTERVAL_NEVER so that the job is no longer scheduled for running.
3. Time in seconds. (Negative values are not accepted).
7.8.3 Return Values
<N.A> or “NONE".
7.8.4 Exceptions
1. If no arguments or less number of arguments than the mandatory number of arguments are provided, it raises an exception and throws a “KonyError” JS Object with the following attributes: errorCode: 4001.
name: "BackgroundJobError".
message: "setBackgroundFetchInterval:
MissingMandatoryParameters."
2. If arguments type does not match the allowed type, it raises an exception and throws a
“KonyError” JS Object with the following attributes: errorCode: 4002.
name: "BackgroundJobError".
message: "setBackgroundFetchInterval: InvalidParameters."
7.8.5 Platform Availability
Available in iOS Platform.
© 2015 by Kony, Inc. All rights reserved 170 of 848
7. Background Jobs Kony Studio API Developer's Guide
Version 5.0
7.8.6 JavaScript Example
//Fetch interval
//1. constants.BACKGROUND_TASK_FETCH_INTERVAL_MINIMUM
//2. constants.BACKGROUND_TASK_FETCH_INTERVAL_NEVER
//3. Time in seconds. (Negative values are not accepted).
var fetchInterval = constants.BACKGROUND_TASK_FETCH_INTERVAL_
MINIMUM; kony.backgroundjob.setBackgroundFetchInterval(fetchInterval);
© 2015 by Kony, Inc. All rights reserved 171 of 848
Kony Studio API Developer's Guide
Version 5.0
7.9 Long Running Network Tasks
kony.net.HttpRequest
now supports long running network tasks which run to completion even when the app is pushed to Background or Suspended state, these are also known as background transfers and are available from iOS7.
Background transfers can be scheduled while the app is in foreground or while the app is in background (with the help of background fetch jobs in background state).
Background transfers can be enabled by setting the property ‘backgroundTransfer’ to ‘true’ on the
HTTP request object returned by kony.net.HttpRequest.
‘‘<HttpRequestObject>.backgroundTransfer’ has to be set to ‘true’ before open() API is invoked on the
HTTP request after its creation.
It is always advisable to set “<HttpRequestObject>.backgroundTransfer” to ‘true’ immediately after creation of HttpRequest object.
7.9.1 Signature var httpclient = new kony.net.HttpRequest(); httpclient.backgroundTransfer = true;
7.9.2 Input Parameters
Http request object returned by kony.net.HttpRequest supports additional property
‘backgroundTransfer’ to enable running network tasks to run even when the App is in background state.
backgroundTransfer : <Read/Write property>
Lets the HTTP request to know that Background transfers need to be supported.
Possible values: true / false
Default value: false
© 2015 by Kony, Inc. All rights reserved 172 of 848
Kony Studio API Developer's Guide
Version 5.0
7.9.3 Platform Availability
Available in iOS Platform.
7.9.4 JavaScript Example var logPrefix = "bg_transfer_test_case_1 :- "; send_request(); function send_request() { var request = new kony.net.HttpRequest(); request.onReadyStateChange = callbackHandler;
//BGtransfer request.backgroundTransfer = true;
//session var req_session = request.getSession(); kony.print(logPrefix + " request.getSession() : " + req_ session);
//url var url =
"https://developer.apple.com/library/ios/documentation/iphone/concep tual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf"; kony.print(logPrefix + "URL : " + url); request.open(constants.HTTP_METHOD_GET, url); request.send();
}; function callbackHandler(request) { kony.print(logPrefix + " :
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++");
© 2015 by Kony, Inc. All rights reserved 173 of 848
Kony Studio API Developer's Guide
Version 5.0
kony.print(logPrefix + " : Scope :- request.status : " + request.status); kony.print(logPrefix + " : Scope :- request.statusText : " + request.statusText); kony.print(logPrefix + " : Scope :- request.responseType : "
+ request.responseType); kony.print(logPrefix + " : Scope :- request.response : " + request.response); kony.print(logPrefix + " : Scope :request.getAllResponseHeaders() : "); kony.print(request.getAllResponseHeaders()); kony.print(logPrefix + " :
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++");
};
7.10 suspend
Temporarily suspends a background transfer task, while suspended, it produces no network traffic and is not subject to timeouts.
A suspended background transfer task if resumable can be resumed using resume() API. If the task cannot be resumed the transfer task will start afresh.
This API is applicable only if
<HttpRequestObject>.backgroundTransfer = true
for a HTTPrequest.
7.10.1 Signature
<<HttpRequestObject>>.suspend
7.10.2 Input Parameters
None
© 2015 by Kony, Inc. All rights reserved 174 of 848
Kony Studio API Developer's Guide
Version 5.0
7.10.3 Return Values
None
7.10.4 Platform Availability
Available in iOS Platform.
7.10.5 JavaScript Example var request = new kony.net.HttpRequest();
//BGtransfer request.backgroundTransfer = true;
//url var url =
"https://developer.apple.com/library/ios/documentation/iphone/concep tual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf"; kony.print(logPrefix + "URL : " + url); request.open(constants.HTTP_METHOD_GET, url); request.send();
//suspend task request.suspend();
7.11 resume
l
A resumable suspended task can be resumed using this API. If the task cannot be resumed the transfer task will start afresh.
© 2015 by Kony, Inc. All rights reserved 175 of 848
Kony Studio API Developer's Guide
Version 5.0
l
This API is applicable only if
<HttpRequestObject>.backgroundTransfer = true
for a HTTPrequest.
7.11.1 Signature
<<HttpRequestObject>>.resume()
7.11.2 Input Parameters
None
7.11.3 Return Values
None
7.11.4 Platform Availability
Available in iOS Platform.
7.11.5 JavaScript Example var request = new kony.net.HttpRequest();
//BGtransfer request.backgroundTransfer = true;
//url var url =
"https://developer.apple.com/library/ios/documentation/iphone/concep tual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf"; kony.print(logPrefix + "URL : " + url); request.open(constants.HTTP_METHOD_GET, url);
© 2015 by Kony, Inc. All rights reserved 176 of 848
Kony Studio API Developer's Guide
Version 5.0
request.send();
//suspend task request.suspend();
//resume task request.resume();
7.12 getTaskState
l
Returns the current state of the transfer task: active, suspended, in the process of being canceled, or completed l
This API is applicable only if
<HttpRequestObject>.backgroundTransfer = true
for a HTTPrequest.
7.12.1 Signature var taskState = <<HttpRequestObject>>. getTaskState()
7.12.2 Input Parameters
None
7.12.3 Return Values taskState: <constant> l constants.SESSION_TASK_STATE_RUNNING
l constants.SESSION_TASK_STATE_SUSPENDED
l constants.SESSION_TASK_STATE_CANCELING
l constants.SESSION_TASK_STATE_COMPLETED
© 2015 by Kony, Inc. All rights reserved 177 of 848
Kony Studio API Developer's Guide
Version 5.0
7.12.4 Platform Availability
Available in iOS Platform.
7.12.5 JavaScript Example var request = new kony.net.HttpRequest();
//BGtransfer request.backgroundTransfer = true;
//url var url =
"https://developer.apple.com/library/ios/documentation/iphone/concep tual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf"; kony.print(logPrefix + "URL : " + url); request.open(constants.HTTP_METHOD_GET, url); request.send();
//getTaskStat() var tastState = request_object.getTaskState(); if (tastState == constants.SESSION_TASK_STATE_RUNNING) { kony.print("tastState == constants.SESSION_TASK_
STATE_RUNNING");
} else if (tastState == constants.SESSION_TASK_STATE_
SUSPENDED) { kony.print("tastState == constants.SESSION_TASK_
STATE_SUSPENDED");
CANCELING) {
} else if (tastState == constants.SESSION_TASK_STATE_
kony.print("tastState == constants.SESSION_TASK_
© 2015 by Kony, Inc. All rights reserved 178 of 848
Kony Studio API Developer's Guide
Version 5.0
STATE_CANCELING");
} else if (tastState == constants.SESSION_TASK_STATE_
COMPLETED) { kony.print("tastState == constants.SESSION_TASK_
STATE_COMPLETED");
}
© 2015 by Kony, Inc. All rights reserved 179 of 848
Kony Studio API Developer's Guide
Version 5.0
7.13 Session Configuration API
7.13.1 getSession l
By default, if a new background transfer task is created using
kony.net.HttpRequest
[‘<HttpRequestObject>.backgroundTransfer = true’] a new session is created and this new task is associated with it.
l
<HttpRequestObject> now exposes a new method ‘getSession()’ using which the Session identifier associated with the HttpRequest can be obtained.
l
Multiple background tasks can be associated with the same Session by passing the Session identifier returned by
<HttpRequestObject>.getSession()
to any new
‘kony.net.HttpRequest’ created there after.
l getSession() API is applicable only if
<HttpRequestObject>.backgroundTransfer = true
for a HTTPrequest.
l
When ever a new
kony.net.HttpRequest
is created by passing a session identifier then by default backgroundTransfer property will be enabled
[‘<HttpRequestObject>.backgroundTransfer = true’].
Note: A session object life is dependent on the life of any of the request objects or request object it is associated with. Which means to be certain that a session is alive, any of the request objects or request object with which it is associated should be alive.
7.13.1.1 Signature var session_identifier = <<HttpRequestObject>>.getSession()
//To associate new HTTP Requests created with the same session
<New HttpRequestObject2> = new kony.net.HttpRequest(<session_identifier >);
7.13.1.2 Input Parameters
None
© 2015 by Kony, Inc. All rights reserved 180 of 848
Kony Studio API Developer's Guide
Version 5.0
7.13.1.3 Return Values
Session identifier for the Session associated with the HttpRequest instance.
7.13.1.4 JavaScript Example var request = new kony.net.HttpRequest();
//BGtransfer request.backgroundTransfer = true;
//url var url =
"https://developer.apple.com/library/ios/documentation/iphone/concep tual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf"; kony.print(logPrefix + "URL : " + url); request.open(constants.HTTP_METHOD_GET, url); request.send();
//request session identifier var request_session = request.getSession();
//To associate new HTTP Requests created with the same session
//request 2 var request_2 = new kony.net.HttpRequest(request_session);
//request 3 var request_3 = new kony.net.HttpRequest(request_session);
© 2015 by Kony, Inc. All rights reserved 181 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
8. Badge APIs
Badge is a small icon which displays some indicative information to the users. Badge can be used for an application, a specific widget, app menu, or an app menu icon.
The badge looks like the image below:
A badge can be used in the following scenarios to : l display a message on a specific widget l emphasize the price l advertise a promotion l indicate the number of unread messages or notifications.
Note: Badge APIs are applicable only on iPhone and iPad.
This chapter explains the following APIs: l
kony.application.setApplicationBadgeValue
l
kony.application.getApplicationBadgevalue
l
l
l
kony.application.setAppMenuBadgeValue
l
kony.application.getAppMenuBadgeValue
© 2015 by Kony, Inc. All rights reserved 182 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
8.1 kony.application.setApplicationBadgeValue
This API allows you to set a badge value to an application icon on the mobile desktop at the top-right corner of the application icon. If you pass an empty string as a parameter, the badge applied on the application icon is removed.
8.1.1 Signature
JavaScript : kony.application.setApplicationBadgeValue(
)
8.1.2 Input Parameters badgeValue [String] - Mandatory
Value of the badge. The value that you specify in the badgeValue parameter appears within the badge. Do not pass any other value except a numerical value. For example, to set a badge value for an appicon, specify the value as "2" instead of 2. If the length of the badge value is greater than
1 the badge is a rounded rectangle. For example, if you specify the value of the badge as 88, the number appears in a rounded rectangular badge. If the length of the badge value is 1, the badge is always a circle.
8.1.3 Return Values
None
8.1.4 UI Behavior
The badge appears with white font on a red background. The shape of the badge varies with its value: l
If the badge value is a single digit, the badge shape is a circle.
© 2015 by Kony, Inc. All rights reserved 183 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
l
If the badge value contains multiple digits, the badge shape is a rectangle with rounded corners and borders.
8.1.5 Platform Availability
Available only on iPhone and iPad.
8.1.6 JavaScript Example function setApplicationBadgeValue()
{
//Set the ApplicationBadgeValue to the application icon on the mobile desktop at the top-right corner of the application icon.
kony.application.setApplicationBadgeValue("234567");
}
The badge appears as follows when you execute the code given above:
© 2015 by Kony, Inc. All rights reserved 184 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
8.2 kony.application.getApplicationBadgeValue
This API allows you to read the badge value (if any) attached to the given application icon. If the applications icon does not have any badge value attached to it, this API returns an empty string.
8.2.1 Signature
JavaScript : kony.application.getApplicationBadgeValue()
8.2.2 Input Parameters
None
8.2.3 Return Values badgeValue [String]
Returns the badge value applied to the application icon If the application icon has no badge value attached to it, it returns null/nil.
8.2.4 Platform Availability
Available only on iPhone and iPad.
8.2.5 JavaScript Example function getApplicationBadgeValue()
{
//Get the ApplicationBadgeValue from the application icon on the mobile desktop at the top-right corner of the application icon.
kony.application.getApplicationBadgeValue();
}
© 2015 by Kony, Inc. All rights reserved 185 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
8.3 setBadge
This API enables you to set the badge value to the given widget at the top-right corner of the widget. If you pass an empty string as a parameter, the badge applied to the widget is cleared.
8.3.1 Signature
JavaScript: <<widgetreference>>.setBadge(
)
8.3.2 JavaScript Parameters badgeText [String] - Mandatory
Specifies the Text value that appears within the badge. If the length of the badgeText is greater than 1 the badge is a rounded rectangle. For example, if you specify the text of the badge as 88, the number appears in a rounded rectangular badge. If the length of the badge text is 1, the badge is always a circle. The badge can occupy upto 70% of the width of the parent widget. For example, on a button with a width of 100 pixels, a badge with about 100 characters will occupy only 70 pixels of the button width. The badge text is truncated and shows about 30 characters followed by three dots.
skin [String] - Optional
Specifies the background color for the badge. The default color is red.
8.3.3 Return Values
None.
8.3.4 UI Behavior
The badge appears with white font on a red background. The shape of the badge varies with its value:
© 2015 by Kony, Inc. All rights reserved 186 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
l
If the badge value is a single character (a character or a number), the badge shape is a circle.
l
If the badge value contains multiple characters, the badge shape is a rectangle with rounded corners and borders.
l
The badge can occupy a maximum of 70% width of the parent widget (widget on which badge is applied). For example, on a button with a width of 100 pixels, a badge with about 100 characters will occupy only 70 pixels of the button width. The badge value is truncated and about 30 characters followed by three dots.
Important: When a badge is set, the widgets are re-laid to accommodate the badge values.
8.3.5 Rules and Restrictions
For iOS platform, this method is applicable on Box, Label, and Image widgets only.
For Android platform, this method is applicable on Button and Image widgets only.
8.3.6 Platform Availability
Available only on iPhone, iPad, and Android.
8.3.7 JavaScript Example function setBadge()
{
//To set a badge value with skin "badgeSkin" on a hbox with ID hbx1 placed on a form frm1, use the following snippet: frm1.hbx1.setBadge("2","badgeSkin");
}
© 2015 by Kony, Inc. All rights reserved 187 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
8.4 getBadge
This API enables you to read the badge value (if any) attached to the specified widget. If the specified widget does not have a badge attached to it, it returns an empty string.
8.4.1 Signature
JavaScript : <<widgetreference>>.getBadge(
)
8.4.2 JavaScript Parameters uniqueIdentifier [Widget Reference] - Mandatory
Unique identifier of a widget which is a handle to the widget.
8.4.3 Return Values badgeValue [String]
Returns the badge value applied to the specified widget. If the specified widget has no badge value attached to it, it returns an empty string.
8.4.4 UI Behavior
Important: When a badge is removed, the widgets are re-laid to accommodate the cleared badge values.
8.4.5 Rules and Restrictions
For iOS platform, this method is applicable on Box, Label, Button, Image, TextBox, and TextArea widgets only.
For Android platform, this method is applicable on Button and Image widgets only.
© 2015 by Kony, Inc. All rights reserved 188 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
8.4.6 Platform Availability
Available only on iPhone, iPad, and Android.
8.4.7 JavaScript Example function getBadge()
{
//To get a badge value on a hbox with ID hbx1 placed on a form frm1, use the following snippet: var badgeVal =frm1.hbx1.getBadge(); alert("badge value is::"+badgeVal);
}
8.5 kony.application.setAppMenuBadgeValue
This API allows you to set a badge value to the specified app menu item on the top-right corner of the app menu item. If you pass an empty string as the parameter, the badge value of the app menu item is cleared.
8.5.1 Signature
JavaScript
: kony.application.setAppMenuBadgeValue( appmenuID ,
8.5.2 Input Parameters appMenuId [String] - Mandatory
If you are setting the badge for an app menu item that was created dynamically, use the same ID that was used to create the app menu item.If you are setting the badge for an app menu item that was created from the IDE, use the ID available in the generated script file.
© 2015 by Kony, Inc. All rights reserved 189 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
menuItemId [String] - Mandatory
Id of the app menu item to which the badge value to be set.
badgeValue [String] - Mandatory
Value of the badge. The value you specify in the badge value appears within the badge. If the length of the badge value is greater than 1 the badge is a rounded rectangle. For example, if you specify the value of the badge as 88, the number appears in a rounded rectangular badge. If the length of the badge value is 1, the badge is always a circle. The maximum number of characters that can be specified in a badge value is 9. If the badge value id beyond 9 only the first 9 characters are displayed.
8.5.3 Return Values
None
8.5.4 UI Behavior
The following image depicts how a bade appears on an app menu item:
8.5.5 Platform Availability
Available only on iPhone and iPad.
8.5.6 JavaScript Example function setAppMenuBadgeValue()
{
//Set the AppMenuBadgeValue for the menu item with id ::
"appmenuitemid3" ,here the badge value is "3" kony.application.setAppMenuBadgeValue
("accountMenu","appmenuitemid3",
© 2015 by Kony, Inc. All rights reserved 190 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
"3");
}
8.6 kony.application.getAppMenuBadgeValue
This API enables you to read the badge value (if any) attached to the specified app menu item. If the specified app menu item does not have any badge value attached to it, the API returns an empty string.
8.6.1 Signature
JavaScript
: kony.application.getAppMenuBadgeValue( appmenuID , menuItemID )
8.6.2 Input Parameters appMenuId [String] - Mandatory
If you are setting the badge for an app menu item that was created dynamically, use the same ID that was used to create the app menu item.If you are setting the badge for an app menu item that was created from the IDE, use the ID available in the generated script file.
menuItemId [String] - Mandatory
Identifier of the app menu item from which the badge value is to be read.
8.6.3 Return Values badgeValue [String]
Returns the badge value applied to the specified app menu. If the specified app menu has no badge value attached to it, it returns an empty string.
8.6.4 Platform Availability
Available only on iPhone and iPad.
© 2015 by Kony, Inc. All rights reserved 191 of 848
8. Badge APIs Kony Studio API Developer's Guide
Version 5.0
8.6.5 JavaScript Example function getAppMenuBadgeValue()
{
//Get the AppMenuBadgeValue for the menu item with id :
:"appmenuitemid3" kony.application.getAppMenuBadgeValue
("accountMenu","appmenuitemid3");
}
© 2015 by Kony, Inc. All rights reserved 192 of 848
9. Beacon FFI APIs Kony Studio API Developer's Guide
Version 5.0
9. Beacon FFI APIs
Beacon FFI APIs help you work with iBeacons. iBeacons are devices that transmit signals using
Bluetooth low-energy wireless technology, and allow you to create and monitor beacons that advertise certain identifying information. Beacon Region is a region defined by a device’s proximity to Bluetooth
Beacons.
9.1 Prerequisites
To use Beacon FFI APIs, you need iOS 7 or later, Bluetooth turned on, and a compatible iOS device: l
Xcode 5.0 or later l iPhone 4s or later l iPad (3rd generation) or later l iPad mini or later l iPod touch (5th generation) or later
The following classes are available in Beacon FFI: l
l
l
l
9.2 How-to Sections
l
Determining the Availability of Region Monitoring
l
© 2015 by Kony, Inc. All rights reserved 193 of 848
9. Beacon FFI APIs l
Handling Boundary-Crossing Events
l
Determining the Proximity of a Beacon Using Ranging
l
Turning an iOS Device Into an iBeacon
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 194 of 848
Kony Studio API Developer's Guide
Version 5.0
9.2.1 Determining the Availability of Region Monitoring
Before monitoring a Beacon Region on a device, the developer should check for the availability of the region monitoring and the authorization status.To determine the availability, follow these steps:
1. Check the availability of the
Monitoring.
The
isMonitoringAvailableForBeaconRegions
method helps determine whether a device supports Beacon Region Monitoring. If the method returns false, the application cannot use
Beacon Region Monitoring. If the method returns true, the developer must check the authorization status of the Beacon Region Monitoring.
if (beaconManager.isMonitoringAvailableForBeaconRegions()) { kony.print("Monitoring is available");
// Check for authorization status
}
2. Check the
Monitoring Authorization Status.
The
method of
determines whether the application is currently authorized to use iOS location services for monitoring the beacons. If the authorization status is
BeaconManagerAuthorizationStatusAuthorized
, the application will receive boundary-crossing notifications for any region it is monitoring. If the authorization status is any other value, the application does not receive those notifications.
If the application is not authorized to use Beacon Region Monitoring, it can still register Beacon
Regions for later use. If the user grants authorization to the application, monitoring for those regions will begin and will generate subsequent boundary-crossing notifications.
if (beaconManager.authorizationStatus() ==
"BeaconManagerAuthorizationStatusAuthorized") {
© 2015 by Kony, Inc. All rights reserved 195 of 848
Kony Studio API Developer's Guide
Version 5.0
} kony.print("Authorized to use location services");
You can use
authorizationStatusChanged
callback to detect changes in authorization status to the application.
Refer to the Apple’s Location and Maps Programming Guide for more information.
© 2015 by Kony, Inc. All rights reserved 196 of 848
Kony Studio API Developer's Guide
Version 5.0
9.2.2 Monitoring Beacon Regions
When a Beacon Region is monitored, respective callbacks are fired when the device crosses the boundary of the region. You can define a Beacon Region using the
class with proximityUUID, major, minor and identifier methods. The identifier is required and provides a way to refer to a particular beacon in your code. To register a Beacon Region for monitoring, call the
method of the
object.
To monitoring Beacon Regions, follow these steps:
1. Create a
object with beacon identifying information.
var aBeaconRegion = new com.kony.BeaconRegion(aProximityUUID, aMajor, aMinor, anIdentifier);
2. Create a Beacon Manager object with event callback functions.
function monitoringCallback(beaconRegion, state) {} function rangingCallback(beaconRegion, beacons) {} function errorCallback(beaconManagerError, errorName, errorDictionary, beaconRegion) {} var aBeaconManager = new com.kony.BeaconManager
(monitoringCallback, rangingCallback, errorCallback);
3. Start monitoring the beacon region by calling the
method of the
BeaconManager object.
aBeaconManager.startMonitoringBeaconRegion(aBeaconRegion);
© 2015 by Kony, Inc. All rights reserved 197 of 848
Kony Studio API Developer's Guide
Version 5.0
9.2.3 Handling Boundary-Crossing Events
If the device enters or exits a Beacon Region, you will be notified through the
monitoringCallback
of BeaconManager object. A developer can postpone these notifications until the user turns on the device’s display by calling setNotifyEntryStateOnDisplay with true.
To handle boundary-crossing events, follow these steps:
1. Define a monitoring callback.
A monitoring callback should accept two arguments,
object and Device State, of the Beacon Region. The monitoring callback is called on detection of any boundary-crossing event.
function monitoringCallback(beaconRegion, beaconRegionState) {
...
}
2. Handle events.
If the device enters a Beacon Region,
beaconRegionState
will be
BeaconRegionStateInside
.
If the device exits a Beacon Region,
beaconRegionState
will be
BeaconRegionStateOutside
.
function monitoringCallback(beaconRegion, beaconRegionState) { if (beaconRegionState == "BeaconRegionStateInside") {
// Device is inside the beacon region -- start ranging beacons
}
}
© 2015 by Kony, Inc. All rights reserved 198 of 848
Kony Studio API Developer's Guide
Version 5.0
9.2.4 Determining the Proximity of a Beacon Using Ranging
A
can be ranged to determine the proximity of the beacon from the device using the
startRangingBeaconsRegion
method of the
object.
You should call the
isRangingAvailableForBeaconRegions
method of the
before attempting to range beacons.
Whenever the beacons come within range or go out of range, the
object will notify you through rangingCallback with an array of
objects. The beacon objects are detected in the order of closest to farthest. Use the
property to determine relative distance of the beacon to the device. Determine the beacon identifying information using other properties of the beacon object.
To determine proximity, follow these steps:
1. Determining the availability of beacon ranging.
The
isRangingAvailableForBeaconRegions
method determines whether the current device supports beacon region ranging. If the method returns false, the application cannot use beacon region ranging.
2. Define ranging callback for notifications.
Ranging callback should accept two arguments, a
and array beacons, which are in range.
function rangingCallback(beaconRegion, beacons) {
// Determine the proximity of beacons to the device.
}
3. Ranging beacons in a region.
© 2015 by Kony, Inc. All rights reserved 199 of 848
Kony Studio API Developer's Guide
Version 5.0
To start ranging beacons in a beacon region, use
startRangingBeaconsInRegion
method to start ranging updates for beacons in that region.
var aBeaconRegion = new com.kony.BeaconRegion(aProximityUUID, aMajor, aMinor, anIdentifier); var aBeaconManager = new com.kony.BeaconManager
(monitoringCallback, rangingCallback, errorCallback); aBeaconManager.startRangingBeaconsInRegion(aBeaconRegion);
4. Determine proximity and other properties.
In the
rangingCallback
, the developer can determine the relative distance of the beacon from the device.
function rangingCallback(beaconRegion, beacons) { for (var beacon in beacons) { if (beacon.getProximity() ==
"BeaconProximityImmediate") {
// Immediate
} else if (beacon.getProximity() ==
"BeaconProximityNear") {
// Near
} else { // beacon.getProximity() ==
"BeaconProximityFar"
// Far
}
}
}
}
© 2015 by Kony, Inc. All rights reserved 200 of 848
Kony Studio API Developer's Guide
Version 5.0
9.2.5 Turning an iOS Device Into an iBeacon
Any iOS device that supports sharing data using Bluetooth low energy can be used as an iBeacon.
Because the application you write must run in the foreground, iBeacon support on iOS devices is intended for testing purposes and for applications that always run in the foreground, such as point-ofsale apps. For other types of iBeacon implementations, you need to acquire dedicated beacon hardware from third-party manufacturers.
To turn an iOS device into an iBeacon, follow these steps:
1. Create a
object.
To use your iOS device as a beacon, you first generate a 128-bit UUID that will be your Beacon
Region’s proximity UUID. Open Terminal(in Mac OS) and type uuidgen on the command line.
You receive a unique 128-bit value in an ASCII string that is punctuated by hyphens, as in this example.
$ uuidgen
FBA1FFE5-7CD6-451B-8F1F-22B2AC70AA45
Next, create a Beacon Region with the UUID you generated for the beacon’s proximity UUID, defining the major and minor values as needed. Be sure to also use a unique string identifier for the new region. This code shows how to create a new Beacon Region using the example UUID above.
var proximityUUID = "FBA1FFE5-7CD6-451B-8F1F-22B2AC70AA45"; var major = 10; var minor = 12; var identifier = "KonyBeaconSample" var beaconRegion = new com.kony.BeaconRegion(proximityUUID, major, minor, identifier);
© 2015 by Kony, Inc. All rights reserved 201 of 848
Kony Studio API Developer's Guide
Version 5.0
2. Advertise the beacon information using the
Now that you have created a Beacon Region, you need to advertise your beacon’s proximity
UUID (and any major or minor value you specified) using the com.kony.PeripheralManager
object.
var peripheralManager = new com.kony.PeripheralManager
(stateUpdatedCallback, advertisingStatusCallback); peripheralManager.startAdvertisingWithMeasuredPower
(beaconRegion, null);
© 2015 by Kony, Inc. All rights reserved 202 of 848
Kony Studio API Developer's Guide
Version 5.0
9.3 com.kony.Beacon
You cannot create Beacon objects directly. Beacon objects are created by native platforms only.
The com.kony.Beacon class has the following methods: l
l
l
l
l
l
9.3.1 getAccuracy( )
The accuracy of the proximity value, measured in meters from the beacon.
Indicates the one sigma horizontal accuracy in meters. Use this property to differentiate between beacons with the same proximity value. Do not use it to identify a precise location for the beacon.
Accuracy values may fluctuate due to RF interference.
A negative value in this property signifies that the actual accuracy could not be determined. For more information, see Apple Documentation .
9.3.1.1 Signature
JavaScript : <<BeaconObject>>.getAccuracy()
Input Parameters
None
© 2015 by Kony, Inc. All rights reserved 203 of 848
Kony Studio API Developer's Guide
Version 5.0
9.3.1.2 Return Values
Number
Accuracy of the proximity value.
9.3.1.3 Platform Availability
Available only on iOS
9.3.1.4 JavaScript Example var beacon1 = new com.kony.Beacon();
...
var accuracy1 = beacon1.getAccuracy();
9.3.2 getMajor( )
The most significant value in the beacon. A major value, which is a number that can be used to group related beacons that have the same proximity UUID.
9.3.2.1 Signature
JavaScript: <<BeaconObject>>.getMajor()
9.3.2.2 Input Parameters
None
9.3.2.3 Return Values
Number
9.3.2.4 Platform Availability
Available only on iOS
© 2015 by Kony, Inc. All rights reserved 204 of 848
Kony Studio API Developer's Guide
Version 5.0
9.3.2.5 JavaScript Example var beacon1 = new com.kony.Beacon();
...
var major1 = beacon1.getMajor();
9.3.3 getMinor( )
The least significant value in the beacon. A minor value, which is a number that differentiates beacons with the same proximity UUID and major value.
9.3.3.1 Signature
JavaScript : <<BeaconObject>>.getMinor()
9.3.3.2 Input Parameters
None
9.3.3.3 Return Values
Number
9.3.3.4 Platform Availability
Available only on iOS
9.3.3.5 JavaScript Example var beacon1 = new com.kony.Beacon();
...
var minor1 = beacon1.getMinor();
© 2015 by Kony, Inc. All rights reserved 205 of 848
Kony Studio API Developer's Guide
Version 5.0
9.3.4 getProximity( )
The proximity value gives a general sense of the relative distance to the beacon. Use it to quickly identify beacons that are nearer to the user rather than farther away.
9.3.4.1 Signature
JavaScript: <<BeaconObject>>.getProximity()
9.3.4.2 Input Parameters
None
9.3.4.3 Return Values
String
A string can be any of the following values: l
BeaconProximityUnknown - The proximity of the beacon could not be determined.
l
BeaconProximityImmediate - The beacon is in the user’s immediate vicinity.
l
BeaconProximityNear - The beacon is relatively close to the user.
l
BeaconProximityFar - The beacon is far away.
9.3.4.4 Platform Availability
Available only on iOS
9.3.4.5 JavaScript Example var beacon1 = new com.kony.Beacon();
...
var proximity1 = beacon1.getProximity();
© 2015 by Kony, Inc. All rights reserved 206 of 848
Kony Studio API Developer's Guide
Version 5.0
9.3.5 getProximityUUIDString( )
The proximity UUID (string representation) of the beacon. A proximity UUID (universally unique identifier), which is a 128-bit value that uniquely identifies one or more beacons as a certain type or from a certain organization
9.3.5.1 Signature
JavaScript: <<BeaconObject>>.getProximityUUIDString()
9.3.5.2 Input Parameters
None
9.3.5.3 Return Values
String
Proximity UUID of the beacon.
9.3.5.4 Platform Availability
Available only on iOS
9.3.5.5 JavaScript Example var beacon1 = new com.kony.Beacon();
...
var proximityUUIDString1 = beacon1.getProximityUUIDString();
9.3.6 getrssi( )
The received signal strength of the beacon, measured in decibels. This value is the average RSSI value of the samples received since the range of the beacon was last reported to your app.
© 2015 by Kony, Inc. All rights reserved 207 of 848
9.3.6.1 Signature
JavaScript : <<BeaconObject>>.getrssi()
9.3.6.2 Input Parameters
None
9.3.6.3 Return Values
Number
9.3.6.4 Platform Availability
Available only on iOS
9.3.6.5 JavaScript Example var beacon1 = new com.kony.Beacon();
...
var rssi1 = beacon1.getrssi();
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 208 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4 com.kony.BeaconManager
BeaconManager is for managing iBeacons in iOS.
The com.kony.BeaconManager class has the following methods: l
l
getAuthorizationStatusChanged( )
l
l
l
isMonitoringAvailableForBeaconRegions( )
l
isRangingAvailableForBeaconRegions( )
l
l
setAuthorizationStatusChangedCallback( )
l
setMonitoringStartedForRegionCallback( )
l
startMonitoringBeaconRegion( )
l
startRangingBeaconsInRegion( )
l
l
Here is an example for creating a BeaconManager with callbacks: var aBeaconManager = new com.kony.BeaconManager(monitoringCallback, rangingCallback, errorCallback);
Input Parameters
© 2015 by Kony, Inc. All rights reserved 209 of 848
Kony Studio API Developer's Guide
Version 5.0
l monitoringCallback [Function] - Optional
To get monitoring beacon region updates from BeaconManager: o beaconRegion [Object] - com.kony.BeaconRegion - An object containing information about the region that was entered or exited.
o beaconRegionState [String] - Can represent one of the following strings: n
BeaconRegionStateUnknown - It is unknown whether the device is inside or outside of the region.
n
BeaconRegionStateInside - The device is inside the given region.
n
BeaconRegionStateOutside - The device is outside of the given region.
function monitoringCallback(beaconRegion, beaconRegionState)
{
} l rangingCallback [Function] - Optional
To get ranging updates from BeaconManager: o beaconRegion [Object] - com.kony.BeaconRegion - Object representing a Beacon
Region.
o beacons [Object Array] - com.kony.Beacon - An array of com.kony.Beacon objects representing the beacons currently in range (in the order of closest first). You can use the information in these objects to determine the range of each beacon and its identifying information.
function rangingCallback(beaconRegion, beacons) {
} l errorCallback [Function] - Optional
To get error updates from BeaconManager:
© 2015 by Kony, Inc. All rights reserved 210 of 848
Kony Studio API Developer's Guide
Version 5.0
o beaconManagerError [String] - Can represent one of the following strings: n
BeaconManagerMonitoringError - If an error occurs while trying to monitor a given region.
n
BeaconManagerRangingError - If the region object itself is invalid or if it contains invalid data.
n
BeaconManagerFailedError - The beacon manager was unable to retrieve a location value.
o errorName [String] - Name of the error.
o errorDictionary [Object] - Dictionary object.
o beaconRegion [Object] - com.kony.BeaconRegion.
function errorCallback(beaconManagerError, errorName, errorDictionary, beaconRegion) {
}
9.4.0.1 Return Values
Object - com.kony.BeaconManager
9.4.0.2 Platform Availability
Available only on iOS.
9.4.1 authorizationStatus( )
This API helps you know the authorization status of the location services for the application. The authorization status of a given application is managed by the system and determined by several factors. Applications must be explicitly authorized to use location services by the user, and location services must currently be enabled for the system. A request for user authorization is displayed automatically when your application first attempts to use location services.
© 2015 by Kony, Inc. All rights reserved 211 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.1.1 Signature
JavaScript : <<BeaconManagerObject>>.authorizationStatus()
Input Parameters
None
9.4.1.2 Return Values
String
Returns one of the following strings: l
BeaconManagerAuthorizationStatusNotDetermined - The user has not made a choice regarding whether this application can use location services.
l
BeaconManagerAuthorizationStatusRestricted - This application is not authorized to use location services. The user cannot change this application’s status, possibly due to active restrictions such as parental controls being in place.
l
BeaconManagerAuthorizationStatusDenied - The user explicitly denied the use of location services for this application or location services are currently disabled in Settings.
l
BeaconManagerAuthorizationStatusAuthorized - This application is authorized to use location services.
9.4.1.3 Platform Availability
Available only on iOS.
9.4.1.4 JavaScript Example var authorizationStatus1 = aBeaconManager.authorizationStatus();
© 2015 by Kony, Inc. All rights reserved 212 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.2 getMonitoredRegions( )
This API gets the Beacon Regions that are currently being monitored. You cannot add regions to this property directly. Instead, you must register regions by calling the
method.
9.4.2.1 Signature
JavaScript : <<BeaconManagerObject>>.getMonitoredRegions()
9.4.2.2 Input Parameters
None
9.4.2.3 Return Values
Array of com.kony.BeaconRegion objects
All the Beacon Regions that are being monitored by the BeaconManager.
9.4.2.4 Platform Availability
Available only on iOS.
9.4.2.5 JavaScript Example var monitoredRegions = aBeaconManager.getMonitoredRegions();
9.4.3 getRangedRegions( )
This API helps to get the Beacon Regions currently being ranged. The objects in the set are instances of the com.kony.BeaconRegion class.
9.4.3.1 Signature
JavaScript: <<BeaconManagerObject>>.getRangedRegions()
© 2015 by Kony, Inc. All rights reserved 213 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.3.2 Input Parameters
None
9.4.3.3 Return Values
Array of com.kony.BeaconRegion objects
All the Beacon Regions being ranged by the BeaconManager.
9.4.3.4 Platform Availability
Available only on iOS.
9.4.3.5 JavaScript Example var rangedRegions1 = aBeaconManager.getRangedRegions();
9.4.4 isMonitoringAvailableForBeaconRegions( )
This API helps to determine if the monitoring is available for Beacon Regions.
Note: The availability of region monitoring support is dependent on the hardware on the device.
This method does not consider the availability of location services or the fact that the user might have disabled them for the app or system. You must determine your app’s authorization status separately.
9.4.4.1 Signature
JavaScript : <<BeaconManagerObject>>.isMonitoringAvailableForBeaconRegions()
9.4.4.2 Input Parameters
None
© 2015 by Kony, Inc. All rights reserved 214 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.4.3 Return Values
Boolean
True, if it is available; false, if it is not available.
9.4.4.4 Platform Availability
Available only on iOS.
9.4.4.5 JavaScript Example var isMonitoringAvailableForBeaconRegions1 = aBeaconManager.isMonitoringAvailableForBeaconRegions();
9.4.5 isRangingAvailableForBeaconRegions( )
This API helps to determine if the ranging is available.
9.4.5.1 Signature
JavaScript : <<BeaconManagerObject>>.isRangingAvailableForBeaconRegions()
9.4.5.2 Input Parameters
None
9.4.5.3 Return Values
Boolean
True, if it is available; false, if it is not available.
9.4.5.4 Platform Availability
Available only on iOS.
© 2015 by Kony, Inc. All rights reserved 215 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.5.5 JavaScript Example var isRangingAvailableForBeaconRegions1 = aBeaconManager.isRangingAvailableForBeaconRegions();
9.4.6 requestStateForRegion( )
This API helps to determine the state of the current device relative to the Beacon Region. This method performs the request asynchronously and delivers the results through monitoringCallback.
9.4.6.1 Signature
JavaScript : <<BeaconManagerObject>>.requestStateForRegion()
9.4.6.2 Input Parameters beaconRegion
Mention the beacon region to know the state.
9.4.6.3 Return Values
None
9.4.6.4 Platform Availability
Available only on iOS.
9.4.6.5 JavaScript Example aBeaconManager.requestStateForRegion(beaconRegion);
9.4.7 setAuthorizationStatusChangedCallback( )
This API helps to set the authorization status changed callback.
© 2015 by Kony, Inc. All rights reserved 216 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.7.1 Signature
JavaScript : <<BeaconManagerObject>>.setAuthorizationStatusChangedCallback()
9.4.7.2 Input Parameters l authorizationStatusChanged [Function] o
Status [String] - either of the following strings are passed: n
BeaconManagerAuthorizationStatusNotDetermined - The user has not made a choice regarding whether this application can use location services.
n
BeaconManagerAuthorizationStatusRestricted - This application is not authorized to use location services. The user cannot change this application’s status, possibly due to active restrictions such as parental controls being in place.
n
BeaconManagerAuthorizationStatusDenied - The user explicitly denied the use of location services for this application or location services are currently disabled in
Settings.
n
BeaconManagerAuthorizationStatusAuthorized - This application is authorized to use location services.
function setAuthorizationStatusChangedCallback
(authorizationStatusChanged) {
} function authorizationStatusChanged(Status){
}
9.4.7.3 Return Values
None
9.4.7.4 Platform Availability
Available only on iOS.
© 2015 by Kony, Inc. All rights reserved 217 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.7.5 JavaScript Example aBeaconManager.setAuthorizationStatusChangedCallback
(authorizationStatusChanged);
9.4.8 setMonitoringStartedForRegionCallback( )
This API helps to set the monitoring started for region callback. This API informs the user though this callback that a new region is being monitored.
9.4.8.1 Signature
JavaScript : <<BeaconManagerObject>>.setMonitoringStartedForRegionCallback()
9.4.8.2 Input Parameters l monitoringStartedForRegionCallback [Function] beaconRegion [Object] - com.kony.BeaconRegion
function monitoringStartedForRegionCallback (Object){
}
9.4.8.3 Return Values
None
9.4.8.4 Platform Availability
Available only on iOS.
9.4.8.5 JavaScript Example aBeaconManager.setMonitoringStartedForRegionCallback
(monitoringStartedForRegionCallback);
© 2015 by Kony, Inc. All rights reserved 218 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.9 startMonitoringBeaconRegion( )
This API helps to start monitoring for the specified Beacon Region. You must call this method once for each region you want to monitor. If an existing region with the same identifier is already being monitored by the application, the old region is replaced by the new one. Region events are delivered through monitoringCallback. The errorCallback informs the user of any errors.
9.4.9.1 Signature
JavaScript : <<BeaconManagerObject>>.startMonitoringBeaconRegion()
9.4.9.2 Input Parameters beaconRegion [Object] - com.kony.BeaconRegion
Mention the Beacon Region to monitor.
9.4.9.3 Return Values
None
9.4.9.4 Platform Availability
Available only on iOS.
9.4.9.5 JavaScript Example aBeaconManager.startMonitoringBeaconRegion(beaconRegion);
9.4.10 startRangingBeaconsInRegion( )
This API helps to start ranging beacons in a specified Beacon Region.
© 2015 by Kony, Inc. All rights reserved 219 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.10.1 Signature
JavaScript : <<BeaconManagerObject>>.startRangingBeaconsInRegion()
9.4.10.2 Input Parameters beaconRegion - com.kony.BeaconRegion
A Beacon Region for ranging.
Note: Make this call once the region monitored state is "BeaconRegionStateInside."
9.4.10.3 Return Values
None
9.4.10.4 Platform Availability
Available only on iOS.
9.4.10.5 JavaScript Example aBeaconManager.startRangingBeaconsInRegion(beaconRegion);
9.4.11 stopMonitoringBeaconsRegion( )
This API stops the monitoring of a specified beacon region.
9.4.11.1 Signature
JavaScript : <<BeaconManagerObject>>.stopMonitoringBeaconRegion()
© 2015 by Kony, Inc. All rights reserved 220 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.11.2 Input Parameters beaconRegion
Mention the beacon region to stop ranging.
9.4.11.3 Return Values
None
9.4.11.4 Platform Availability
Available only on iOS.
9.4.11.5 JavaScript Example aBeaconManager.stopMonitoringBeaconsRegion(beaconRegion);
9.4.12 stopRangingBeaconsInRegion( )
This API helps to stop ranging beacons in a specified Beacon Region. If the specified region object is not currently being monitored, this method has no effect.
9.4.12.1 Signature
JavaScript : <<BeaconManagerObject>>.stopRangingBeaconsInRegion()
9.4.12.2 Input Parameters beaconRegion
Mention the Beacon Region to stop ranging. The beacon attributes should be the same object that you registered.
9.4.12.3 Return Values
None
© 2015 by Kony, Inc. All rights reserved 221 of 848
Kony Studio API Developer's Guide
Version 5.0
9.4.12.4 Platform Availability
Available only on iOS.
9.4.12.5 JavaScript Example aBeaconManager.stopRangingBeaconsInRegion(beaconRegion);
© 2015 by Kony, Inc. All rights reserved 222 of 848
Kony Studio API Developer's Guide
Version 5.0
9.5 com.kony.BeaconRegion
A Beacon Region object defines the type of region based on the device’s proximity to a Bluetooth beacon. A Beacon Region monitors for devices whose identifying information matches the information the user provides. If a device appears in range, the region triggers the delivery of an appropriate notification.
The com.kony.BeaconRegion class includes the following methods: l
l
l
l
getNotifyEntryStateOnDisplay( )
l
l
setNotifyEntryStateOnDisplay( )
Here is an example for creating a Beacon Region with callbacks: var BeaconRegion1= new com.kony.BeaconRegion(UUIDString1, major1, minor1, identifier1)
Input Parameters l proximityUUID [String] - contains the identifier that identifies your company’s beacons. You usually generate only one UUID for your company’s beacons but can generate more as needed. You can generate this value using the uuidgen command-line tool.
l major [Number] - property contains a value that groups related sets of beacons. For example, a bank can assign the same major value for all beacons on the same floor.
l minor [Number] - Optional
This property specifies the individual beacon within a group. For example, for a group of
© 2015 by Kony, Inc. All rights reserved 223 of 848
Kony Studio API Developer's Guide
Version 5.0
beacons on the same floor of a bank, this value can be assigned to a beacon in a particular section.
l identifier [String] - Optional
A unique identifier to associate with the Beacon Region object returned. Use this identifier to differentiate regions within your application. This value must not be null.
9.5.0.1 Return Values
Object - com.kony.BeaconRegion
9.5.0.2 Platform Availability
Available only on iOS.
9.5.1 getIdentifier( )
The getIdentifier() is an identifier for the region object. This is a value you specify and can use to identify a region inside your application.
9.5.1.1 Signature
JavaScript : <<BeaconRegionObject>>.getIdentifier()
9.5.1.2 Input Parameters
None
9.5.1.3 Return Values
String
9.5.1.4 Platform Availability
Available only on iOS.
© 2015 by Kony, Inc. All rights reserved 224 of 848
Kony Studio API Developer's Guide
Version 5.0
9.5.1.5 JavaScript Example var identifier1 = BeaconRegion1.getIdentifier();
9.5.2 getMajor( )
The getMajor() is a value identifying a group of beacons. This is a read-only value.
Note: If you do not specify a major value for the beacon, the value in this property is
nil
. When this property is
nil
, the major value of the beacon is ignored when determining if it is a match.
9.5.2.1 Signature
JavaScript : <<BeaconRegionObject>>.getMajor()
9.5.2.2 Input Parameters
None
9.5.2.3 Return Values
Number
9.5.2.4 Platform Availability
Available only on iOS.
9.5.2.5 JavaScript Example var major1 = BeaconRegion1.getMajor();
9.5.3 getMinor( )
The value identifying a specific beacon within a group.
© 2015 by Kony, Inc. All rights reserved 225 of 848
Kony Studio API Developer's Guide
Version 5.0
Note: If you do not specify a minor value for the beacon, the value in this property is
nil
. When this property is nil, the minor value of the beacon is ignored while determining if it is a match.
9.5.3.1 Signature
JavaScript : <<BeaconRegionObject>>.getMinor()
9.5.3.2 Input Parameters
None
9.5.3.3 Return Values
Number
9.5.3.4 Platform Availability
Available only on iOS.
9.5.3.5 JavaScript Example var minor1 = BeaconRegion1.getMinor();
9.5.4 getNotifyEntryStateOnDisplay( )
A Boolean indicating whether beacon notifications are sent when the device’s display is ON.
If set to YES, the location manager sends beacon notifications when the user turns on the display and the device is already inside the region. These notifications are sent even if your application is not running. In these situations, the system launches your application into the background so that it can handle the notifications.
Note: The default value for this property is NO.
© 2015 by Kony, Inc. All rights reserved 226 of 848
Kony Studio API Developer's Guide
Version 5.0
9.5.4.1 Signature
JavaScript : <<BeaconRegionObject>>.getNotifyEntryStateOnDisplay( )
9.5.4.2 Input Parameters
None
9.5.4.3 Return Values
Boolean
9.5.4.4 Platform Availability
Available only on iOS.
9.5.4.5 JavaScript Example var notifyEntryStateOnDisplay1 =
BeaconRegion1.getNotifyEntryStateOnDisplay();
9.5.5 getProximityUUIDString( )
The unique ID of the beacons being targeted. This is a read-only ID.
9.5.5.1 Signature
JavaScript : <<BeaconRegionObject>>.getProximityUUIDString( )
9.5.5.2 Return Values
String
9.5.5.3 Platform Availability
Available only on iOS.
© 2015 by Kony, Inc. All rights reserved 227 of 848
Kony Studio API Developer's Guide
Version 5.0
9.5.5.4 JavaScript Example var proximityUUIDString1 = BeaconRegion1.getProximityUUIDString();
9.5.6 setNotifyEntryStateOnDisplay( )
A Boolean indicating whether beacon notifications are sent when the device’s display is ON.
If set to TRUE, the location manager sends beacon notifications when the user turns on the display and the device is already inside the region. These notifications are sent even if your application is not running. In these situations, the system launches your application into the background so that it can handle the notifications.
Note: The default value for this property is FALSE.
9.5.6.1 Signature
JavaScript : <<BeaconRegionObject>>.setNotifyEntryStateOnDisplay()
9.5.6.2 Input Parameters
State [Boolean]
9.5.6.3 Return Values
None
9.5.6.4 Platform Availability
Available only on iOS.
9.5.6.5 JavaScript Example
BeaconRegion1.setNotifyEntryStateOnDisplay(true);
© 2015 by Kony, Inc. All rights reserved 228 of 848
Kony Studio API Developer's Guide
Version 5.0
9.6 com.kony.PeripheralManager
A Peripheral Manager object is used to manage published services within the local peripheral device’s
Generic Attribute Profile (GATT) database and to advertise these services to central devices. If a service is in the database, it is visible and can be accessed by any connected central. If your application does not have the specified Bluetooth-peripheral background mode, the contents of its services become disabled when it is in the background or in a suspended state. Any remote central trying to access the service’s characteristic value or characteristic descriptors receives an error.
Before you call Peripheral Manager methods, the state of the peripheral manager object must be powered ON, as indicated by the PeripheralManagerStatePoweredOn. This state indicates that the peripheral device (for example, your iPhone or iPad) supports Bluetooth low energy, and Bluetooth is switched ON and available to use. Peripheral Manager is used for turning iOS device into iBeacon.
The com.kony.PeripheralManager class has the following APIs: l
l
l
startAdvertisingWithMeasuredPower( )
l
Here is an example to create a new Peripheral Manager object.
var BeaconRegion1= new com.kony.PeripheralManager();
Here is an example to create a PeripheralManager with callbacks: var peripheralManager = new com.kony.PeripheralManager
(stateUpdatedCallback,advertisingStatusCallback);
© 2015 by Kony, Inc. All rights reserved 229 of 848
Kony Studio API Developer's Guide
Version 5.0
9.6.0.1 Input Parameters l stateUpdatedCallback [Function] - Optional
To get updated callback state from the Peripheral Manager o peripheralManagerState [String ] - Can represent one of the following values: n
PeripheralManagerStatePoweredOff - Indicates Bluetooth is currently powered off.
n
PeripheralManagerStatePoweredOn - Indicates Bluetooth is currently powered on.
n
PeripheralManagerStateResetting - The connection with the system service was momentarily lost. An update will occur.
n
PeripheralManagerStateUnauthorized - The app is not authorized to use the
Bluetooth low energy peripheral or server role.
n
PeripheralManagerStateUnknown - The current state of the peripheral manager is unknown. An update will occur.
n
PeripheralManagerStateUnsupported - The platform does not support the
Bluetooth low energy peripheral or server role.
function stateUpdatedCallback (peripheralManagerState){} l advertisingStatusCallback [Function] - Optional
To get the status callback of advertising from the Peripheral Manager.
o errorName [String] - Name of the error if error occurrs, null otherwise.
o errorInfo [Object] - Information about the error if error occurs, null otherwise.
function advertisingStatusCallback (errorName, errorInfo){}
© 2015 by Kony, Inc. All rights reserved 230 of 848
Kony Studio API Developer's Guide
Version 5.0
9.6.0.2 Return Values
Object - com.kony.PeripheralManager
9.6.0.3 Platform Availability
Available only on iOS.
9.6.1 authorizationStatus( )
The authorization status of an application is managed by the system and determined by several factors. Applications must be clearly authorized to share data using Bluetooth services while in the background state. The system automatically displays a request for user authorization when your app first attempts to use Bluetooth services to share data.
Calling this method does not prompt the user for access. Instead, you can use this method to detect restricted access and simply hide any affected UI features from the user.
9.6.1.1 Signature
JavaScript : <<PeripheralObject>>.authorizationStatus( )
9.6.1.2 Input Parameters
None
9.6.1.3 Return Values
String
Returns any one of the following values: l
PeripheralManagerAuthorizationStatusDetermined - The user has made a choice regarding whether this application can share data using Bluetooth services while in the background state.
© 2015 by Kony, Inc. All rights reserved 231 of 848
Kony Studio API Developer's Guide
Version 5.0
l
PeripheralManagerAuthorizationStatusRestricted - This application is not authorized to share data using Bluetooth services while in the background state. The user cannot change this application's status, possibly due to active restrictions such as parental controls.
l
PeripheralManagerAuthorizationStatusDenied - The user clearly denied this app from sharing data using Bluetooth services while in the background state.
l
PeripheralManagerAuthorizationStatusAuthorized - This application is authorized to share data using Bluetooth services while in the background state.
9.6.1.4 Platform Availability
Available only on iOS.
9.6.1.5 JavaScript Example var authorizationStatus1 = PeripheralManager1.authorizationStatus
();
9.6.2 isAdvertising( )
To determine if the Peripheral Manager is currently advertising data.
9.6.2.1 Signature
JavaScript : <<PeripheralObject>>.isAdvertising( )
9.6.2.2 Input Parameters
None
© 2015 by Kony, Inc. All rights reserved 232 of 848
Kony Studio API Developer's Guide
Version 5.0
9.6.2.3 Return Values
Boolean
9.6.2.4 Platform Availability
Available only on iOS.
9.6.2.5 JavaScript Example var isAdvertising1 = PeripheralManager1.isAdvertising();
9.6.3 startAdvertisingWithMeasuredPower()
Starts advertising beacon data with Measured Power.
9.6.3.1 Signature
JavaScript : <<PeripheralObject>>.startAdvertisingWithMeasuredPower()
9.6.3.2 Input Parameters l beaconRegion [Object] - com.kony.BeaconRegion
A Beacon Region whose data is to be advertised.
l measuredPower [Number] - Optional
The Received Signal Strength Indicator (RSSI) value (measured in decibels) for the device.
This value represents the measured strength of the beacon from one meter away and is used during ranging. Specify null to use the default value for the device.
9.6.3.3 Return Values
None
9.6.3.4 Platform Availability
Available only on iOS.
© 2015 by Kony, Inc. All rights reserved 233 of 848
Kony Studio API Developer's Guide
Version 5.0
9.6.3.5 JavaScript Example
PeripheralManager1.startAdvertisingWithMeasuredPower(beaconRegion, measuredPower);
9.6.4 stopAdvertising( )
Stops advertising Peripheral Manager data.
9.6.4.1 Signature
JavaScript : <<PeripheralObject>>.stopAdvertising( )
9.6.4.2 Input Parameters
None
9.6.4.3 Return Values
None
9.6.4.4 Platform Availability
Available only on iOS.
9.6.4.5 JavaScript Example var stopAdvertising1 = PeripheralManager1.stopAdvertising();
© 2015 by Kony, Inc. All rights reserved 234 of 848
10. Bookmark and Refresh APIs Kony Studio API Developer's Guide
Version 5.0
10. Bookmark and Refresh APIs
In Kony's current desktop architecture which is based on SPA, the URL of the page is never changed throughout the navigation of the application. This leads to a scenario where in if a user tries to bookmark a page, no matter where in the application the user is, the same URL is displayed. So subsequently when the user tries to open the bookmarked page, the desktop application has no way of knowing the actual bookmarked page and as a result, the user is invariably taken to the home page of the application.
An example of the URL in the desktop web application built on Kony would be: http://xyz.kony.com/kdw/#frm1
The same experience can be extended to other cases like refresh, sharing of a link etc. In all these scenarios, as there is no change in the URL, the user is by default taken to the home page of the application.
In the traditional desktop web application development, the developers create URLs with some context information so that when they are used, the URL carries necessary context and the application can change based on the context information and take the user to the appropriate page of the application instead of always redirecting them to the home page. Similar to this approach, Kony One
Platform provides the following set of APIs which enable the developer to add context to the URL so that when the end user bookmarks it or shares it, the URL carries necessary parameters so that the application is rendered accordingly.
Use Case Scenario
After signing into an application, if the user wants to stay in same page upon refresh, then the following code should be invoked in the App Service:
For example: function appServiceCallBack(params){
//alert(JSON.stringify(params)); if (params.launchparams['formID']) {
© 2015 by Kony, Inc. All rights reserved 235 of 848
10. Bookmark and Refresh APIs Kony Studio API Developer's Guide
Version 5.0
var formID = params.launchparams['formID']; return formID;
}
}
10.1 kony.application.setBMState
This API sets the bookmark state to the URL. This API accepts the formID and a json structure of key value pairs which will be added to the URL of the page.
10.1.1 Signature
JavaScript: kony.application.setBMState (
10.1.2 Input Parameters formID [String] - Mandatory.
Identifier of the form to be bookmarked.
state [JSON Object] - Mandatory
A JSON object comprising key value pairs. The key value pairs are user defined. You cannot specify this as a nested structure. i.e the value part can not be another JSON object.
10.1.3 Return Values
None.
10.1.4 Platform Availability
Supported for SPA and Desktop Web.
10.1.5 JavaScript Example
To set a bookmark for a URL, enter the following:
© 2015 by Kony, Inc. All rights reserved 236 of 848
10. Bookmark and Refresh APIs Kony Studio API Developer's Guide
Version 5.0
var state = {Bookmark : "about", text : "About"}; kony.application.setBMState ("form1", state)
10.2 kony.application.resetBMState
This API resets the state associated with the URL of a form. It removes all the parameters attached to the form URL
10.2.1 Signature
JavaScript: kony.application.resetBMState (
)
10.2.2 Input Parameters formID [String] - Mandatory.
Identifier of the form for which the parameters of the URL have to be removed.
10.2.3 Return Values
None.
10.2.4 Platform Availability
Supported for SPA and Desktop Web.
10.2.5 JavaScript Example
To reset a bookmark for a URL, enter the following: kony.application.resetBMState ("form1")
© 2015 by Kony, Inc. All rights reserved 237 of 848
10. Bookmark and Refresh APIs Kony Studio API Developer's Guide
Version 5.0
10.3 kony.application.addBMState
This API adds a specified key and value to the parameter list of the URL of the form.
10.3.1 Signature
JavaScript:
kony.application.addBMState ( formID
,
,
10.3.2 Input Parameters formID [String] - Mandatory.
Identifier of the form to be bookmarked.
key [String] - Mandatory
Key string representing the LHS of the parameter.
value [String] - Mandatory
Value string representing the RHS of the key-value combination. The value can not be a nested structure.
10.3.3 Return Values
None.
10.3.4 Platform Availability
Supported for SPA and Desktop Web.
10.3.5 JavaScript Example
To set a bookmark for a URL, enter the following: kony.application.addBMState ("form1", "About", "page2")
© 2015 by Kony, Inc. All rights reserved 238 of 848
10. Bookmark and Refresh APIs Kony Studio API Developer's Guide
Version 5.0
10.4 kony.application.removeBMState
This API removes a specified key from the parameter list of the URL of the form.
10.4.1 Signature
JavaScript: kony.application.removeBMState (
10.4.2 Input Parameters formID [String] - Mandatory.
Identifier of the form for which the parameters of the URL have to be removed.
key [String] - Mandatory
Key string representing the key to be removed.
10.4.3 Return Values
None.
10.4.4 Platform Availability
Supported for SPA and Desktop Web.
10.4.5 JavaScript Example
To remove a bookmark for a URL, enter the following: kony.application.removeBMState ("form1", "About")
10.5 kony.application.getBMState
This API retrieves the list of parameters attached to a URL using the above add, set APIs.
© 2015 by Kony, Inc. All rights reserved 239 of 848
10. Bookmark and Refresh APIs Kony Studio API Developer's Guide
Version 5.0
10.5.1 Signature
JavaScript: kony.application.getBMState (
10.5.2 Input Parameters formID [String] - Mandatory.
Identifier of the form for which the parameters of the URL have to be fetched.
10.5.3 Return Values
A json structure representing key-values of various parameters attached to the URL string of the given form.
10.5.4 Platform Availability
Supported for SPA and Desktop Web.
10.5.5 JavaScript Example
To fetch a list of parameters for a form, enter the following: kony.application.getBMState("form1")
© 2015 by Kony, Inc. All rights reserved 240 of 848
11. Camera API Kony Studio API Developer's Guide
Version 5.0
11. Camera API
When you capture an image using the Camera Widget, camera captures the rawbytes of the image.
This API allows you to delete rawbytes for the image. If you use this API, the captured image is deleted from the disk or in-memory.
The following APIs are explained in this chapter: l
You can view a video on using the Camera API at: http://docs.kony.com/video_ tutorials/default.htm#Camera.htm%3FTocPath%3D_____6 .
11.1 kony.camera.releaseRawBytes
This API enables you to delete rawbytes for the image. If you use this API, the captured image is deleted from the disk or in-memory.
The following are the important considerations for this API: l
Rawbytes once released using this API cannot be used or released again.
l
If multiple handles to the same rawbytes exist, and if you release the rawbytes using any of those handles, the other handles become obsolete.
11.1.1 Use Case
You can use this API to delete rawbytes of an image (captured from the camera) for memory management and better user experience so that the mobile application runs smoothly.
11.1.2 Signature
JavaScript: kony.camera.releaseRawBytes(
)
© 2015 by Kony, Inc. All rights reserved 241 of 848
11. Camera API Kony Studio API Developer's Guide
Version 5.0
11.1.3 Input Parameters rawBytes [Object] - Mandatory
Specifies the rawbytes of the image (captured from the camera) you want to release when the camera widget accessMode property is set as: l
CAMERA_IMAGE_ACCESS_MODE_PUBLIC: The captured image is stored on the device as a Image and is accessible to all the applications on the device.
l
CAMERA_IMAGE_ACCESS_MODE_PRIVATE: This is the default option for
Windows platform. The captured image is stored as an Image on the device and will not be accessible to any other application on the device and remain private to the application.
l
CAMERA_IMAGE_ACCESS_MODE_INMEMORY: The captured camera image is stored in memory and is never written to the disk.
11.1.4 Return Values
None
11.1.5 Best Practices
Scenario 1
If you try to release rawbytes that was already released, you will encounter an exception.
To avoid an exception, you must follow the following best practices to ensure that rawbytes are released properly:
1. Before releasing the rawbytes, ensure that the rawbytes handle is not null.
2. Assign null after releasing the rawbytes.
© 2015 by Kony, Inc. All rights reserved 242 of 848
11. Camera API Kony Studio API Developer's Guide
Version 5.0
11.1.6 JavaScript Example if( null != RawBytesHandle){ kony.camera.releaseRawBytes(RawBytesHandle)
RawBytesHandle = null
} else
//RawBytesHandle already released (or rawbytes not assigned to it)
Scenario 2
If you assign a handle to new rawbytes without releasing the rawbytes that the handle is currently pointing to, the access to the previous rawbytes is lost and will be released only at the time of application termination.
To avoid such a scenario, you must do the following:
1. Initialize the rawbytes handle to null before use.
2. Before assigning the rawbytes, ensure that the rawbytes handle is null.
11.1.7 JavaScript Example if( null == RawBytesHandle)
RawBytesHandle = cameraWidget.rawBytes
else
// RawBytesHandle not empty, release it and then use.
The following best practices ensure that rawbytes are properly treated and released.
1. Check if the rawbytes handle is not null before releasing.
2. Make sure to assign null after releasing rawbytes.
3. Initialize RawBytesHandle to null before use.
© 2015 by Kony, Inc. All rights reserved 243 of 848
11. Camera API Kony Studio API Developer's Guide
Version 5.0
4. Check if RawBytesHandle is not null, before assigning RawBytes.
11.1.8 Platform Availability
Available on all platforms except SPA.
11.1.9 JavaScript Example
//To delete the rawbytes captured by the camera widget cam1 in form
Frm1, enter the following: var imagetodel = frm1.cam1.rawBytes
kony.camera.releaseRawBytes(imagetodel) or kony.camera.releaseRawBytes(frm1.cam1.rawBytes)
© 2015 by Kony, Inc. All rights reserved 244 of 848
12. Charm Setting APIs Kony Studio API Developer's Guide
Version 5.0
12. Charm Setting APIs
The Charm settings on the Windows 8 platform contains settings that you can apply to the application.
The settings can be configured to control an application's access to system capabilities and some specific settings of the current application. To view the Charm settings pane, swipe from the right side of the screen from right to left. For more information about Charm settings, refer Charm Settings.
12.1 kony.application.createSettingsMenu
This API enables you to create a Charm settings menu for an application.
12.1.1 Signature
JavaScript: kony.application.createSettingsMenu (
,
© 2015 by Kony, Inc. All rights reserved 245 of 848
12. Charm Setting APIs Kony Studio API Developer's Guide
Version 5.0
12.1.2 Input Parameters id [String] - Mandatory.
Identifier of the Charm setting menu created.
menuSettings [Hash table] - Mandatory
The menuSettings hash table comprises the following key-value pairs: l id: ID of the Charm menu item.
l text: Name of the menu item.
12.1.3 Return Values
None.
12.1.4 Special Considerations
If a Charm setting menu is already created with the identifier passed, a new Charm setting menu will be created and the old Charm setting menu will be replaced with the new one. The same holds true for menu items as well.
At least one menu item must be present in the Charm settings menu created. A Charm settings menu with no menu items is invalid.
12.1.5 Platform Availability
Available on Windows 8.
12.1.6 JavaScript Example
To create a Charm settings menu, enter the following:
© 2015 by Kony, Inc. All rights reserved 246 of 848
12. Charm Setting APIs Kony Studio API Developer's Guide
Version 5.0
var settingsMenuItem1 = {id : "about", text : "About"}; var settingsMenuItem2 = {id : "help", text : "Help"}; var settingsMenu = [settingsMenuItem1, settingsMenuItem2]; kony.application.createSettingsMenu("mysettingsmenu", settingsMenu);
12.2 kony.application.setCurrentSettingsMenu
This method uses the unique identifier which represents the Charm settings menu and sets it as current settings menu. There can be only one current settings menu that can be set any time. Calling this method multiple times, replaces the current Charm settings menu.
12.2.1 Signature
JavaScript:
kony.application.setCurrentSettingsMenu ( id )
12.2.2 Input Parameters id [String] - Mandatory.
Identifier of the Charm setting menu to be set.
12.2.3 Return Values
None.
12.2.4 Platform Availability
Available on Windows 8.
12.2.5 JavaScript Example
To create a Charm settings menu, enter the following: kony.application.setCurrentSettingsMenu ("myMenu")
© 2015 by Kony, Inc. All rights reserved 247 of 848
12. Charm Setting APIs Kony Studio API Developer's Guide
Version 5.0
12.3 kony.application.getCurrentSettingsMenu
This method returns the unique identifier of the current menu that is set through getCurrentSettingsMenu.
12.3.1 Signature
JavaScript: kony.application.getCurrentSettingsMenu ()
12.3.2 Input Parameters
None
12.3.3 Return Values
Returns the unique identifier of the current menu that is set through getCurrentSettingsMenu.
12.3.4 Platform Availability
Available on Windows 8.
12.3.5 JavaScript Example
To get the unique identifier a Charm settings menu, enter the following: kony.application.getCurrentSettingsMenu ();
//Alert the Current Charm Settings menu alert("Current charm menu id is:: "+currCharmMenuId);
12.4 kony.application.addSettingsMenuItemAt
This API enables you to add a menu item at a given index in the Charm settings menu.
© 2015 by Kony, Inc. All rights reserved 248 of 848
12. Charm Setting APIs Kony Studio API Developer's Guide
Version 5.0
12.4.1 Signature
JavaScript: kony.application.addSettingsMenuItemAt (
,
)
12.4.2 Input Parameters id [String] - Mandatory.
Identifier of the Charm setting menu created.
index [Number] - Mandatory.
The index at which the menu item must be added. The index value lies between 0 and n-1. If the index is beyond the current length of the Charm menu items then the item is added to the end.
menuSettings [Hash table] - Mandatory
The menuSettings hash table comprises the following key-value pairs l id: ID of the Charm menu item.
l text: Name of the menu item.
l onClick: onclick event to be executed for the menu item.
12.4.3 Return Values
None.
12.4.4 Platform Availability
Available on Windows 8.
12.4.5 JavaScript Example
To add a menu item at a given index, enter the following:
© 2015 by Kony, Inc. All rights reserved 249 of 848
12. Charm Setting APIs Kony Studio API Developer's Guide
Version 5.0
//The below function is the callback function for onClickClosure event of app menu item with id "appmenuitemid3".
function onClickClosure3()
{
//proceed with the logic
} var settingsMenuItem1 = {id : "about", text : "About", onClick : onClickClosure3};
//Adding the above app menu item at the index 3.
kony.application.addSettingsMenuItemAt("accountMenu", 3, settingsMenuItem1);
12.5 kony.application.removeSettingsMenuItemAt
This API enables you to removes the specified App Menu item based on the index.
12.5.1 Signature
JavaScript:
kony.application.removeSettingsMenuItemAt ( id , index
)
12.5.2 Input Parameters id [String] - Mandatory.
Identifier of the Charm setting menu created.
index [Number] - Mandatory.
The index from which the menu item must be removed. The index value lies between 0 and n-1.
12.5.3 Return Values
None.
© 2015 by Kony, Inc. All rights reserved 250 of 848
12. Charm Setting APIs Kony Studio API Developer's Guide
Version 5.0
12.5.4 Platform Availability
Available on Windows 8.
12.5.5 JavaScript Example
To remove a menu item from a given index, enter the following:
//Removing a menu item from the index 3.
kony.application.removeSettingsMenuItemAt("charmmenu", 3);
© 2015 by Kony, Inc. All rights reserved 251 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13. Cryptography APIs
Cryptography is the process of securing the information. It can be defined as the conversion of data into scrambled text (concealing its readability and meaning) and deciphering it using a key. This data can be sent across safely over public and private networks.
When you have to transmit sensitive or critical information over the network (private or public), you need to encrypt the information to ensure information security. Decryption mechanism is used to convert the encrypted text into a readable format.
Note: Windows Phone 7 does not support TripleDES and RSA algorithms.
The following APIs are explained in this chapter: l
l
l
l
l
l
l
l
l
l
You can view a video on using Cryptography API at: Video Tutorial .
© 2015 by Kony, Inc. All rights reserved 252 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.1 Concepts
This section explains few concepts of Cryptography.
Encryption
Conversion of data into an encoded format using a key is known as encryption.
Decryption
Converting the encoded text into clear text using a key is known as decryption.
Note: Encryption and decryption are done using a cipher.
Cipher
Cipher is an object capable of carrying out encryption and decryption following a scheme
( algorithm).
Block Ciphers
A block cipher is a symmetric key cipher that operates on fixed-length groups of bits called blocks.
For example, a block cipher encryption algorithm takes a 128-bit block of plaintext as input, and produces an output of a corresponding 128-bit block of cipher text. The process of transformation is governed by a secret key. Decryption is a similar process - the decryption algorithm takes a 128bit block (in this example) of cipher text along with the secret key, and yields the original 128-bit block of plaintext.
Note: Kony Platform currently supports only Block Ciphers.
Stream Ciphers
A stream cipher, also called a stream algorithm, combines plaintext bits with a keystream. A keystream is a pseudorandom algorithm bit stream. Plaintext digits are encrypted one at a time.
© 2015 by Kony, Inc. All rights reserved 253 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Padding
Block cipher algorithms like DES mode require their input to be an exact multiple of the block size.
If the plaintext to be encrypted is not an exact multiple, you need to pad before encrypting by adding a padding string.
The following table describes the supported padding for different algorithms:
Algorithm
AES/TripleDES
RSA
Platform iPhone
Android/Android Tablet
BlackBerry
SPA iPhone
Android/Android Tablet
BlackBerry
Windows
Phone/Windows
8.1/Kiosk
Possible Padding pkcs7(default) none,pkcs1,pkcs5(default) none,pkcs5(default)
ISO10126, ISO97971, zeropaddding, nopadding, pkcs7 none,pkcs1(default) none,pkcs5,pkcs1(default) none,pkcs5,pkcs1(default) pkcs1
Mode
The modes specify how the data will be encrypted (cryptographically protected) and decrypted
(returned to original form). The modes included in this standard are: l
Electronic Codebook (ECB) mode l
Cipher Block Chaining (CBC) mode
© 2015 by Kony, Inc. All rights reserved 254 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
l
Cipher Feedback (CFB) mode l
Output Feedback (OFB) mode l
ECB and CBC are valid modes for the Block ciphers
The following table describes the supported modes for different algorithms:
Algorithm
AES/TripleDES
RSA iPhone
Platform
Android
BlackBerry
SPA iPhone
Android/Android Tablet
BlackBerry
Possible Modes ecb,cbc(default) ecb,cbc(default) ecb,cbc(default) ecb, cfb, ofb, cbc, ctr ecb(default) ecb(default) ecb(default)
Initialization Vector
The initialization vector (IV) adds randomness to the cipher text. As a result, if the same message is encrypted twice with the same key, the resulting cipher texts will be different, as long as different initialization vectors are used.
The length (number of bytes) of Initialization Vector should be the same as the block size of the algorithm (AES and TripleDES). For AES the IV has to be 16 bytes (128 bits). For TripleDES the
IV has to be 8 bytes (64 bits).
© 2015 by Kony, Inc. All rights reserved 255 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
RSA Algorithm
RSA is an algorithm for public-key cryptography. It is the first algorithm known for both signing and encryption. This algorithm involves a public key and a private key. The public key can be known to everyone and is used for encrypting messages. Messages encrypted with the public key can only be decrypted using the private key.
Note: SPA does not support the RSA algorithm.
13.2 Types of Cryptography
The following are the types of cryptography supported by Kony: l
Symmetric cryptography - cryptography that uses the same key for both encryption and decryption. Both encryption and decryption are done on the device.
l
Asymmetric cryptography - cryptography that uses a public key to encrypt data and a private key to decrypt data. The public key is available in a trusted certificate, whereas the private key is confidential and not shared. Encryption is done on the device and decryption on the server (that has access to the private key). As the private key is not exposed, we support only encryption using symmetric cryptography.
© 2015 by Kony, Inc. All rights reserved 256 of 848
13. Cryptography APIs
13.3 Supported Algorithms
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 257 of 848
13. Cryptography APIs
The following table lists the supported algorithms:
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 258 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Cryptography
Type
Algorithm
Symmetric l aes - Advanced Encryption Standard l tripledes - Triple Data Encryption Standard.
This algorithm uses two keys for encryption and one key for decryption . The algorithm works as follows:
encryptedtext = E
K3
(D
K2
(E
K1
(text to be encrypted)))
The text is encrypted with key1 , decrypted with key2 , and then again encrypted with key3 .
Decryption is the reverse:
decryptedtext = D
K3
(E
K2
(D
K1
(text to be decrypted)))
tripledes applies the DES cipher algorithm three times to each data block.
The following are the three different combinations of using this algorithm: o
Option 1: K1, K2, and K3 are different (all three keys are independent) o
Option 2: K1 and K2 are different; K3=K1
(two keys are independent) o Option 3: K1=K2=K3 (all three keys are identical)
Note: We recommend using Option 1 as it is more secured compared to the other two options.
© 2015 by Kony, Inc. All rights reserved
Supported Key
Strengths (in bits) l
128, 192, and 256 for aes algorithm l
192 for tripledes algorithm
259 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Cryptography
Type
Asymmetric
Algorithm l
RSA
Note: We currently support ONLY encryption (not decryption) using the asymmetric cryptography.
Supported Key
Strengths (in bits)
1024 and above
This chapter describes the following APIs: l
l
l
l
l
l
l
l
.
13.4 kony.crypto.newKey
This API allows you to create a key for cryptography using the specified algorithm. The key created using this API is used for encrypting clear text and decrypting the encrypted data.
13.4.1 Use Case
You can use this API to generate cryptographic keys when you want to transmit information in a secured manner over the private or public networks.
© 2015 by Kony, Inc. All rights reserved 260 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.4.2 Signature
JavaScript: kony.crypto.newKey(
,
13.4.3 Input Parameters algo [String] - Mandatory
Scheme using which the key is to be created. Possible values are: l securerandom - uses a secure random number as the scheme to generate a key. This scheme always produces a unique key.
l random - uses a random number as the scheme to generate a key. This scheme always produces a unique key.
Note: random and securerandom are supported only on iPhone.
Note: There is no differentiation between securerandom and random on Android and
BlackBerry platforms.
l passphrase - if this is the scheme, you need to pass the exact passphrase using which the key needs to be generated. The passphrasetext (an array of strings) is passed in the properties (JavaScript) parameter. The passphrase scheme always produces the same key for the same passphrase text.
Note: Only Passphrase is supported on SPA.
keystrength [Number] - Mandatory
Number of bits that indicate the key strength. If the subalgo is: aes - possible value is 128, 192, 256.
tripledes - possible value is 192.
© 2015 by Kony, Inc. All rights reserved 261 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Important: l tripledes Algorithm is not supported in Windows Platforms.
l
On iPhone platform, keystrength of 192 is supported only if the algorithm is random or securerandom. You cannot apply a passphrasehashalgo to the key when the algorithm is random or securerandom.
l tripledes - In Android and iOS, if the supplied key length is not equal to 192 an exception will be thrown with error message Invalid Keystrength and error code 104 .
Note: On BlackBerry, the passphrasetext length should be greater than or equal to keystrength 16 else an illegal exception occurs.
propertiesTable [Table] - Mandatory l passphrasetext [Array of Strings ]- the exact passphrase using which the key needs to be generated if the scheme is passphrase .
Note: This value in the table is mandatory only if the scheme is passphrase .
If the subalgo is aes, it contains a single string, whereas if the subalgo is tripledes, it contains three strings.
For example: o for aes , passphrasetext = {"inputstring1"} o for tripledes , passphrasetext = ["TestStr1","TestStr2","TestStr3"]
Note: passphrase should contain at least 3 characters (24 bytes), else the API throws an illegalargument exception.
© 2015 by Kony, Inc. All rights reserved 262 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Note: tripledes - in Android, if the passphrase length is less than 24 bytes or greater than 24 bytes an exception will be thrown with error message Invalid Keystrength and error code 104.
l subalgo - represents the key algorithm that is used to create the key. This is a mandatory parameter
(irrespective of the scheme). Possible values are: aes and tripledes .
l passphrasehashlogo - hashing algorithm to be applied for the passphrase text. (applicable only on iPhone).
Note: This value in the table is applicable only if the scheme is passphrase .
Possible values for the hash algorithm are: o md2 (for key strength of 128) o md4 (for key strength of 128) o md5 (for key strength of 128) o sha2 (for key strength of 256)
13.4.4 Return Values
The following are the return values for this API: key [userdata] - object
The key that is created using the specified algorithm.
13.4.5 API Usage
The recommended key strengths are as follows for this API: l aes - 128 l tripledes - 192.
© 2015 by Kony, Inc. All rights reserved 263 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.4.6 Platform Availability
Available on all platforms except J2ME.
13.4.7 Exceptions
CryptoError: Thrown by Crypto API.Various error conditions related to CryptoError will be covered through the following error codes.
l
2001 - unsupported algorithm.
l
2002 - invalid key strength specified.
l
2003 - insufficient buffer provided for specified operation.
l
2004 - memory allocation failure.
l
2005 - input data did not encode or encrypt properly .
l
2006 - specified name already exists.
l
2007 - key with the specified unique ID is not found.
Error
13.4.8 JavaScript Example var myEncryptionKey = kony.crypto.newKey("passphrase", 192 ,
{passphrasetext: ["TestStr1","TestStr2","TestStr3"],subalgo:
"tripledes"});
13.5 kony.crypto.encrypt
Converting data into an encoded format using a key is known as encryption. Encryption of data is done through symmetric cryptography. We support both symmetric and asymmetric encryption.
© 2015 by Kony, Inc. All rights reserved 264 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
This API provides the ability to encrypt the input text with the specified key and algorithm. The rawbytes of the encrypted text are returned.
13.5.1 Use Cases
You need to use encryption when you pass sensitive data like: l passwords l account numbers l account information l credit card information, and so on.
13.5.2 Signature
JavaScript: kony.crypto.encrypt(
,
)
13.5.3 Input Parameters algo [String] - Mandatory
Specifies the algorithm using which the input string needs to be encrypted.
Possible values are:
1. aes
2. tripledes
3. rsa
Important: l tripledes algorithm is not supported in Windows Platforms.
© 2015 by Kony, Inc. All rights reserved 265 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
generatedkey [Object] - Mandatory
The key to be used for encryption.
l
On Windows Phone and Kiosk, this parameter is the byte array that is returned in a call to kony.crypto.retrievePublicKey.
l
On Windows 8 this parameter is the name of the certificate that is included in the root directory of the Windows package, in “resources/common” in Kony Studio.
l
On all other platforms this API accepts the key generated using the kony.crypto.newKey API.
inputstring [String] - Mandatory
Data which needs to be encrypted.
propertiesTable [Table] - Mandatory
Note: This parameter is ignored in Windows 8.
This Object contains the following key-value pairs: l padding - a string that denotes the padding that needs to be applied.
Note: Windows Phone and Kiosk support pkcs and oeap padding.
l mode - a string that denotes the encryption mode.
Note: This value is ignored for the rsa algorithm.
l initializationvector - a string that denotes the Initialization Vector to be used.
Note: This parameter is applicable only if the subalgo is aes or tripledes.
© 2015 by Kony, Inc. All rights reserved 266 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.5.4 Return Values rawbytes [Object] - userdata
The rawbytes for the encrypted version of the input text.
13.5.5 Exceptions
CryptoError: Thrown by Crypto API.Various error conditions related to CryptoError will be covered through the following error codes.
l
2001 - unsupported algorithm.
l
2002 - invalid key strength specified.
l
2003 - insufficient buffer provided for specified operation.
l
2004 - memory allocation failure.
l
2005 - input data did not encode or encrypt properly .
l
2006 - specified name already exists.
l
2007 - key with the specified unique ID is not found.
Error
13.5.6 Platform Availability
Available on all platforms except J2ME.
13.5.7 JavaScript Example var algo="aes"; var encryptDecryptKey = kony.crypto.newKey("passphrase", 128,
{passphrasetext: ["inputstring1"], subalgo: "aes",
© 2015 by Kony, Inc. All rights reserved 267 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
passphrasehashalgo: "md5"}); var inputstr="pleaseencryptme"; var prptobj={padding:"pkcs5",mode:"cbc",initializationvector:
"1234567890123456"}; var myEncryptedText = kony.crypto.encrypt(algo,encryptDecryptKey, inputstr,prptobj);
13.5.7.1 Example for Windows Phone and Kiosk var algo="rsa"; var encryptDecryptKey = kony.crypto.retrievePublicKey
("rsa","sample.cer",true); var inputstr="pleaseencryptme"; var prptobj={padding:"pkcs1",mode:"ecb"}; var myEncryptedText = kony.crypto.encrypt
(algo,encryptDecryptKey,inputstr,prptobj); kony.print("********************************myEncryptedText is::****************************"); kony.print(myEncryptedText); alert ("Encrypted Text : " + myEncryptedText);
13.5.7.2 Example for Windows 8 var algo="rsa"; var inputstr="pleaseencryptme";
© 2015 by Kony, Inc. All rights reserved 268 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
var prptobj={padding:"",mode:""}; var myEncryptedText = kony.crypto.encrypt
(algo,”sample.cer”,inputstr,prptobj); kony.print("********************************myEncryptedText is::****************************"); kony.print(myEncryptedText); alert ("Encrypted Text : " + myEncryptedText);
13.6 kony.crypto.decrypt
This API provides the ability to decrypt the encrypted text with the specified key and algorithm. The
API returns the decrypted text.
13.6.1 Use Cases
You can use this API to decrypt secured data like: l passwords l account information l credit card information, and so on.
13.6.2 Signature
JavaScript: kony.crypto.decrypt(
generatedkey , encryptedRawbytes
,
13.6.3 Input Parameters algo [String] - Mandatory
Algorithm using which the encrypted text needs to be decrypted. Possible values are:
© 2015 by Kony, Inc. All rights reserved 269 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
l aes l tripledes
Important: l tripledes Algorithm is not supported in Windows Platforms.
generatedkey [Object] - Mandatory
The key to be used for decryption.
Note: As we currently support only symmetric decryption, we use the same key used for encryption.
encryptedRawbytes [Object] - Mandatory
The rawbytes of the encrypted text that need to be decrypted.
propertiesTable [Table] - Mandatory
This Object contains the following key-value pairs: l padding - a string that denotes the padding that needs to be applied.
Note: If padding is none, and the text length is less than the block size, the underlying platform throws a Bad Padding error.
Block size for different algorithms is as follows: l aes - 128 bits l tripledes - 64 bits l rsa - 1024 or 2048 bits l mode - a string that denotes the encryption mode.
l initializationvector - a string that denotes the IV to be used.
© 2015 by Kony, Inc. All rights reserved 270 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Note: This parameter is applicable only if the algorithm is aes or tripledes.
13.6.4 Return Values clearText [String]
The clear text decrypted from the encrypted rawbytes.
13.6.5 Exceptions
CryptoError: Thrown by Crypto API.Various error conditions related to CryptoError will be covered through the following error codes.
l
2001 - unsupported algorithm.
l
2002 - invalid key strength specified.
l
2003 - insufficient buffer provided for specified operation.
l
2004 - memory allocation failure.
l
2005 - input data did not encode or encrypt properly.
l
2006 - specified name already exists.
l
2007 - key with the specified unique ID is not found.
Error
13.6.6 Platform Availability
Available on all platforms except J2ME.
13.6.7 JavaScript Example var algo="aes";
© 2015 by Kony, Inc. All rights reserved 271 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
var encryptDecryptKey = kony.crypto.newKey("passphrase", 128,
{passphrasetext: ["inputstring1"], subalgo: "aes", passphrasehashalgo: "md5"}); var inputstr="pleaseencryptme"; var prptobj={padding:"pkcs5",mode:"cbc",initializationvector:
"1234567890123456"}; var myEncryptedText = kony.crypto.encrypt(algo,encryptDecryptKey, inputstr,prptobj); var myClearText = kony.crypto.decrypt(algo,encryptDecryptKey, myEncryptedText,prptobj);
13.7 kony.crypto.retrievePublicKey
Public Key Infrastructure (PKI) is the mechanism to secure the public networks (like Internet) to safely and securely transmit data with the use of keys. PKI assumes the use of public key cryptography
(
asymmetric cryptography ). PKI is the most common method to authenticate the message sender or
encrypt the message. PKI consists of a Certificate Authority (CA) that issues and verifies digital certificates (trusted certificates). A certificate includes the public key or information about the public key.
Note: Due to security reasons, Thin Client or Mobile Web applications cannot access public/private keys or certificates that are on the server.
This API provides the ability to extract the public key from a base64 string of encoded X509 certificate or a locally packaged X509 certificate.
13.7.1 Signature
JavaScript:
kony.crypto.retrievePublicKey( algo , inputsource
,
)
© 2015 by Kony, Inc. All rights reserved 272 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.7.2 Input Parameters algo [String] - Mandatory
The algorithm used for the public key. Possible values are: l
RSA l
AES - Supported only on Windows platforms.
inputsource [String] - Mandatory
This parameter indicates the name of the input source certificate from which the key needs to be retrieved.
Note: The certificate must be present in the resources folder.
islocalresource [Boolean] - Mandatory
This flag defines how the inputsource string needs to be interpreted.
l islocalresource is false - represents that the input source is base64 string of X509 certificate.
l islocalresource is true - represents that the input source is name of the local resource for the certificate. For example, public.cer.
13.7.3 Return Values publickey - userdata [Object]
The public key extracted from the certificate.
13.7.4 Rules and Restrictions l
Self-signed certificates are not supported on Android and BlackBerry platforms.
l iOS supports only Distinguished Encoding Rules (DER) representation of an X.509 certificate, when input source is certificate.
© 2015 by Kony, Inc. All rights reserved 273 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.7.5 Exceptions
CryptoError: Thrown by Crypto API.Various error conditions related to CryptoError will be covered through the following error codes.
l
2001 - unsupported algorithm.
l
2002 - invalid key strength specified.
l
2003 - insufficient buffer provided for specified operation.
l
2004 - memory allocation failure.
l
2005 - input data did not encode or encrypt properly.
l
2006 - specified name already exists.
l
2007 - key with the specified unique ID is not found.
Error
13.7.6 Platform Availability
Available on all platforms except J2ME, Windows 8 Tablet, Windows Kiosk, Service Side Mobile Web,
Desktop Web, and SPA.
13.7.7 JavaScript Example var myKey = kony.crypto.retrievePublicKey("rsa","public.cer",true);
13.8 kony.crypto.createHash
Hash value is a unique and compact numerical representation of a chunk of data.
© 2015 by Kony, Inc. All rights reserved 274 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
This API provides the ability to create a hash value in hexadecimal format for a given input string, using the specified algorithm.
13.8.1 Use Cases
You can use this API when you want to mask sensitive data with a numerical representation.
13.8.2 Signature
JavaScript:
kony.crypto.createHash( algo ,
13.8.3 Input Parameters algo [String] - Mandatory
Algorithm to be used for creating the hash value. Possible values are: l sha1 l sha224 l sha256 l sha384 l sha512 l md2 l md4 l md5
Important: l sha224, sha384,sha512, md2, md4,and md5 Algorithm are not supported in
Windows Platforms.
© 2015 by Kony, Inc. All rights reserved 275 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
inputstring [String] - Mandatory
Input string for which the hash value needs to be created.
13.8.4 Return Values hashValue [String]
Hash value created using the specified algorithm for the given input string. This string is in hexadecimal format. Length of the hashValue string in bytes is as follows (for each algorithm):
1. sha1
2. sha224
3. sha256
4. sha384
5. sha512
6. md2
7. md4
8. md5
For details about the digest length and hexa decimal string length, see the table given below.
Hashing
Algorithm sha1 sha224 sha256 sha384
32
48
Digest Length (in bytes)
20 40
Hexa Decimal String Length (in characters)
28 56
64
96
© 2015 by Kony, Inc. All rights reserved 276 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Hashing
Algorithm sha512 md2 md4 md5
16
16
16
Digest Length (in bytes)
64
Hexa Decimal String Length (in
128 characters)
32
32
32
13.8.5 Exceptions
CryptoError: Thrown by Crypto API.Various error conditions related to CryptoError will be covered through the following error codes.
l
2001 - unsupported algorithm.
l
2002 - invalid key strength specified.
l
2003 - insufficient buffer provided for specified operation.
l
2004 - memory allocation failure.
l
2005 - input data did not encode or encrypt properly.
l
2006 - specified name already exists.
l
2007 - key with the specified unique ID is not found.
Error
13.8.6 Platform Availability
Available on all platforms except J2ME and Windows Kiosk.
© 2015 by Kony, Inc. All rights reserved 277 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.8.7 JavaScript Example var algo="md5"; var inputstr="pleasecreatehash"; var myHashValue = kony.crypto.createHash(algo,inputstr);
13.9 kony.crypto.saveKey
This API allows you to save the generated key on the device store. If a key does not exist with the given name, the API creates a key; if a key exists with the given name, the API updates the same. The key is saved and a unique identifier is returned.
Note: Device store in case of iOS is Keychain. Keychain in iOS is the most secured place to store the crypto keys. saveKey and readKey APIs save and read from the Keychain. The Keychain can be shared between the applications provisioned and signed by the same certificate vendor.
Important: To avoid accidental overwrite of one application content by the other application content, it is recommended to use the unique application specific identifier while saving and reading the crypto keys using saveKey and readKey APIs.
13.9.1 Use Cases
To use the key at a later point of time for encryption and decryption.
13.9.2 Signature
JavaScript : kony.crypto.saveKey (
,
)
© 2015 by Kony, Inc. All rights reserved 278 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.9.3 Input Parameters name [String] - Mandatory
Unique name with which you want to save the key on the device store.
key [Object] - Mandatory
The key that you want to save on the device.
13.9.4 Return Values uniqueID [String]
The unique ID represents the saved key on the device store. We can access the key from the device store using this unique ID.
Note: UniqueID is determined by the system. It might be the same as name in some platforms but not guaranteed.
13.9.5 Exceptions
CryptoError: Thrown by Crypto API.Various error conditions related to CryptoError will be covered through the following error codes.
l
2001 - unsupported algorithm.
l
2002 - invalid key strength specified.
l
2003 - insufficient buffer provided for specified operation.
l
2004 - memory allocation failure.
l
2005 - input data did not encode or encrypt properly.
l
2006 - specified name already exists.
l
2007 - key with the specified unique ID is not found.
© 2015 by Kony, Inc. All rights reserved 279 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Error
13.9.6 API Usage
You can use this API to save the generated symmetric keys.
13.9.7 Platform Availability
Available on all platforms except J2ME and Windows Kiosk.
13.9.8 JavaScript Example var myEncryptionKey = kony.crypto.newKey("securerandom",256,
{subalgo:
"aes"}); var myUniqueKey = kony.crypto.saveKey("myKey",myEncryptionKey);
13.10 kony.crypto.readKey
This API provides you the ability to read the key from the device store.
Note: Device store in case of iOS is Keychain. Keychain in iOS is the most secured place to store the crypto keys. saveKey and readKey APIs save and read from the Keychain. The Keychain can be shared between the applications provisioned and signed by the same certificate vendor.
Important: To avoid accidental overwrite of one application content by the other application content, it is recommended to use the unique application specific identifier while saving and reading the crypto keys using saveKey and readKey APIs.
13.10.1 Use Cases
You can read the key from the device store if you want to use that key for encryption or decryption.
© 2015 by Kony, Inc. All rights reserved 280 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.10.2 Signature
JavaScript : kony.crypto.readKey(
)
13.10.3 Input Parameters uniqueID [String] - Mandatory
Unique ID represents the key on the device store (this is the ID returned by kony.crypto.saveKey
API).
13.10.4 Return Values
The following are the return values for this API: key [rawbytes - object]
This key is generated using aes, tripledes, or RSA algorithms and saved on the device store.
13.10.5 API Usage
You can use this API only to read the keys that you have saved earlier on the device store, i.e., keys that have a unique ID associated with them.
13.10.6 Exceptions
CryptoError: Thrown by Crypto API.Various error conditions related to CryptoError will be covered through the following error codes.
l
2001 - unsupported algorithm.
l
2002 - invalid key strength specified.
l
2003 - insufficient buffer provided for specified operation.
l
2004 - memory allocation failure.
l
2005 - input data did not encode or encrypt properly.
© 2015 by Kony, Inc. All rights reserved 281 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
l
2006 - specified name already exists.
l
2007 - key with the specified unique ID is not found.
Error
13.10.7 Platform Availability
Available on all platforms except J2ME and Windows Kiosk.
13.10.8 JavaScript Example var encryptDecryptKey = kony.crypto.newKey("passphrase", 128,
{passphrasetext: ["inputstring1"], subalgo: "aes", passphrasehashalgo: "md5"}); var myUniqueIDKey = kony.crypto.saveKey("myKey",encryptDecryptKey); var myCryptoKey = kony.crypto.readKey(myUniqueIDKey); alert(myCryptoKey);
13.11 kony.crypto.deleteKey
This API provides you the ability to delete a key from the device store.
13.11.1 Use Cases
You can delete the key from the device store if you are sure that you do not need that key anymore in the application.
13.11.2 Signature
JavaScript:kony.crypto.deleteKey(
)
© 2015 by Kony, Inc. All rights reserved 282 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.11.3 Input Parameters uniqueID [String] - Mandatory
Unique ID represents the key on the device store (this is the ID returned by kony.crypto.saveKey
API).
13.11.4 Return Values
None.
13.11.5 API Usage
You can use this API only to delete the keys that you have saved earlier on the device store,which is keys that have a unique ID associated with it.
13.11.6 Exceptions
CryptoError: Thrown by Crypto API.Various error conditions related to CryptoError will be covered through the following error codes.
l
2001 - unsupported algorithm.
l
2002 - invalid key strength specified.
l
2003 - insufficient buffer provided for specified operation.
l
2004 - memory allocation failure.
l
2005 - input data did not encode or encrypt properly.
l
2006 - specified name already exists.
l
2007 - key with the specified unique ID is not found.
Error
© 2015 by Kony, Inc. All rights reserved 283 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.11.7 Platform Availability
Available on all platforms except J2ME and Windows Kiosk.
13.11.8 JavaScript Example var encryptDecryptKey = kony.crypto.newKey("passphrase", 128,
{passphrasetext: ["inputstring1"], subalgo: "aes", passphrasehashalgo: "md5"}); var myUniqueIDKey = kony.crypto.saveKey("myKey",encryptDecryptKey); kony.crypto.deleteKey(myUniqueIDKey);
Note: You can use this API only to delete the keys that you have saved earlier on the device store, i.e., keys that have a unique ID associated with them.
13.12 kony.crypto.createPBKDF2Key()
Password-Based Key Derivation Function 2 (PBKDF2) is a key derivation function that generates encryption keys of different lengths to protect passwords.
PBKDF2 applies a hash function (chosen by algorithm input) to the input password or passphrase along with a salt value and repeats the process many times to produce a derived key, which is used as a cryptographic key in subsequent operations. The added computational work, or key stretching, makes it more difficult to crack a password.
This function uses a password in plain text, a salt value and iteration count, as inputs and generates a
PBKDF2 key using the supplied
© 2015 by Kony, Inc. All rights reserved 284 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.12.1 Signature var mySecureNewKey = kony.crypto.createPBKDF2Key
(algo, password, salt ,iteration, klen);
13.12.2 Input Parameters algo [String] - Mandatory
Hashing algorithm used for creating the key. Refer to
table for a list of supported algorithms in each platform.
password [String] - Mandatory
Master password from which a derived key is generated.
salt [String] - Mandatory
A random salt input string from a programmer iteration [Number] - Mandatory
The desired number of iterations klen [Number] - Optional
The klen is the desired length of the derived key in bits. If the key length is not specified, this value defaults to 256-bits.
Note: If klen key is used for encryption or decryption, a developer needs to make sure that this key length (klen) is supported by a corresponding encryption or decryption algorithm.
aes - possible values are 128, 192, and 256.
tripledes - possible value is 192.
13.12.3 Return Values
The following are the return values for this API:
© 2015 by Kony, Inc. All rights reserved 285 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
key [userdata] - object
The key created using the PBKDF2 algorithm.
13.12.4 Platform Availability
Available in iOS and Android
In Android, the Bundle OpenSSL Library option is available in Application Properties
> Native > Android section. If this option is selected, the OpenSSL library is bundled along with the application.
l
If the Bundle OpenSSL Library option is selected in Kony Studio, implementation in OpenSSL library is invoked.
l
If the Bundle OpenSSL Library option is not selected in Kony Studio, default Java implementation offered by the native Android platform is invoked.
Note: Supported hashing algorithms for each case are listed in the
table. If the device under testing does not support a user requested hashing algorithm, a corresponding error message is thrown by the API.
13.12.5 Exceptions
Common error codes and their descriptions follow: l
100 - Invalid Input parameters l
101 - Unsupported algorithm l
102 - Unknown error l
104 - Invalid key strength l
105 - Sub algorithm parameter is mandatory l
109 - The specified item could not be found
© 2015 by Kony, Inc. All rights reserved 286 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.12.6 JavaScript Example var mySecureNewKey = kony.crypto.createPBKDF2Key
("SHA1","password",”salt”,1000,256); kony.print("mySecureNewKey :" + mySecureNewKey);
13.12.7 Supported Algorithms
The following table lists algorithms supported for a specific platform.
Platform Name
Android Default Implementation
Android OpenSSL Implementation (Bundle
Open SSL Library option is selected in Kony
Studio) iOS
Supported Algorithms
SHA1
MD5, SHA1, SHA224, SHA256, SHA384, SHA512
SHA1 , SHA224, SHA256, SHA384, SHA512
13.13 kony.crypto.createHMacHash()
HMAC (Hash-based Message Authentication Code) uses a cryptographic key along with a user selected hash function to generate a MAC (Message Authentication Code).
The purpose of this API is to return Hash value of a given message. The cryptographic strength of the
HMAC depends upon the cryptographic strength of the underlying hash function, the size of its hash output, and on the size and quality of the key.
13.13.1 Signature var myHash = kony.crypto.createHMacHash(algo, key, message);
© 2015 by Kony, Inc. All rights reserved 287 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
13.13.2 Input Parameters algo [String] - Mandatory
Hashing algorithm used to create for creating the hash value. Refer to
table for a list of supported algorithms in each platform.
key [String] - Mandatory
Input key to algorithm.
message [String] - Mandatory
Plain text for which hash needs to be generated.
13.13.3 Return Values hashValue [String]
Hash value created using the specified algorithm for the given input string. This string is in a hexadecimal format. For details about the digest length and hexadecimal string length, refer to the
Hash lengths table under the CreateHash API
section.
13.13.4 Platform Availability
Available in iOS and Android
In Android, the Bundle OpenSSL Library option is available in Application Properties
> Native > Android section. If this option is selected, OpenSSL library is bundled along with the application.
l
If the Bundle OpenSSL Library option is selected in Kony Studio, the implementation in
OpenSSL library is invoked.
l
If the Bundle OpenSSL Library option is not selected in Kony Studio, the default Java implementation offered by native Android platform is invoked.
© 2015 by Kony, Inc. All rights reserved 288 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Note: Supported hashing algorithms for each case are listed in the
table. If the device under testing does not support a user requested hashing algorithm, a corresponding error message will be thrown by the API.
13.13.5 Exceptions
Common error codes and their descriptions follow: l
100 - Invalid input parameters l
101 - Unsupported algorithm l
102 - Unknown error l
104 - Invalid key strength l
105 - Sub algorithm parameter is mandatory l
109 - The specified item could not be found
13.13.6 JavaScript Example var myHash = kony.crypto.createHMacHash("SHA1","key1","test message to generate hash"); kony.print("myHash :" + myHash);
13.13.7 Supported Algorithms
The following table lists algorithms supported for a specific platform.
Platform Name
Android Default Implementation
Supported Algorithms
MD5, SHA1, SHA224, SHA256, SHA384, SHA512 (
SHA224 supported only on API level 21 and above)
© 2015 by Kony, Inc. All rights reserved 289 of 848
13. Cryptography APIs Kony Studio API Developer's Guide
Version 5.0
Platform Name
Android OpenSSL Implementation (Bundle
OpenSSL Library option is selected in
Kony Studio) iOS
Supported Algorithms
MD5, SHA1, SHA224, SHA256, SHA384, SHA512
MD5,SHA1,SHA224,SHA256,SHA384,SHA512
© 2015 by Kony, Inc. All rights reserved 290 of 848
14. Modules APIs Kony Studio API Developer's Guide
Version 5.0
14. Modules APIs
The Functional Modules APIs are used to load a functional module (that is defined using
functionalModule.xml
file) through synchronous and asynchronous operations on demand.
14.1 loadFunctionalModule
loadFunctionalModule is a synchronous API used to load functional module (views and jsModules) in scope of JavaScript. Until loading of module is complete, further executions will be stopped.
14.1.1 Signature
JavaScript: kony.modules.loadFunctionalModule (
14.1.2 Parameters modulename [String] - Mandatory
Unique module name that is defined in the
functionalModules.xml
file.
Note: If the module is already loaded, then it returns true without reloading the same module.
14.1.3 Return Values
Boolean true: When module is loaded.
false: When any issue found while loading.
14.1.4 Platform Availability
Available on iOS, Android, Windows, SPA and Desktop Web
© 2015 by Kony, Inc. All rights reserved 291 of 848
14. Modules APIs Kony Studio API Developer's Guide
Version 5.0
14.1.5 JavaScript Example
//In module1 you can load module2 as below when required.
function buttonClick() { kony.modules.loadFunctionalModule("module2");
//Now we cn access objects defined in module2 frmLogin.show();
}
14.2 loadFunctionalModuleAsync
The loadFunctionalModuleAsync is an asynchronous API used to load functional module (views and jsModules) in scope of JavaScript. A success callback is invoked after successful completions of load, else error callback will be invoked.
Note: If the module is already loaded, then it will call successcallback without loading the same module.
14.2.1 Signature
JavaScript: kony.modules.loadFunctionalModuleAsync (
,
,
14.2.2 Parameters modulename [String] - Mandatory
Unique name of the module that is defined in the
functionalModules.xml
file.
successcallback [Function] - Mandatory
The callback will be invoked after successful load of module files and after calling corresponding init function, if defined.
© 2015 by Kony, Inc. All rights reserved 292 of 848
14. Modules APIs Kony Studio API Developer's Guide
Version 5.0
l successcallback (modulename) errorcallback [Function] - Mandatory
The callback which will be invoked if there are any issue while loading module files.
l errorcallback (modulename, errorcode)
14.2.3 Error Codes
1250 – Invalid module name is specified.
1251 – Unable to load module.
14.2.4 Platform Availability
Available on iOS, Android, Windows, SPA and Desktop Web.
14.2.5 JavaScript Example
//In module1 you can load module2 as below when required.
var successcalback = function (modulename) {
//Now we cn access objects defined in module2 frmLogin.show();
} var errorcalback = function (modulename, errorcode) { kony.print("error : " + errorcode + " in module - " + modulename);
} function buttonClick() { kony.modules.loadFunctionalModuleAsync("module2", successcalback, errorcalback);
}
© 2015 by Kony, Inc. All rights reserved 293 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
15. GeoLocation APIs
The GeoLocation APIs define a high-level interface to location information, such as latitude and longitude associated with the mobile device. The API uses the common sources of location information like Global Positioning System (GPS) to infer details like IP address, RFID, WiFi and
Bluetooth MAC addresses, and GSM/CDMA cell IDs. This API does not always return the device's actual location.
The API is designed to enable both one-shot position requests and repeated position updates, as well as the ability to explicitly query the cached positions. Location information is represented by latitude and longitude coordinates.
The GeoLocation APIs are modeled after W3C GeoLocation specification.
Important: If you are developing a BlackBerry 10 application, you must provide access permission in Kony Studio IDE. To provide permission, go to Preferences > Native > BlackBerry 10 and enable access_location_services.
The following are the Geolocation APIs: l
kony.location.getCurrentPosition
l
l
You can view a video on using Geolocation API at: http://docs.kony.com/video_ tutorials/default.htm#GeoLocation.htm%3FTocPath%3D_____14 .
15.1 kony.location.getCurrentPosition
This API takes one, two, or three arguments. When invoked, it must immediately return and then asynchronously attempt to obtain the current location of the device. If the attempt is successful, the successCallback is invoked (i.e. the handleEvent operation must be called on the callback object) with a new Position object, reflecting the current location of the device. If the attempt fails, the errorCallback
© 2015 by Kony, Inc. All rights reserved 294 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
is invoked with a new PositionError object, reflecting the reason for the failure.
15.1.1 Signature
JavaScript: kony.location.getCurrentPosition(
errorcallback , positionoptions
)
15.1.2 Input Parameters successcallback [Function] - Mandatory
Specifies the callback function that must be executed when the API call is successful. The signature of the callback function is successcallback(position) where position contains the coordinates of the geo-location that are created and returned by the API. It is an object that has the following key-value pairs: l coords [Object] - coordinates that has the following key-value pairs: o latitude [Number] - latitude in decimal degrees.
o longitude [Number] - longitude in decimal degrees.
o altitude [Number] - height of the location in meters above the ellipsoid.
o accuracy [Number] - Accuracy level of the latitude and longitude coordinates in meters.
o altitudeaccuracy [Number] - Accuracy level of the altitude coordinate in meters.
o heading [Number] - Direction of travel, specified in degrees counting clockwise relative to the true north.
o speeding [Number] - Current ground speed of the device, specified in meters per second.
o timestamp [Number] - represents the time when the Position object was acquired.
© 2015 by Kony, Inc. All rights reserved 295 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
errorcallback [Function] - Optional
Specifies the callback function that must be executed when the API call fails. The callback function has the following signature: errorcallback(positionerror)- positionerror is an object that has the following key-value pairs: l code [Number] - the error code.
l message [String] - the error message. The following are the pre-defined messages: o
PERMISSION_DENIED o
POSITION_UNAVAILABLE o TIMEOUT positionoptions [Object] - Optional
Using this parameter, the user can customize the retrieval of the geolocation. It is an object that has the following key-value pairs: enableHighAccuracy [Boolean] - provides a hint to the implementation in order to receive the best possible result.
timeout [Number] - denotes the maximum length of time in milliseconds that is allowed to pass from the call.
maximumAge [Number] - indicates the application to accept a cached position whose age is no greater than the specified time in milliseconds.
15.1.3 Return Values:
None.
© 2015 by Kony, Inc. All rights reserved 296 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
15.1.4 Exceptions
LocationError
Error
15.1.5 JavaScript Example function successcallback(position)
{ var geoPosition = "Latitude: " + position.coords.latitude; geoPosition = geoPosition + " Longitude: " + position.coords.longitude; geoPosition = geoPosition + " Altitude: " + position.coords.altitude; geoPosition = geoPosition + " Accuracy: " + position.coords.accuracy; geoPosition = geoPosition + " Altitude Accuracy: "
+ position.coords.altitudeAccuracy; geoPosition = geoPosition + " Heading: " + position.coords.heading; geoPosition = geoPosition + " Speeding: " + position.coords.speeding; geoPosition = geoPosition + " Timestamp: " + position.timestamp; alert(geoPosition);
} function errorcallback(positionerror)
{ var errorMesg = "Error code: " + positionerror.code; errorMesg = errorMesg + " message: " + positionerror.message
alert(errorMesg);
} var positionoptions = {timeout: 15000}; // 15 secs
© 2015 by Kony, Inc. All rights reserved 297 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
kony.location.getCurrentPosition(successcallback, errorcallback, positionoptions );
15.1.6 Platform Availability
Available on all platforms except Windows 7 Kiosk and prior to IE8 releases.
15.2 kony.location.watchPosition
This API takes one, two, or three arguments. When invoked, it must immediately return a number that uniquely identifies a watch operation and then asynchronously start the watch operation. This operation first attempts to obtain the current location of the device. If the attempt is successful, the succesCallback is invoked (i.e. the handleEvent operation must be called on the callback object) with a new Position object, reflecting the current location of the device. If the attempt fails, the errorCallback is invoked with a new PositionError object, reflecting the reason for the failure.
The watch operation continues to monitor the position of the device and invokes the appropriate callback every time this position changes. The watch operation continues until the clearwatch method is called with the corresponding identifier.
15.2.1 Signature
JavaScript: kony.location.watchPosition(
)
15.2.2 Input Parameters successcallback [Function] - Mandatory
Specifies the callback function that must be executed when the API call is successful. The signature of the callback function is successcallback(position) where position contains the coordinates of the geolocation that are created and returned by the API. It is an object that has the following key-value pairs: l coords [Object] - coordinates that has the following key-value pairs:
© 2015 by Kony, Inc. All rights reserved 298 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
o latitude [Number] - latitude in decimal degrees.
o longitude [Number] - longitude in decimal degrees.
o altitude [Number] - height of the location in meters above the ellipsoid.
o accuracy [Number] - Accuracy level of the latitude and longitude coordinates in meters.
o altitudeaccuracy [Number] - Accuracy level of the altitude coordinate in meters.
o heading [Number] - Direction of travel, specified in degrees counting clockwise relative to the true north.
o speeding [Number] - Current ground speed of the device, specified in meters per second.
o timestamp [Number] - represents the time when the Position object was acquired.
l timestamp [Number] - represents the time when the Position object was acquired.
errorcallback [Function] - Optional
Specifies the callback function that must be executed when the API call fails. The callback function has the following signature: errorcallback(positionerror): Positionerror is an Object that has the following key-value pairs: l code [Number] - the error code. //TBD.
l message [String] - the error message. The following are pre-defined messages: o
PERMISSION_DENIED o
POSITION_UNAVAILABLE o
TIMEOUT
© 2015 by Kony, Inc. All rights reserved 299 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
positionoptions [Object] - Optional
Using this parameter, the user can customize the retrieval of the geolocation. It is an Object that has the following key-value pairs: l enableHighAccuracy [Boolean] - provides a hint to the implementation in order to receive the best possible result.
l timeout [Number] - denotes the maximum length of time in milliseconds that is allowed to pass from the call.
l maximumAge [Number] - indicates the application to accept a cached position whose age is no greater than the specified time in milliseconds.
15.2.3 Return Values watchID [Number]
Returns a number that denotes the unique ID of the watch operation.
15.2.4 Exceptions:
LocationError
Error
15.2.5 JavaScript Example function successcallback1(position)
{ lblTest.text = "working with watchPosition success full call back"; var geoPosition = "Latitude: " + position.coords.latitude; geoPosition = geoPosition + " Longitude: " + position.coords.longitude; geoPosition = geoPosition + " Altitude: " + position.coords.altitude; geoPosition = geoPosition + " Accuracy: " +
© 2015 by Kony, Inc. All rights reserved 300 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
position.coords.accuracy; geoPosition = geoPosition + " Altitude Accuracy: " + position.coords.altitudeAccuracy; geoPosition = geoPosition + " Heading: " + position.coords.heading; geoPosition = geoPosition + " Speed: " + position.coords.speed; geoPosition = geoPosition + " Timestamp: " + position.timestamp; alert(geoPosition);
} function errorcallback1(positionerror)
{ lblTest.text = "working with watchPosition err call back"; var errorMesg = "Error code: " + positionerror.code; errorMesg = errorMesg + " message: " + positionerror.message
alert(errorMesg);
} var positionoptions = {maximumAge: 3000}; watchID = kony.location.watchPosition (successcallback1, errorcallback1, positionoptions)
15.2.6 Platform Availability
Available on all platforms except Desktop Web, Windows 7 Kiosk, IE8 and prior to IE8 releases.
*Dummy Implementation on Mobile Web.
15.3 kony.location.clearWatch
This API takes one argument. When invoked, it must first check the value of the given watchID argument. If this value does not correspond to any previously started watch process, then the method must return immediately without performing any further action. Otherwise, the watch process identified by the watchID argument must be immediately stopped and no further callbacks must be
© 2015 by Kony, Inc. All rights reserved 301 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
invoked.
15.3.1 Signature
JavaScript: kony.location.clearWatch(
)
15.3.2 Input Parameters watchID [Number] - Mandatory
Specifies the number that uniquely identifies the watch.
15.3.3 Return Values
None.
15.3.4 Exceptions
LocationError
Error
15.3.5 JavaScript Example kony.location.clearWatch(watchID);
15.3.6 Platform Availability
Available on all platforms except Desktop Web and Windows 7 Kiosk. *Dummy Implementation on
Mobile Web.
15.4 Deprecated APIs
This section lists all the deprecated APIs
© 2015 by Kony, Inc. All rights reserved 302 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
15.4.1 phone.mylocation
This API is deprecated from Kony Studio 4.0 release onwards. As an alternate, to capture the location details use the
geolocation.getcurrentposition
API.
This API provides you with the ability to capture the current location of the user based on the Global
Positioning System (GPS) and Location Based Services (LBS) capabilities.
15.4.1.1 Use Case
You can use this API to: l pre-populate your current location details in applications like Flight Search or Hotel Search.
l identify outlets like Shopping Mall, Gas Station, ATM, and so on nearest to your current location.
15.4.1.2 Signature
JavaScript: phone.mylocation()
15.4.1.3 Input Parameters
This API does not require any input parameters.
15.4.1.4 Return Values
Reference [userdata]
Contains three keys: cellular ID longitude latitude
Status [Number]
Status can be one of the following:
© 2015 by Kony, Inc. All rights reserved 303 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
0: Success in finding the location
-1: Unable to find the location
15.4.1.5 Error Codes
The following error codes are returned:
Error Code
101
Description
Network Related Error
102
103
104
105
Location API access is denied by user
Unknown location or Location not found
Unknown error
Location Services Disabled
15.4.1.6 Implementation Details
To fetch location details on Mobile Web, enable the Requires GPS property of a project and set the
CaptureGPS property to true. For more information about capturing location details on Mobile Web, see the appendix GPS Functionality in Kony Studio User Guide.
This API does not fetch data if it is used in the
appinit
event or on the first call of
form.preshow
API.
15.4.1.7 Rules and Restrictions l
On Mobile Web, this API is available on: o iPhone o
Android
© 2015 by Kony, Inc. All rights reserved 304 of 848
15. GeoLocation APIs Kony Studio API Developer's Guide
Version 5.0
o
BlackBerry Torch o other HTML5 browsers.
l
You cannot test this API from Windows Phone Mango emulator as with current release of
WP7.0
cellular ID cannot be retrieved.
15.4.2 Platform Availability
Available on all platforms except IE8 and prior to IE8 releases.
Available on all platforms except prior to IE8 releases.
© 2015 by Kony, Inc. All rights reserved 305 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
16. Gesture APIs
A gesture is an action associated with movement of a mouse or a touch screen action. The developers determine how a gesture should be interpreted and the function that must be executed when a gesture is recognized.
Gestures are applicable only on mobile or tablet devices that have touch support.
Note: l
Currently, Kony Platform supports only Tap, Swipe, Longpress, Pan, Rotation, and Pinch gesture types. l
In tablet, longpress is only triggered when it is a touch event and not a mouse event.
The gesture APIs in this chapter are as follows: l
l
l
addGestureRecognizerForAllForms
l
removeGestureRecognizerForAllForms
16.1 Important Considerations
l
Single tap matches with the onClick functionality. If a box has an onClick event defined, both gesture event and onClick are triggered.
l
Number of taps is limited to one or two, only single tap or double tap are recognized.
l
Number of fingers is limited to one, only single finger is recognized.
© 2015 by Kony, Inc. All rights reserved 306 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
16.2 addGestureRecognizer
This API allows you to set a gesture recognizer for a specified gesture for a specified widget.
16.2.1 Signature addGestureRecognizer(
,
,
16.2.2 Input Parameters gestureType [Number] - Mandatory
Indicates the type of gesture to be detected on the widget. The following are possible values: l
1 – constants.GESTURE_TYPE_TAP
l
2 - constants.GESTURE_TYPE_SWIPE
l
3 – constants.GESTURE_TYPE_LONGPRESS
l
4 – constants.GESTURE_TYPE_PAN
l
5 – constants.GESTURE_TYPE_ROTATION
l
6 - constants.GESTURE_TYPE_PINCH
l
7 - constants.GESTURE_TYPE_RIGHTTAP
Note: l
RIGHTTAP applicable only to Windows 8.1 and Windows Desktop/Kiosk platforms.
l
ROTATION is not supported on Android.
© 2015 by Kony, Inc. All rights reserved 307 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
gestureConfigParams [object] - Mandatory
Specifies a table that has the configuration parameters needed to setup a gesture recognizer. The configuration parameters vary based on the type of the gesture.
This parameter has the following key-value pairs:
Gesture Type: TAP l fingers [Number] - specifies the maximum number of fingers that must be respected for a gesture. Possible values are: 1. Default value is 1.
l taps [Number] - specifies the maximum number of taps that must be respected for a gesture. Possible values are: 1 or 2. Default value is 1.
For example,{fingers:1,taps:1}
Gesture Type: SWIPE l fingers [Number] - specifies the maximum number of fingers that must be respected for a gesture. Possible values are: 1. Default value is 1.
For example, {fingers: 1}.
Gesture Type : LONGPRESS l pressDuration [Number] - specifies the minimum time interval (in seconds) after which the gesture is recognized as a LONGPRESS. This is not applicable to
Windows.
For example, if the pressDuration is 2 seconds, any continued press is recognized as LONGPRESS only if it lasts for at least 2 seconds. Default value is 1.
For example, {pressDuration=1}.
Note: LONGPRESS event is not supported in SPA (Windows Phone) platform.
© 2015 by Kony, Inc. All rights reserved 308 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
Gesture Type : PAN l fingers [number] specifies the minimum number of fingers needed to recognize this gesture. Default value is 1.
l continuousEvents [Boolean] indicates if callback should be called continuously for every change beginning from the time the gesture is recognized to the time it ends.
Gesture Type : ROTATION l
Rotation gesture involves only two fingers.
l continuousEvents [Boolean] indicates if callback must be called continuously for every change beginning from the time the gesture is recognized to the time it ends.
Gesture Type : PINCH l
Pinch gesture invloves two fingures.
l continuousEvents [Boolean] indicates if callback should be called continuously every change beginning from the time the gesture is recognized to the time it ends.
onGestureClosure [function] - Mandatory
Specifies the function that needs to be executed when a gesture is recognized. This function will be raised asynchronously and has the following signature: onGestureClosure(widgetRef, gestureInfo, context) l widgetRef - specifies the handle to the widget on which the gesture was recognized.
l gestureInfo - Table with information about the gesture. The contents of this table vary based on the gesture type.
l context - Table with SegmentedUI row details.
gestureInfo table has the following key-value pairs:
© 2015 by Kony, Inc. All rights reserved 309 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
l gestureType [number] – indicates the gesture type; 1 for TAP, 2 for SWIPE, and 3 for
LONGPRESS,4 for PAN, 5 for ROTATION, 6 for PINCH and 7 for RIGHTTAP l gesturesetUpParams [object] – specifies the set up parameters passed while adding the gesture recognizer l gesturePosition [number] – indicates the position where the gesture was recognized.
Possible values are: 1 for TOPLEFT, 2 for TOPCENTER, 3 for TOPRIGHT, 4 for
MIDDLELEFT, 5 for MIDDLECENTER, 6 for MIDDLERIGHT, 7 for BOTTOMLEFT, 8 for
BOTTOMCENTER, 9 for BOTTOMRIGHT, 10 for CENTER l swipeDirection [number] –indicates the direction of swipe. This parameter is applicable only if the gesture type is SWIPE. Possible values are: 1 for LEFT, 2 for RIGHT, 3 for TOP, 4 for
BOTTOM. Direction is w.r.t the view and not device orientation.
l gestureX [number] – specifies the X coordinate of the point (in pixels) where the gesture has occurred. The coordinate is relative to the widget coordinate system.
l gestureY [number] – specifies the Y coordinate of the point (in pixels) where the gesture has occurred. The coordinate is relative to the widget coordinate system.
l widgetWidth [number] – specifies the width of the widget (in pixels) l widgetHeight [number] – specifies the height of the widget (in pixels) l gestureState[number] – indicates the gesture state as below l
1 – gesture state begin l
2 - gesture state changed l
3 – gesture state ended.
l
* gestureState is applicable only for continuous gestures like PAN, ROTATION and
PINCH.
l rotation [number] rotation of the gesture in degrees since its last change.( Applicable only when gesture type is ROTATION
© 2015 by Kony, Inc. All rights reserved 310 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
l velocityX and velocityY : horizontal and vertical component of velocity expressed in points per second. (Applicable only for PAN gesture type) l velocity [number]: velocity of pinch in scale per second (Applicable for Pinch gesture) l scale [number]:scale factor relative to the points of the two touches in screen coordinates l touchType[number]:(windows only) l
0 - constants.TOUCHTYPE_FINGER
l
1 - constants.TOUCHTYPE_PEN
l
2 - constants.TOUCHTYPE_MOUSE
l translationX and translationY [number] : cumulative distance as number. (Applicable only for PAN gesture type) context table has the following key-value pairs: l rowIndex [number] : row index of the segui where gesture was recognised. (Applicable to gestures added to segUI rows) l sectionIndex [number] : section index of the segui where gesture was recognised.
(Applicable to gestures added to segUI rows)
16.2.3 Return Values
String - Reference to the gesture is returned.
16.2.4 API Usage
It is not recommend to define gestures for widgets that have a default behavior associated with it.
16.2.4.1 Scenario 1
If you click (tap) a button (any clickable widget), the default behavior is to trigger an onClick event.
© 2015 by Kony, Inc. All rights reserved 311 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
If you define a Tap gesture on such widgets, the gesture closure is executed in addition to the onClick event.
16.2.4.2 Scenario 2
If you swipe a larger form, the default behavior is to scroll up and down depending on the direction in which you swipe. If you define a SWIPE gesture on such forms, the gesture closure gets executed in addition to scrolling the form.
16.2.4.3 Scenario 3
If you swipe a Segmented UI with huge number of rows, the default behavior is to scroll the
Segmented UI. If you define a SWIPE gesture on such segments, the gesture closure gets executed in addition to scrolling the form.
16.2.5 Rules and Restrictions
Gestures can be added only for the following widgets: l
Form l
HBox l
VBox l
Scrollable Box l
Flex Container l
Flex Scroll Container.
16.2.6 Example
Example 1: var setupTblTap = {fingers:1,taps:2}
© 2015 by Kony, Inc. All rights reserved 312 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
function myTap(widget,gestureInformationTap){
...//write your logic here
}
To add a TAP gesture recognizer on a hbox with ID hbx1 placed on a form frm1, use the following snippet:
Var gestureHandle = Frm1.hbx1.addGestureRecognizer
(constants.GESTURE_TYPE_TAP, setupTblTap, myTap)
Example 2: var setupTblSwipe = {fingers: 1} function mySwipe (frm1.hbx1, gestureInformationSwipe){
...//write your logic here}
}
To add a SWIPE gesture recognizer on a hbox with ID hbx1 placed on a form frm1, use the following snippet: frm1.hbx1.addGestureRecognizer (constants.GESTURE_TYPE_SWIPE, setupTblSwipe, mySwipe)
Example 3: var setupTblSwipe = {fingers: 1} function mySwipe (frm1.hbx1, gestureInformationSwipe){
...//write your logic here}
}
To add a SWIPE gesture recognizer on a hbox with ID hbx1 placed on a form frm1, use the following snippet: frm1.hbx1.addGestureRecognizer (constants.GESTURE_TYPE_SWIPE, setupTblSwipe, mySwipe)
© 2015 by Kony, Inc. All rights reserved 313 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
16.2.7 Platform Availability
Available on all platforms except Server Side Mobile Web, BlackBerry 10, Windows 7/Kiosk, and
Desktop Web.
16.3 removeGestureRecognizer
This API allows you to remove the specified gesture recognizer for the specified widget.
16.3.1 Signature
removeGestureRecognizer( gestureHandle
)
16.3.2 Input Parameters gestureHandle - Mandatory
Specifies the handle to the gesture returned by addGestureRecognizer call.
16.3.3 Example
Example 1
To remove the TAP gesture recognizer on a hbox with ID hbx1 placed on a form frm1, use the following snippet: frm1.hbx1.removeGestureRecognizer( 1 )
Example 2
To remove the SWIPE gesture recognizer on a hbox with ID hbx1 placed on a form frm1, use the following snippet: frm1.hbx1.removeGestureRecognizer( 2 )
Example 3
© 2015 by Kony, Inc. All rights reserved 314 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
To remove the LONGPRESS gesture recognizer on a hbox with ID hbx1 placed on a form frm1, use the following snippet: frm1.hbx1.removeGestureRecognizer( 3 )
16.3.4 Platform Availability
Available on all platforms except Server Side Mobile Web, BlackBerry 10, Windows 7/Kiosk, and
Desktop Web.
16.4 addGestureRecognizerForAllForms
This API allows the developers to set a gesture recognizer for the specified gesture of the specified widget.
16.4.1 Signature kony.application.addGestureRecognizerForAllForms (
,
,
)
16.4.2 Input Parameters gestureType [Number] - Mandatory
Indicates the type of gesture that needs to be detected on the widget. The following are possible values: l
1 – constants.GESTURE_TYPE_TAP
l
2 - constants.GESTURE_TYPE_SWIPE
l
3 – constants.GESTURE_TYPE_LONGPRESS
l
4 – constants.GESTURE_TYPE_PAN
l
5 – constants.GESTURE_TYPE_ROTATION
© 2015 by Kony, Inc. All rights reserved 315 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
l
6 - constants.GESTURE_TYPE_PINCH
l
7 - constants.GESTURE_TYPE_RIGHTTAP
Note: l
RIGHTTAP is applicable only to Windows 8.1 and Windows Desktop/Kiosk platforms.
l
ROTATION is not supported on Android.
gestureConfigParams [object] - Mandatory
Specifies a table that has the configuration parameters needed to setup a gesture recognizer. The configuration parameters vary based on the type of the gesture.
This parameter has the following key-value pairs:
Gesture Type: TAP l fingers [Number] - specifies the maximum number of fingers that must be respected for a gesture. Possible values are: 1. Default value is 1.
l taps [Number] - specifies the maximum number of taps that must be respected for a gesture. Possible values are: 1 or 2. Default value is 1.
For example,{fingers:1,taps:1}
Gesture Type: SWIPE l fingers [Number] - specifies the maximum number of fingers that must be respected for a gesture. Possible values are: 1. Default value is 1.
For example, {fingers: 1}.
Gesture Type : LONGPRESS l pressDuration [Number] - specifies the minimum time interval (in seconds) after which the gesture is recognized as a LONGPRESS. This is not applicable to
Windows.
© 2015 by Kony, Inc. All rights reserved 316 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
For example, if the pressDuration is 2 seconds, any continued press is recognized as LONGPRESS only if it lasts for at least 2 seconds. Default value is 1.
For example, {pressDuration:1}.
Gesture Type : PAN l fingers [number] specifies the minimum number of fingers needed to recognize this gesture. Default value is 1.
l continuousEvents [Boolean] indicates if callback should be called continuously for every change beginning from the time the gesture is recognized to the time it ends.
Gesture Type : ROTATION l
Rotation gesture involves only two fingers.
l continuousEvents [Boolean] indicates if callback must be called continuously for every change beginning from the time the gesture is recognized to the time it ends.
Gesture Type : PINCH l
Pinch gesture invloves two fingures.
l continuousEvents [Boolean] indicates if callback should be called continuously every change beginning from the time the gesture is recognized to the time it ends.
onGestureClosure [function] - Mandatory
Specifies the function that needs to be executed when a gesture is recognized. This function will be raised asynchronously and has the following signature: onGestureClosure(widgetRef, gestureInfo, context)
© 2015 by Kony, Inc. All rights reserved 317 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
l widgetRef - specifies the handle to the widget on which the gesture was recognized.
l gestureInfo - Table with information about the gesture. The contents of this table vary based on the gesture type.
l context - Table with SegmentedUI row details.
gestureInfo table has the following key-value pairs: l gestureType [number] – indicates the gesture type; 1 for TAP, 2 for SWIPE, and 3 for
LONGPRESS,4 for PAN, 5 for ROTATION, 6 for PINCH and 7 for RIGHTTAP l gesturesetUpParams [object] – specifies the set up parameters passed while adding the gesture recognizer l gesturePosition [number] – indicates the position where the gesture was recognized.
Possible values are: 1 for TOPLEFT, 2 for TOPCENTER, 3 for TOPRIGHT, 4 for
MIDDLELEFT, 5 for MIDDLECENTER, 6 for MIDDLERIGHT, 7 for BOTTOMLEFT, 8 for
BOTTOMCENTER, 9 for BOTTOMRIGHT, 10 for CENTER l swipeDirection [number] –indicates the direction of swipe. This parameter is applicable only if the gesture type is SWIPE. Possible values are: 1 for LEFT, 2 for RIGHT, 3 for TOP, 4 for
BOTTOM. Direction is w.r.t the view and not device orientation.
l gestureX [number] – specifies the X coordinate of the point (in pixels) where the gesture has occurred. The coordinate is relative to the widget coordinate system.
l gestureY [number] – specifies the Y coordinate of the point (in pixels) where the gesture has occurred. The coordinate is relative to the widget coordinate system.
l widgetWidth [number] – specifies the width of the widget (in pixels) l widgetHeight [number] – specifies the height of the widget (in pixels) l gestureState[number] – indicates the gesture state as below l
1 – gesture state begin l
2 - gesture state changed
© 2015 by Kony, Inc. All rights reserved 318 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
l
3 – gesture state ended.
l
* gestureState is applicable only for continuous gestures like PAN, ROTATION and
PINCH.
l rotation [number] rotation of the gesture in degrees since its last change.( Applicable only when gesture type is ROTATION l velocityX and velocityY : horizontal and vertical component of velocity expressed in points per second. (Applicable only for PAN gesture type) l velocity [number]: velocity of pinch in scale per second (Applicable for Pinch gesture) l scale [number]:scale factor relative to the points of the two touches in screen coordinates l touchType[number]:(windows only) l
0 - constants.TOUCHTYPE_FINGER
l
1 - constants.TOUCHTYPE_PEN
l
2 - constants.TOUCHTYPE_MOUSE
l translationX and translationY [number] : cumulative distance as number. (Applicable only for PAN gesture type) context table has the following key-value pairs: l rowIndex [number] : row index of the segui where gesture was recognised. (Applicable to gestures added to segUI rows) l sectionIndex [number] : section index of the segui where gesture was recognised.
(Applicable to gestures added to segUI rows)
16.4.3 Return Values
String - Reference to the gesture is returned.
© 2015 by Kony, Inc. All rights reserved 319 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
16.4.4 JavaScript Example
//Defining a function function formGesture(widgetID,gestureInfo)
{ var y = kony.type(gestureInfo); //expected value of y = table var z = kony.type(gestureInfo.gesturesetUpParams); //expected values of z = table var a = gestureInfo.gestureType; var b = gestureInfo.gesturesetUpParams; var c = gestureInfo.gesturePosition; var d = gestureInfo.gestureX; var e = gestureInfo.gestureY; var f = gestureInfo.widgetWidth; var g = gestureInfo.widgetHeight; kony.print("*******************************************"); if(kony.os.toNumber(gestureInfo.gestureType) == 2)
{ h = gestureInfo.swipeDirection; kony.print("swipe direction is: "+h);
} else{ h = ""
} if(kony.os.toNumber(a) == 1)
{ b1 = "fingers: "+gestureInfo.gesturesetUpParams.fingers; b2 = "taps: "+gestureInfo.gesturesetUpParams.taps; kony.print(""+b1+""+b2);
} else if(kony.os.toNumber(a) == 2)
© 2015 by Kony, Inc. All rights reserved 320 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
{ b1 = "fingers :"+gestureInfo.gesturesetUpParams.fingers; b2 = ""; kony.print(""+b1+""+b2);
} else if(kony.os.toNumber(a) == 3)
{ b1 = "pressduration:"+gestureInfo.gesturesetUpParams
pressDuration; b2 = ""; kony.print(""+b1+""+b2);
} kony.print("widget id is: "+widgetID[id]); //will print the widgetID.
To print widgetID use widgetID.id
kony.print("type of gestureInfo is: "+y); kony.print("type of gesturesetUpParams is: "+z); kony.print("gestureType is: "+a); //gestureType=1 or 2 or 3 kony.print("gesturesetUpParams is: "+b.fingers);
//gesturesetUpParams
= {fingers =1, taps =1} or {fingers =1, taps =2} or {fingers =1} or
{pressDuration = 1} kony.print("gesturePosition is: "+c); //gesturePosition=1 or 2 or 3 or .....9
kony.print("gestureX is: "+d); //ex: gestureX=30 kony.print("gestureY is: "+e); //ex: gestureY=100 kony.print("widgetWidth is: "+f); //ex: widgetWidth=320 kony.print("widgetHeight is: "+g); //ex: widgetHeight=28
//gesturePosition, gestureX, gestureY, widgetWidth, widgetHeight params are not applicable in android kony.print("*******************************************");
}
© 2015 by Kony, Inc. All rights reserved 321 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
function callbackSingleTapGesture()
{ var x ={fingers:1,taps:1}; try{ kony.application.setGestureRecognizerForAllForms(1, x, formGesture);
} catch(err){ alert(typeof err); alert("error in function callbackSingleTapGesture:
"+err.message);
}
}
16.4.5 Platform Availability
Available on all platforms except Server Side Mobile Web, BlackBerry 10, Windows 7/Kiosk, and
Desktop Web.
16.5 removeGestureRecognizerForAllForms
This method allows you to remove a specified gesture recognizer for all Forms.
16.5.1 Signature
JavaScript: kony.application.removeGestureRecognizerForAllForms(
)
16.5.2 JavaScript Parameters uniqueIdentifier - Mandatory
Reference to the gesture. The reference to the gesture is returned by the setGestureRecognizerForAllForms.
© 2015 by Kony, Inc. All rights reserved 322 of 848
16. Gesture APIs Kony Studio API Developer's Guide
Version 5.0
16.5.3 Example function callbackClearLongPressGesture()
{ try{ kony.application.removeGestureRecognizerForAllForms
(uniqueidentifier);
} catch(err){ alert(typeof err); alert("error in function callbackClearLongPressGesture:
"+err.message);
}
}
16.5.4 Platform Availability
Available on all platforms except Server Side Mobile Web, BlackBerry 10, Windows 7/Kiosk, and
Desktop Web.
© 2015 by Kony, Inc. All rights reserved 323 of 848
17. Deprecated APIs Kony Studio API Developer's Guide
Version 5.0
17. Deprecated APIs
17.1 setGestureRecognizer
This method allows you to set a gesture recognizer for a specified gesture for a specified widget. You can set a Gesture recognizer only for a Form, an HBox, a VBox, and a Scroll Box.
17.1.1 Signature
JavaScript:
setGestureRecognizer( gestureType , setupParams
,
)
17.1.2 Input Parameters widgetRef - Mandatory
Specifies the handle to the widget reference for which you want to add the gesture recognizer.
gestureType [Number] - Mandatory
Indicates the type of gesture that needs to be detected on the widget. The following are possible values: l
1 for TAP l
2 for SWIPE l
3 for LONGPRESS setupParams [array of arrays] - Mandatory
Specifies a JavaScript object that has the configuration parameters needed to setup a gesture recognizer. The configuration parameters vary based on the type of the gesture.
This parameter has the following parameters:
Gesture Type: TAP l fingers [Number] - specifies the maximum number of fingers that must be
© 2015 by Kony, Inc. All rights reserved 324 of 848
17. Deprecated APIs Kony Studio API Developer's Guide
Version 5.0
respected for a gesture. Possible values are: 1. Default value is 1.
l taps [Number] - specifies the maximum number of taps that must be respected for a gesture. Possible values are: 1 or 2. Default value is 1.
For example,{fingers:1,taps:1}
Note: If both onclick and a single tap gesture has been defined for a box then the behaviour is undefined.
Gesture Type: SWIPE l fingers [Number] - specifies the maximum number of fingers that must be respected for a gesture. Possible values are: 1. Default value is 1.
l swipedistance [Number] - specifies the distance between the pixel from where the swipe started to the pixel where the swipe stopped (finger is moved up or removed). The default value is 50 pixels.
Note: This parameter is applicable only on Android.
l swipevelocity [Number] - specifies the velocity of the swipe measured in pixels per second. The default value is 75.
Note: This parameter is applicable only on Android.
For example,{fingers:1,swipedistance:50,swipevelocity:75}
Gesture Type : LONGPRESS l pressDuration [Number] - specifies the minimum time interval (in seconds) after which the gesture is recognized as a LONGPRESS.
For example, if the pressDuration is 2 seconds, any continued press is recognized as LONGPRESS only if it lasts for at least 2 seconds. Default value is 1.
Note: LONGPRESS is not supported in DesktopWeb ( Internet Explorer 11) and SPA Windows Phone.
© 2015 by Kony, Inc. All rights reserved 325 of 848
17. Deprecated APIs Kony Studio API Developer's Guide
Version 5.0
Note: This parameter is not customizable on Android platform. The default value on
Android platform is 500 ms. Any value you pass to this parameter is ignored and the default value is used.
For example,{pressDuration:1} gestureHandler [Function] - Mandatory
Specifies the function that needs to be executed when a gesture is recognized. This function has the following signature: gestureHandler(widgetRef,gestureInfo) l widgetRef - specifies the handle to the widget on which the gesture was recognized.
l gestureInfo - specifies an array that provides information about the gesture. The contents of this array vary based on the gesture type.
The Kony platform populates the details in the gestureInfo array. This array has the following keyvalue pairs: l gestureType [Number] - indicates the gesture type; 1 for TAP, 2 for SWIPE, and 3 for LONGPRESS.
l gesturesetUpParams [Array] - this array is the set up parameters passed while adding the gesture recognizer.
l swipeDirection [Number] -indicates the direction of swipe. This parameter is applicable only if the gesture type is SWIPE. Possible values are: 1 for LEFT, 2 for RIGHT, 3 for TOP, 4 for BOTTOM.
l
The following parameters are applicable only on iPhone: o gesturePosition [Number] - indicates the position where the gesture was recognized. Possible values are: 1 for TOPLEFT, 2 for TOPCENTER, 3 for TOPRIGHT, 4 for MIDDLELEFT, 5 for MIDDLECENTER, 6 for
MIDDLERIGHT, 7 for BOTTOMLEFT, 8 for BOTTOMCENTER, 9 for
BOTTOMRIGHT, 10 for CENTER.
o gestureX [Number] - specifies the X coordinate of the point (in
© 2015 by Kony, Inc. All rights reserved 326 of 848
17. Deprecated APIs Kony Studio API Developer's Guide
Version 5.0
pixels) where the gesture has occurred. The coordinate is relative to the widget coordinate system.
o gestureY [Number] - specifies the Y coordinate of the point (in pixels) where the gesture has occurred. The coordinate is relative to the widget coordinate system.
o widgetWidth [Number] - specifies the width of the widget (in pixels).
o widgetHeight [Number] - specifies the height of the widget (in pixels).
17.1.3 Return Values
String - Reference to the gesture is returned.
17.1.4 API Usage
We recommend not to define gestures for widgets that have a default behavior associated with it.
17.1.4.1 Scenario 1
When you swipe a larger form, the default behavior is to scroll up and down depending on the direction in which you swipe.
If you define a SWIPE gesture on such forms, the gesture function gets executed in addition to scrolling the form.
Note: On Android, no gesture event is triggered in this case (hence no gesture function is executed) and the form scrolls normally.
17.1.4.2 Scenario 2
When you swipe a Segmented UI with huge number of rows, the default behavior is to scroll the
Segmented UI.
© 2015 by Kony, Inc. All rights reserved 327 of 848
17. Deprecated APIs Kony Studio API Developer's Guide
Version 5.0
If you define a SWIPE gesture on such segments, the gesture function gets executed in addition to scrolling the Segment.
Note: On Android, if the swipe is started from an area outside the Segmented UI, then only the function is executed, else the Segmented UI would scroll normally and no function is executed.
17.1.4.3 Scenario 3
You can add both single tap and double tap gestures to the same widget. setgesturerecognizer API replaces the existing gesture if it of the same type and has the same set of configurations. If the gesture type is different or the gesture has a different set of configurations, then both the gestures are added to the same widget.
17.1.4.4 Scenario 4
If you set the same gesture type on the same widget with different set of configurations without removing the existing gesture, the existing gesture is replaced with the new gesture (as the gesture type is same).
17.1.5 Rules and Restrictions
You can add gesture recognizers only for the following widgets: l
Form l
HBox l
VBox l
Scrollable Box.
17.1.6 JavaScript Example
//The below function will get invoked when a gesture is recognized.
function myTap(myWidget,gestureInfo)
{
© 2015 by Kony, Inc. All rights reserved 328 of 848
17. Deprecated APIs Kony Studio API Developer's Guide
Version 5.0
alert(" Tap Gesture detected"); alert("gestureType :"+gestureInfo.gestureType); alert("gesturePosition :"+gestureInfo.gesturePosition);
//write any further logic here
}
//Setting Gesture configuration.
var setupTblTap = {fingers:1,taps:2};//double tap gesture
//To add a TAP gesture recognizer on a hbox with ID hbx1 placed on a form frm1 var tapGesture=frm1.hbx1.setGestureRecognizer(1,setupTblTap,myTap);
17.1.7 Platform Availability
Available on all platforms except Server Side Mobile Web, BlackBerry 10, Windows 7/Kiosk, and
Desktop Web.
© 2015 by Kony, Inc. All rights reserved 329 of 848
18. Hybrid APIs Kony Studio API Developer's Guide
Version 5.0
18. Hybrid APIs
Mobile applications can be built and deployed using various techniques and approaches. One extreme is to use the native SDK to build Enterprise applications, while the other extreme is to use traditional web technologies to build mobile web applications. There is a category that falls in between these two extremes, which mixes the native and web technologies to create a mobile application.
Kony Platform provides complete flexibility to choose different packaging and deployment modes according to the needs of the application.
l
Hybrid
Hybrid application is partly a native application and partly a web-based application. In the native part of the application, some of the forms are rendered using UIWebView and Browserfield, while other forms are rendered using Native SDK. The developer can pick and choose the forms that need to be native or web-based. The web-based forms can be either packaged statically along with the application or loaded from a URL dynamically.
l
Single Page Application (SPA)
Single Page Applications (SPA) are a type of web applications, in which all the HTML, CSS, and JavaScripts necessary for the application are retrieved with a single page load. The page does not automatically reload during user interaction with the application or control the transfer to another page. The application requires server interaction only for data retrieval.
Unlike a traditional mobile web application, the browser executes all the application logic on the client-side. The logic include validations, UI rules (hiding or showing fields), form transitions/navigations, and so on.
In an SPA app all the application screens are expressed as a JavaScript model/CSS (unlike
JavaScript, ASPX in typical mobile web application). This model is downloaded to the clientside with the first page download and resides on the client for the lifetime of the session.
For characteristics of each of these application types, see Kony Studio User Guide.
© 2015 by Kony, Inc. All rights reserved 330 of 848
18. Hybrid APIs Kony Studio API Developer's Guide
Version 5.0
Kony Platform utilizes the Single Page Application (SPA) implementation for rendering the statically packaged forms in the wrapper and hybrid applications. In the Wrapper Mode, the application is an
SPA running inside a native shell provided by the native platforms. For the forms with dynamic nature, the traditional Mobile Web implementation is utilized.
18.1 kony.hybrid.executeFunctionInNativeContext
This API provides the ability to send data from the browser widget execution context to native context.
18.1.1 Signature
JavaScript: kony.hybrid.executeFunctionInNativeContext(
,
)
18.1.2 Input Parameters
Function [String] - Mandatory
Specifies the function that needs to be executed.
paramsTable [Object] - Mandatory
Specifies the list of parameters that the user defined function expects as input parameters. It is mandatory only if the invoked function accepts arguments.The paramsTable is the list of params that are passed to that function.
Note: For the first parameter, the function name has to be passed as a string, for example, if the function is test() , then parameter must be passed as "test".
18.1.3 Return Values
None.
© 2015 by Kony, Inc. All rights reserved 331 of 848
18. Hybrid APIs Kony Studio API Developer's Guide
Version 5.0
18.1.4 Platform Availability l iPhone l
Android
18.1.5 Example
//Defining executeFunctionInNativeContext function executeFunctionInNativeContext()
{ kony.hybrid.executeFunctionInNativeContext("JSFunThree",
{"KonySolutions",false,{"abc","xyz"}});
}
18.2 kony.hybrid.executeFunctionInSPAContext
This API provides the ability to send data from the native execution context to browser widget context.
18.2.1 Signature
JavaScript: hybrid.executeFunctionInSPAContext(
)
18.2.2 Input Parameters
Function [String] - Mandatory
Specifies the function that needs to be executed paramsTable [Object] - Mandatory
Specifies the list of parameters that the user defined function expects as input parameters.
© 2015 by Kony, Inc. All rights reserved 332 of 848
18. Hybrid APIs Kony Studio API Developer's Guide
Version 5.0
18.2.3 Return Values
None.
18.2.4 Platform Availability l iPhone l
Android
18.2.5 Example function executeFunctionInSPAContext()
{ kony.hybrid.executeFunctionInSPAContext("JSFunThree",
["KonyLabs",2012,false]);
}
18.3 kony.hybrid.executeFunctionInTCContext
This API is used to exchange data with the server-side context.
18.3.1 Signature
JavaScript:
hybrid.executeFunctionInTCContext( Function ,
18.3.2 Input Parameters
Function [String] - Mandatory
Specifies the function that needs to be executed
© 2015 by Kony, Inc. All rights reserved 333 of 848
18. Hybrid APIs Kony Studio API Developer's Guide
Version 5.0
paramsTable [Object] - Mandatory
Specifies the list of parameters that the user defined function expects as input parameters.
18.3.3 Return Values
None.
18.3.4 Platform Availability l iPhone l
Android
18.3.5 Example function executeFunctionInTCContext()
{ kony.hybrid.executeFunctionInTCContext("JSFunThree",
{"KonySolutions", false,{"abc","xyz"}});
}
© 2015 by Kony, Inc. All rights reserved 334 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19. Input and Output APIs
The section describes file system APIs. Kony Studio enables you to browse file system and select multiple files to upload on the server. This chapter explains the APIs available in the kony.io.FileSystem, kony.io.File, kony.io.FileList, and kony.types.RawBytes namespaces.
l
l
l
l
19.1 kony.io.FileSystem
The kony.io.FileSystem namespace includes APIs to create, read and navigate through the device file system.
The File System APIs library comprises the following APIs:
1.
2.
3.
4.
5.
getExternalStorageDirectoryPath
6.
7.
8.
© 2015 by Kony, Inc. All rights reserved 335 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
9.
10.
kony.io.FileSystem.uploadFiles
Note: All the above APIs are supported only in JavaScript.
19.1.1 getFile getFile API returns a kony.io.File object representing the file for the given path. It returns a kony.io.File
object for the specified file path. getFile API does not create a File.
19.1.1.1 Signature
JavaScript: kony.io.FileSystem.getFile(string path)
19.1.1.2 Input Parameters
Path – path to the file or directory.
19.1.1.3 Return Values
Kony.io.File
19.1.1.4 Platform Availability
Applicable to all native Platforms and Desktop Web.
19.1.2 getCacheDirectoryPath getCacheDirectoryPath API returns the application's cache directory path.
19.1.2.1 Signature
JavaScript: kony.io.FileSystem.getCacheDirectoryPath()
© 2015 by Kony, Inc. All rights reserved 336 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.1.2.2 Input Parameters
None
19.1.2.3 Return Values
String
19.1.2.4 Exceptions
None
19.1.2.5 Platform Availability
Applicable to all native Platforms and DesktopWeb.
19.1.3 getDataDirectoryPath getDataDirectoryPath API returns the application’s data directory path.
19.1.3.1 Signature
JavaScript: kony.io.FileSystem.getDataDirectoryPath()
19.1.3.2 Input Parameters
None
19.1.3.3 Return Values
String
19.1.3.4 Exceptions
None
19.1.3.5 Platform Availability
Applicable to all the native platforms and DesktopWeb.
© 2015 by Kony, Inc. All rights reserved 337 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.1.4 getApplicationDirectoryPath getApplicationDirectoryPath API returns the application directory path.
19.1.4.1 Signature
JavaScript: kony.io.FileSystem.getApplicationDirectoryPath()
19.1.4.2 Input Parameters
None
19.1.4.3 Return Values
String
19.1.4.4 Exceptions
None
19.1.4.5 Platform Availability
Applicable to the iOS platforms.
19.1.5 getExternalStorageDirectoryPath getExternalStorageDirectoryPath API returns the path to the external storage, typically sdcard.
19.1.5.1 Signature
JavaScript: kony.io.FileSystem.getExternalStorageDirectoryPath()
19.1.5.2 Input Parameters
None
19.1.5.3 Return Values
String
© 2015 by Kony, Inc. All rights reserved 338 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.1.5.4 Exceptions
None
19.1.5.5 Platform Availability
Applicable to the Android platform.
19.1.6 getRawDirectoryPath getRawDirectoryPath API returns the application’s “raw” directory path. getRawDirectoryPath API
API is applicable only on Android.
19.1.6.1 Signature
JavaScript: kony.io.FileSystem.getRawDirectoryPath()
19.1.6.2 Input Parameters
None
19.1.6.3 Return Values
String
19.1.6.4 Exceptions
None
19.1.6.5 Platform Availability
Applicable to the Android platform.
19.1.7 getSupportDirectoryPath getSupportDirectoryPath API returns the application’s support directory path. This is applicable to iOS platform only.
© 2015 by Kony, Inc. All rights reserved 339 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.1.7.1 Signature
JavaScript: kony.io.FileSystem.getSupportDirectoryPath()
19.1.7.2 Input Parameters
None
19.1.7.3 Return Values
String
19.1.7.4 Exceptions
None
19.1.7.5 Platform Availability
Applicable to the iOS platform.
19.1.8 isExternalStorageAvailable isExternalStorageAvailable API is used to check, if the external storage is available and accessible on the device. isExternalStorageAvailable API returns boolean value as true/false accordingly on Android platform.
19.1.8.1 Signature
JavaScript: kony.io.FileSystem.isExternalStorageAvailable()
19.1.8.2 Input Parameters
None
19.1.8.3 Return Values
Boolean
© 2015 by Kony, Inc. All rights reserved 340 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.1.8.4 Exceptions
None
19.1.8.5 Platform Availability
Applicable to iOS, Android, and Windows platforms.
19.1.9 kony.io.FileSystem.browse
This API provides the ability to browse and select files from your local system.
19.1.9.1 Signature
JavaScript:
kony.io.FileSystem.browse( browseConfig
,
)
19.1.9.2 Input Parameters browseConfig [String] - Mandatory
Configuration params which is a simple JSON object of key value pairs, that drive the possible options during the browse. Currently the following keys are supported in the configuration: l selectMultipleFiles: (Boolean) - Default (true) l filter: An array indicates what file Filters should be applied to the file selection dialog. The file
Filters need to follow the conventions specified in the IANAMediaTypes specification. For more information, see http://www.iana.org/assignments/media-types/media-types.xhtml
.
browseCallBack [Object] - Mandatory
The callback is executed once the user closes the browse dialog. As part of call back, the platform provides the list of files that have been selected as an array of kony.io.FileSystem objects. The call back signature is as follows: browseCallBack (event, FileList[]).
19.1.9.3 Return Values
None.
© 2015 by Kony, Inc. All rights reserved 341 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.1.9.4 Platform Availability
Applicable only on Desktop web.
19.1.9.5 Example function selectBtn_onClick_seq0() { // Event on button click var config = { selectMultipleFiles: true, filter: ["image/png", "image/jpeg"]
}; kony.io.FileSystem.browse(config, selectedFileCallback);
};
19.1.10 kony.io.FileSystem.uploadFiles
When the developer invokes this API with the list of files, the API Developer's Guide internally iterates through the fileList and makes the network call to the URL mentioned and uploads the files. The
API Developer's Guide assumes that the application using this API has the necessary server side infrastructure to handle the upload.
Internally, API Developer's Guide uses AJAX-based multi-part upload of the files to the URL mentioned in all browsers except IE 8 and 9. In the case of IE 8 and 9, we provide frame-based submit as the multi-part through AJAX (as it is not handled by the browser).
Note: The API kony.io.FileSystem.uploadFiles cannot be tested in local jetty server included in the Kony Studio. Use Tomcat to test the API. The uploadURL must have code to receive and store the files sent via kony app. The sample war file uploadServlet30.war
, contains code to handle uploading or storing files at server end. Both kony app and UploadURL needs to be on the same domain.
19.1.10.1 Signature
JavaScript: kony.io.FileSystem.uploadFiles(
,
)
© 2015 by Kony, Inc. All rights reserved 342 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.1.10.2 Input Parameters
URL [String] - Mandatory
Provide target location to upload the file.
fileList [Object] - Mandatory
Specifies the list of files to be uploaded. This is as an array of kony.io.FileSystem.file objects.
l uploadCallBack [Object] - Mandatory
The callback is invoked each time when the file is getting uploaded. The signature of the call back is expected to be as follows: uploadCallBack(URL, upLoadStates).
upLoadState [Object] - Mandatory
This is an array of key value map states of the individual files that are uploaded. The key value map currently consists of the following keys: o file: File (kony.io.FileSystem.file) object o status: One of the following four status are possible : n
FILE_UPLOAD_START_STATE = 0 n
FILE_UPLOAD_PROGRESS_STATE = 1 n
FILE_UPLOAD_COMPLETE_STATE = 2 n
FILE_UPLOAD_ERROR_STATE = 3 o uploadBytes: Number of bytes that are uploaded.
uploadConfig [Object]
Configuration parameters, which is a simple JSON object of key value pairs, that provides the possible options during the upload. Currently there are no keys.
19.1.10.3 Return Values
None.
© 2015 by Kony, Inc. All rights reserved 343 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.1.10.4 Platform Availability
Available only on Desktop Web.
19.1.10.5 Example function UploadBtn_onClick_seq0() { // Event on upload button click var uploadURL = "http://10.10.4.17:8080/fileupload/upload"; var filesQueue = [{File object},{File Object}]; //Array of File objects got in browseCallBack() kony.io.FileSystem.uploadFiles(uploadURL, filesQueue, upLoadCallBack);
};
19.1.10.6 Limitations for File Browse and Upload APIs
1. API cannot be used in pre-show, post-show, appService, pre-appinit, or post-app init.
2. For details on filter types for Browse API, follow the specification provided in the
IANAMediaTypes. The Kony Studio depends on the browsers respecting the given filter type and enable appropriate file selection for the end user.
3. File Upload API does not work in the cross origin request scenarios. That is, the file can be uploaded only to the site from which the original app has been accessed. For more information, check CORS documentation.
4. For security reasons all browsers just give name or size of the file and not parent or full path. So, file parent and full path are not available in File object in browse or upload APIs. For more information, see http://stackoverflow.com/questions/15201071/how-to-get-full-path-ofselected-file-on-change-of-input-type-file-using-jav .
5. IE 8 and 9 Limitations:
© 2015 by Kony, Inc. All rights reserved 344 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
a. Multiple file selection will not work. As multiple attribute is not supported for input type= file, it allows the user to select only one file from the browse window even when
‘selectMultipleFiles’ is passed as true. For more information, see http://www.w3schools.com/tags/att_input_multiple.asp
.
b. Filters in the Browse API do not work. As accept attribute is not supported for input type= file, even through the filter is passed, it does not have any effect on browse window. User can select any file of any type. Hence, server side file validation is recommended. For more information, see http://www.w3schools.com/tags/att_input_accept.asp
.
c. The file object in Browse API callback method will not have file size in IE 8. IE 8 browsers do provide file path, but it is inconsistent and depends on IE 8 security configuration (IE 9 provide fakepath). We recommend to avoid accessing file parent, path and size in IE 8 and 9. File size is provided in IE 10, Firefox, and Chrome.
d. IE 8 and 9 uses iframe for file upload. The uploadprogress event is not triggered and bytes uploaded information is not provided in Upload API callback. So, callback is fired only twice.
i. When you submit form to iframe with FILE_UPLOAD_PROGRESS_STATE.
ii. When you get error or success onload event of iframe with respective state constants.
e. Multiple Upload. If a widget onclick action invokes the Browse API and user selects the file multiple times from the browse window, in browse API callback, you must handle all the files (selected by the user one by one). When Upload API is called, all the files user selected is uploaded to the specified URL. If you want to upload different files on different servers or URLs, then they need to call Browse API and Upload API subsequently one after the other. That is, you need to upload the selected file before letting the user select an other file (in case user wants to upload files on different URLs).
f. Empty files cannot be uploaded in case of IE browsers.
6. IE 8 and 9 Limitations:
© 2015 by Kony, Inc. All rights reserved 345 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
a. Multiple file selection will not work. As multiple attribute is not supported for input type= file, it allows the user to select only one file from the browse window even when
‘selectMultipleFiles’ is passed as true. For more information, see http://www.w3schools.com/tags/att_input_multiple.asp
.
b. Filters in the Browse API do not work. As accept attribute is not supported for input type= file, even through the filter is passed, it does not have any effect on browse window. User can select any file of any type. Hence, server side file validation is recommended. For more information, see http://www.w3schools.com/tags/att_input_accept.asp
.
c. The file object in Browse API callback method will not have file size in IE 8. IE 8 browsers do provide file path, but it is inconsistent and depends on IE 8 security configuration (IE 9 provide fakepath). We recommend to avoid accessing file parent, path and size in IE 8 and 9. File size is provided in IE 10, Firefox, and Chrome.
d. IE 8 and 9 uses iframe for file upload. The uploadprogress event is not triggered and bytes uploaded information is not provided in Upload API callback. So, callback is fired only twice.
i. When you submit form to iframe with FILE_UPLOAD_PROGRESS_STATE.
ii. When you get error or success onload event of iframe with respective state constants.
e. Multiple Upload. If a widget onclick action invokes the Browse API and user selects the file multiple times from the browse window, in browse API callback, you must handle all the files (selected by the user one by one). When Upload API is called, all the files user selected is uploaded to the specified URL. If you want to upload different files on different servers or URLs, then they need to call Browse API and Upload API subsequently one after the other. That is, you need to upload the selected file before letting the user select an other file (in case user wants to upload files on different URLs).
f. Empty files cannot be uploaded in case of IE browsers.
© 2015 by Kony, Inc. All rights reserved 346 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
7. When the user uploads a file that has special characters in its file name, the special characters in the file name are replaced with other special characters on the server.
8. Check if the user is selecting the same file again and create appropriate conditions for browseCallBack. The check will help identify same files if selected earlier and eliminate duplicate files from getting uploaded.
9. Firefox Limitation. Filters with specific Mimetype might not work properly. It is a known bug in
Firefox, for more information, see: l http://techblog.procurios.nl/k/618/news/view/15872/14863/mimetype-corruption-infirefox.html
l http://support.mozilla.org/en-US/questions/953914 l https://bugzilla.mozilla.org/show_bug.cgi?id=826176 l https://bugzilla.mozilla.org/show_bug.cgi?id=373621
Note: Constants: Constants.FILE_PATH_SEPARATOR: Platform specific File path separator
19.2 kony.io.File
The kony,io.File namespace includes APIs to do various tasks related with files, such as copying, renaming, deleting and so on.
Creating a File object instance: Use the kony.io.FileSystem.getFile() api to get an instance of a File or create it with a new operator. Here, an abject represents a path to a file or directory in the device file system.
var myfile = new kony.io.File("myfile.txt"); or var myfile = kony.io.FileSystem.getFile("myfile.txt")
© 2015 by Kony, Inc. All rights reserved 347 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
File
Properties:Name name: [type:
String, ReadOnly]
Name of the file or directory
Description
Full absolute path of the file or directory fullPath: [type:
String, ReadOnly] parent:
[type:kony.io.File,
ReadOnly]
Returns the parent directory of this file.
This property may return nil or a File object which can neither Readable or
Writable, especially in case of Folders which are not accessible by the given
Application context
Returns true if this file is readable readable: [type:
Boolean,
ReadOnly] writable: [type:
Boolean,
ReadOnly] modificationTime:
[type:Number,
ReadOnly] size:
[type:Number,
ReadOnly
Returns true if this file is writable
Returns the last modification time of the file in UTC
Returns the size of a file in number of bytes.
The File library comprises the following APIs:
1.
2.
3.
© 2015 by Kony, Inc. All rights reserved 348 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
4.
5.
6.
7.
8.
9.
10.
11.
12.
19.2.1 copyTo copyTo API copies a file to the given destination path.
19.2.1.1 Signature
JavaScript: kony.io.File.copyTo(String path, String newName)
19.2.1.2 Input Parameters l
Path – path to the destination directory.
l newName (optional) – New name of the file/directory. Defaults to current name if unspecified.
19.2.1.3 Return Values
Kony.io.File returns a handle to the File object pointing to the destination file, if successful. If failure, then returns null.
19.2.1.4 Exceptions
None
© 2015 by Kony, Inc. All rights reserved 349 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.2.1.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.2.2 moveTo
The moveTo API moves a file to the given destination path.
19.2.2.1 Signature
JavaScript: kony.io.File.moveTo(String path, String newname)
19.2.2.2 Input Parameters l
Path – path to the destination directory.
l newName (optional) – New name of the file/directory. Defaults to current name, if unspecified.
19.2.2.3 Return Values
Kony.io.File – returns a handle to File object pointing to destination file on success. Returns null on failure.
19.2.2.4 Exceptions
None
19.2.2.5 Platform Availability
Available to iOS, Android, and Windows platforms.
19.2.3 remove
The remove API deletes a file or a directory.
19.2.3.1 Signature
JavaScript: remove(boolean, deleteRecursive)
© 2015 by Kony, Inc. All rights reserved 350 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.2.3.2 Input Parameters l boolean: By default, this is false.
o
True - deletes the folder and all its content recursively.
o
False - if the directory is empty it shall be removed.
l deleteRecursive (optional) – Ignored in case of a file.
19.2.3.3 Return Values
None
19.2.3.4 Exceptions
None
19.2.3.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.2.4 rename
The rename API renames a file or a directory.
19.2.4.1 Signature
JavaScript: kony.io.File.rename(String newname)
19.2.4.2 Input Parameters newname – new name for a file or a directory.
19.2.4.3 Return Values
Boolean – If successful, then boolean value is true,. Boolean value is false, if invalid file name or if the destination is a different directory than the current file.
© 2015 by Kony, Inc. All rights reserved 351 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.2.4.4 Exceptions
None
19.2.4.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.2.5 createFile
The createFile API creates a file on the file system represented by this file object.
19.2.5.1 Signature
JavaScript: kony.io.File.createFile()
19.2.5.2 Input Parameters
None
19.2.5.3 Return Values
Boolean – true if the creation of file is successful. False if file already exists or could not be created.
19.2.5.4 Exceptions
None
19.2.5.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.2.6 createDirectory
The createDirectory API creates a directory on the file system represented by this file object.
19.2.6.1 Signature
JavaScript: kony.io.File.createDirectory()
© 2015 by Kony, Inc. All rights reserved 352 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.2.6.2 Input Parameters
None
19.2.6.3 Return Values
Boolean – true if the creation of directory is successful. False if directory already exists or could not be created.
19.2.6.4 Exceptions
None
19.2.6.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.2.7 exists
The exist API checks, if the file or directory exists on the file system represented by this file object.
19.2.7.1 Signature
JavaScript: kony.io.File.exists()
19.2.7.2 Input Parameters
None
19.2.7.3 Return Values
Boolean – true if the file or directory exists on file system.
19.2.7.4 Exceptions
None
© 2015 by Kony, Inc. All rights reserved 353 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.2.7.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.2.8 getFilesList
The getFilesList API returns kony.io.FileList object representing the files and directories available under this file object directory.
19.2.8.1 Signature
JavaScript: kony.io.File.getFilesList()
19.2.8.2 Input Parameters
None
19.2.8.3 Return Values kony.io.FileList – FileList object or null if this File is not identified as a directory.
19.2.8.4 Exceptions
None
19.2.8.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.2.9 isFile
The isFile API checks, if this object represents a typical file on the file system but not a directory.
19.2.9.1 Signature
JavaScript: kony.io.File.isFile()
© 2015 by Kony, Inc. All rights reserved 354 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.2.9.2 Input Parameters
None
19.2.9.3 Return Values
Boolean – true if this file object represents a file, false otherwise.
19.2.9.4 Exceptions
None
19.2.9.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.2.10 isDirectory
The isDirectory API checks, if this object represents a directory file on the file system.
19.2.10.1 Signature
JavaScript: kony.io.File.isDirectory()
19.2.10.2 Input Parameters
None
19.2.10.3 Return Values
Boolean – true, if this file object represents a directory, false otherwise.
19.2.10.4 Exceptions
None
19.2.10.5 Platform Availability
Available for iOS, Android, and Windows platforms.
© 2015 by Kony, Inc. All rights reserved 355 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.2.11 read
The read API returns the kony.types.RawBytes of this file.
19.2.11.1 Signature
JavaScript: kony.io.File.read()
19.2.11.2 Input Parameters
None
19.2.11.3 Return Values kony.types.RawBytes – rawbytes representing the content of the file.Returns null in case of non existent file.
19.2.11.4 Exceptions
None
19.2.11.5 Platform Availability
Available for iOS, Android, and Windows platforms.
Note: RawBytes will hold a handle of File object that it represents. The file content is not actually loaded into memory.
19.2.12 write
The write API writes the given content into the file.
19.2.12.1 Signature
JavaScript: kony.io.File.write(rawbytes/string, append)
© 2015 by Kony, Inc. All rights reserved 356 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.2.12.2 Input Parameters l
Rawbytes/string – data to write of type text string or kony.types.RawBytes
l
Append (optional) – true to append the data. Default is false, that means overrides the content.
19.2.12.3 Return Values
Boolean – true if success, false otherwise.
19.2.12.4 Exceptions
None
19.2.12.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.3 kony.io.FileList
FileList namespace represents the list of file objects.
FileList Properties:Name length: [type: Number, ReadOnly]
Description
Returns the number of files in the FileList object.
The FileList library comprises the following API: l
19.3.1 item
The item API returns the File object at the specified index in the FileList.
19.3.1.1 Signature
JavaScript: kony.io.File.item(index)
© 2015 by Kony, Inc. All rights reserved 357 of 848
19. Input and Output APIs Kony Studio API Developer's Guide
Version 5.0
19.3.1.2 Input Parameters
Index – index in the FileList.
19.3.1.3 Return Values
File - File object at specified index. Null if there is no File at specified index or if index is not in FileList range.
19.3.1.4 Exceptions
None
19.3.1.5 Platform Availability
Available for iOS, Android, and Windows platforms.
19.4 kony.types.RawBytes
The RawBytes namespace represents the file content.
RawBytes
Properties:Name text: [type: String,
ReadOnly]
Description
UTF-8 representation of data in this RawBytes or null if this RawBytes represents a binary.
The RawBytes library comprises the following API: l
19.4.1 readAsText
The readAsText API returns the data as text represented by this rawBytes . Returns null if this represents a binary.
© 2015 by Kony, Inc. All rights reserved 358 of 848
19. Input and Output APIs
19.4.1.1 Signature
JavaScript: kony.io.File.readAsText()
19.4.1.2 Input Parameters
None
19.4.1.3 Return Values
String - text available in this rawbytes.
19.4.1.4 Exceptions
None
19.4.1.5 Platform Availability
Available for iOS, Android, and Windows platforms.
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 359 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20. Internationalization APIs
The process of designing or developing an application in such a way that it supports various languages and regions is known as Internationalization. For an application to support Internationalization, you need not make any changes in the application code or logic.
Internationalization is abbreviated as i18n.
i18n support for an application has to be defined at the time of developing the application.
The APIs in this library perform various operations related to internationalization. The i18n APIs are as follow: l
l
l
kony.i18n.getCurrentDeviceLocale
l
l
kony.i18n.updateResourceBundle
l
kony.i18n.isResourceBundlePresent
l
l
kony.i18n.deleteResourceBundle
l
kony.i18n.setDefaultLocaleAsync
l
kony.i18n.setCurrentLocaleAsync
l
kony.i18n.isLocaleSupportedByDevice
20.1 Concepts
This section explains a few concepts about Internationalization:
© 2015 by Kony, Inc. All rights reserved 360 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.1.1 Resource Bundle
Resource bundle is a properties file that contains all the i18n Keys along with their values. The resource bundle is locale specific, that is, you will have one resource bundle per locale. The resource bundle follows the naming convention of
<language_Country>.properties
. For example, l for English locale in United States, the resource bundle will be
en_US.properties.
l for French locale in Canada, the resource bundle will be
fr_CA.properties
.
The resource bundle has a list of key-value pairs that are used as internationalization keys within the application.
20.1.2 Implementation Details
The current practice to support i18n for applications is to place the text (i18n keys) in the resource bundles that are loaded into the application. Applications are built to access the resource bundles depending on the selected locale data. For an application to support multiple languages, you have to design the application to select the relevant resource bundle at runtime. The keys in the resource bundles are translated to the required languages at runtime.
An internationalized application has the following benefits: l
The same application can run on multiple locales.
l
Widget's text is not hard-coded in the application. Instead the localized keys are retrieved dynamically.
l
Support for new locales does not require recompilation.
l
Region-dependent data such as dates and currencies, appear in formats that conform to the end user's region and language.
© 2015 by Kony, Inc. All rights reserved 361 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.2 kony.i18n.getCurrentLocale
This API returns the locale (string) that is currently being used by the application to populate the localized data. This locale might be different than the system locale. The locale follows the format language_Country. For example,
en_US
.
Country
is not mandatory.
20.2.1 Use Cases
You can use this API to know the current locale of the application before: l changing the locale.
l deleting the resource bundle of the locale.
20.2.2 Signature
JavaScript: kony.i18n.getCurrentLocale()
20.2.3 Input Parameters
None.
20.2.4 Return Values
Current locale [String]
The current locale that is being used by the application is returned.
20.2.5 Exceptions
1300 - i18n error or Locale not supported error
© 2015 by Kony, Inc. All rights reserved 362 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.2.6 Implementation Details
The current locale of the application is identified using the following rules:
Device
Locale
Locales
Supported by the application
Default
Locale en_GB en_US, zh_TW en_TW
Locale returned by getCurrentLocale
API en_TW (Since the device locale is not supported by the application, the API falls back to default locale) en_US en_US, en , zh_TW en_TW en_US en, zh_TW en_TW en_US (Since the device locale is supported by the application, the API returns it as the current locale) en (Since the device locale is supported by the application, the API falls back to the country)
This API follows the rules given below to identify the current locale:
1. When the device locale is not supported by the application:
For example, if the l application supports fr_GR, nl_NL.
l default locale is (set from IDE) nl_NL.
l device locale is en_GB.
The kony.i18n.getCurrentLocale() API returns nl_NL.
© 2015 by Kony, Inc. All rights reserved 363 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
2. When the device locale supports just the language part and not the region part
For example, l application supports fr_GR, en_US, en_GB, nl_NL.
l default locale is (set from IDE) nl_NL.
l device locale is en..
Note: On iPhone and Android, the device settings mandate that a region must also be associated with a language. For devices like BlackBerry, the region is not mandatory.
The kony.i18n.getCurrentLocale() API picks up the first locale that matches the language. In this example, the API returns en_US as it is the first locale that matches the language as specified in the device system settings.
3. When appropriate fonts are not installed on the device for a given locale
For example, l application supports fr_FR and nl_NL l default locale is (set from IDE) nl_NL l device locale is en_GB.
The kony.i18n.getCurrentLocale() API returns nl_NL. If the device does not have Dutch fonts installed, the application UI displays junk characters.
20.2.7 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 364 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.2.8 JavaScript Example
// Method for getting current locale --> function getCurrentLocale()
{ try{ var currentLocales = kony.i18n.getCurrentLocale(); alert("CurrentLocale :"+currentLocales);
} catch(i18nError)
{ alert("Exception While getting currentLocale : "+i18nError );
}
}
20.3 kony.i18n.getSupportedLocales
This API retrieves a list of all the locales supported by the device.
20.3.1 Signature
JavaScript: kony.i18n.getSupportedLocales()
20.3.2 Input Parameters
None
20.3.3 Return Values listOfLocales [Table]
A table with the following key-value pairs is returned:
© 2015 by Kony, Inc. All rights reserved 365 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
l language l country l name
Note: In Windows platform, Country and Name are not supported.
For example, local list = kony.i18n.getSupportedLocales()
Where list={{language:"en", country:"US", name:"English US"},
{language:"en", country:"UK", name:"English UK"}}
20.3.4 Exceptions
1300 - i18n error or Locale not supported error
20.3.5 Platform Availability
Available on all platforms except Server Side Mobile Web, Desktop Web and SPA. *SPA and Desktop
Web returns only current locale instead of all locales supported by the browser.
20.3.6 JavaScript Example function getSupportedLocales()
{ try
{ var locales =kony.i18n.getSupportedLocales(); for(var i=1;i<locales.length;i++)
{ alert("locale is "+locales[i].name);
}
© 2015 by Kony, Inc. All rights reserved 366 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
}
} catch(i18nerr)
{ alert("Exception in getSupportedLocales : "+err );
}
20.4 kony.i18n.getCurrentDeviceLocale
This API provides you the ability to fetch the current locale of the device.
20.4.1 Signature
JavaScript: kony.i18n.getCurrentDeviceLocale()
20.4.2 Input Parameters
None
20.4.3 Return Values listOfLocales [Table]
A table with the following key-value pairs is returned: l language l country l name
For example, local myLocaleDetails = kony.i18n.getCurrentDeviceLocale()
Where myLocaleDetails={language="en", country="US", name="English US"}
© 2015 by Kony, Inc. All rights reserved 367 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
Note: In iOS platform this API returns a string value.
20.4.4 Exceptions
1300 - i18n error or Locale not supported error
20.4.5 Platform Availability
Available on iOS, Android, Windows Mango, Windows 8, and BlackBerry 10.
20.4.6 JavaScript Example function getCurrentDeviceLocale()
{ try
{
} catch(i18nerr)
{ var locale =kony.i18n.getCurrentDeviceLocale(); alert("current device locale is "+locale[0]); alert("Exception in getCurrentDeviceLocale : "+err );
}
}
20.5 kony.i18n.setResourceBundle
This API allows you to set the specified resource bundle for a given locale. If the specified locale has a resource bundle already set, it is overridden with the given resource bundle.
If no resource bundle has been set previously, this API will create a new resource bundle.
© 2015 by Kony, Inc. All rights reserved 368 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.5.1 Use Cases
You must set the resource bundle for a given locale to have internationalization support for that locale.
20.5.2 Signature
JavaScript: kony.i18n.setResourceBundle(
,
)
20.5.3 Input Parameters inputtable [Table] - Mandatory
Specifies the resource bundle that needs to be set for the given locale.
locale [String] - Mandatory
Specifies the locale for which the resource bundle needs to be set.
20.5.4 Return Values
None
20.5.5 Exceptions
1300 - i18n error or Locale not supported error, Locale not supported.
20.5.6 Platform Availability
Available on all platforms.
20.5.7 JavaScript Example function setResourceBundle()
{ try{
© 2015 by Kony, Inc. All rights reserved 369 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
kony.i18n.setResourceBundle
({btn1:"FirstName",btn2:"LastName"}, "en_US") alert(" Set ");
} catch(i18nError)
{ alert("Exception While getting setResourceBundle :
"+i18nError );
}
}
20.6 kony.i18n.updateResourceBundle
This API allows you to append new key-value pairs to the given resource bundle for a specified locale.
The key-value pairs you provide will be appended at the end of the resource bundle.
If no resource bundle exists for the specified locale, a new resource bundle is created.
20.6.1 Signature
JavaScript: kony.i18n.updateResourceBundle(
20.6.2 Input Parameters inputtable [Table] - Mandatory
Specifies the set of key-value pairs that needs to be added to the resource bundle.
locale [String] - Mandatory
Specifies the locale for which the resource bundle needs to be updated with the given values.
© 2015 by Kony, Inc. All rights reserved 370 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.6.3 Return Values
None
20.6.4 Exceptions
1300 - i18n error or Locale not supported error
20.6.5 Platform Availability
Available on all platforms.
20.6.6 JavaScript Example function updateResourceBundle()
{ try{ kony.i18n.updateResourceBundle({1:"John",2:"Jack",3:"Tom"}, "en_
US") alert(" Updated ");
} catch(i18nError)
{ alert("Exception While getting updateResourceBundle : "+i18nError
);
}
}
20.7 kony.i18n.isResourceBundlePresent
This API checks if a resource bundle exists for a given locale and returns a boolean value.
© 2015 by Kony, Inc. All rights reserved 371 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.7.1 Signature
JavaScript:
kony.i18n.isResourceBundlePresent ( locale
)
20.7.2 Input Parameters locale [String] - Mandatory
Specifies the locale for which the resource bundle is checked.
20.7.3 Return Values status [Boolean] true - if the resource bundle exists for the given locale.
false - if no resource bundle exists for the given locale.
20.7.4 Exceptions
1300 - i18n error or Locale not supported error
20.7.5 Platform Availability
Available on all platforms except SPA and Desktop Web.
20.7.6 JavaScript Example
// Method for checking the resources bundle present or not--> function isResourceBundlePresent()
{ try{ var exists = kony.i18n.isResourceBundlePresent("en_US"); alert("isResourceBundlePresent :"+exists);
}
© 2015 by Kony, Inc. All rights reserved 372 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
catch(i18nError)
{ alert("Exception While getting isResourceBundlePresent :
"+i18nError );
}
}
20.8 kony.i18n.isLocaleSupportedByDevice
This API provides you the ability to view whether a locale is supported by a device.
20.8.1 Signature
JavaScript: kony.i18n.isLocaleSupportedByDevice(
20.8.2 Input Parameters locale [String] - Mandatory
Specifies the locale that must be verified if it is supported by the device.
locale must be in one of the following formats: l language_countryCode l language
For example, kony.i18n.isLocaleSupportedByDevice("en_US") kony.i18n.isLocaleSupportedByDevice("fr")
20.8.3 Return Values status [Boolean]
Indicates the status if the specified locale is supported by the device.
© 2015 by Kony, Inc. All rights reserved 373 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
l true - if the specified locale is supported by the device.
l false - if the specified locale is not supported by the device.
20.8.4 Exceptions
1300 - i18n error or Locale not supported error
20.8.5 Platform Availability
Available on all platforms except SPA and Desktop Web.
20.8.6 JavaScript Example function isLocaleSupportedByDevice()
{ try
{ var isPresent =kony.i18n.isLocaleSupportedByDevice("zh_CN"); alert("locale supported by device "+isPresent);
} catch(i18nerr)
{ alert("Exception in isLocaleSupportedByDevice : "+err );
}
} var isPresent =kony.i18n.isLocaleSupportedByDevice("en_us"); kony.print (isPresent);
20.9 kony.i18n.getLocalizedString
This API returns the localized string that corresponds to the specified i18n Key.
© 2015 by Kony, Inc. All rights reserved 374 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.9.1 Signature
JavaScript: kony.i18n.getLocalizedString(
)
20.9.2 Input Parameters i18nkey [String]- Mandatory
Specifies the internationalization key for which the localized string needs to be returned.
20.9.3 Return Type
Localizedstring [String]
Returns the localized string corresponding to the key value.
20.9.4 Exceptions
1300 - i18n error or Locale not supported error
20.9.5 Platform Availability
Available on all platforms.
20.9.6 JavaScript Example
// Method for getLocalizedString --> function getLocalizedString()
{ try{ var currentLocales = kony.i18n.getLocalizedString("1"); var currentLocales1 = kony.i18n.getLocalizedString("2"); alert(" LocalizedString Method called :"+currentLocales+"
"+currentLocales1);
}
© 2015 by Kony, Inc. All rights reserved 375 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
catch(i18nError)
{ alert("Exception While getting localizedString : "+i18nError );
}
}
20.10 kony.i18n.deleteResourceBundle
This API allows you to delete an existing resource bundle. If a resource bundle does not exist, the API will return without performing any operation. Only resource bundles which are newly created using the setResourceBundle API will be deleted. The bundle which are created by IDE, cannot be deleted, but they can only be updated.
20.10.1 Signature
JavaScript: kony.i18n.deleteResourceBundle(
)
20.10.2 Input Parameters locale [String] - Mandatory
Specifies the locale for which the resource bundle needs to be deleted.
20.10.3 Return Values
None
20.10.4 Exceptions
1300 - i18n error or Locale not supported error
20.10.5 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 376 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.10.6 JavaScript Example
// Method for delete the resource bundle --> function deleteResourceBundle()
{ try{ kony.i18n.deleteResourceBundle("en_US"); alert(" Resources bundle has been deleted.");
} catch(i18nError)
{ alert("Exception While getting deleteResourceBundle : "+i18nError
);
}
}
20.11 kony.i18n.setDefaultLocaleAsync
Every application that has support for internationalization needs a locale to be set as a default locale.
This API allows you to set the specified locale as the default locale for the application. You can also set the default locale from the IDE. However, this API allows you to perform that task dynamically.
20.11.1 Use Cases
You must set the resource bundle for a given locale to have internationalization support for that locale.
20.11.2 Signature
JavaScript:
kony.i18n.setDefaultLocaleAsync( localename
,
,
© 2015 by Kony, Inc. All rights reserved 377 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.11.3 Input Parameters localename [String] - Mandatory
Specifies the locale that must be set as the default locale of the application.
onsuccesscallback [Function] - Mandatory onsuccess callback is called by the platform after successfully setting the specified locale as default.
onsucess(oldlocalename, newlocalename)
{
\\code
} onfailurecallback [Function] - Mandatory onfailure callback will be called by the platform if the locale is not set successfully.
onfailure (errCode, errMsg)
{
\\code
} info [Object] - Optional
A JavaScript object consisting of key value pairs. If info parameter is specified, it is passed to the callback function as a last parameter. If the info parameter is not specified, the callback function receives the info as null/nil. "Info" is basically a user data where in the application developers will
© 2015 by Kony, Inc. All rights reserved 378 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
pass it to the async API's and the platform returns this info object to the corresponding async callback.This parameter is helpful for developers to remember the context when the methods are called in asynchronous fashion.Developers can define any custom keys and values within the info
Object based on the needs. These are not predefined keys with values.
20.11.4 Return Values
None
20.11.5 Exceptions
1300 - i18n error or Locale not supported error
20.11.6 Platform Availability
Available on all platforms.
20.11.7 JavaScript Example function setDefaultLocaleAsync()
{ try
{ kony.i18n.setDefaultLocaleAsync("en_US", onsuccesscallback, onfailurecallback); alert("current locale is set to "+kony.i18n.getCurrentLocale());
} catch(i18nerr)
{ alert("Exception in setDefaultLocaleAsync : "+err );
}
}
© 2015 by Kony, Inc. All rights reserved 379 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.12 kony.i18n.setCurrentLocaleAsync
This API provides you the ability to set the specified locale as the current locale of the application. If the locale is not supported by the device, junk characters are displayed on the screen for the locale specific string.
20.12.1 Use Cases
You must set the resource bundle for a given locale to have internationalization support for that locale.
20.12.2 Signature
JavaScript: kony.i18n.setCurrentLocaleAsync(
,
,
20.12.3 Input Parameters localename [String] - Mandatory
Specifies the locale that must be set as the current locale of the application.
onsuccesscallback [Function] - Mandatory onsuccess callback will be called by the platform after a locale is set successfully as the current locale.
onsucess(oldlocalename, newlocalename)
{
\\code
} onfailurecallback [Function] - Mandatory onfailure callback will be called by the platform if the locale is not set successfully.
© 2015 by Kony, Inc. All rights reserved 380 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
onfailure (errCode, errMsg)
{
\\code
} info [Object] - Optional
A JavaScript object consisting of key value pairs. If info parameter is specified, it is passed to the callback function as a last parameter. If the info parameter is not specified, the callback function receives the info as null/nil. "Info" is basically a user data where in the application developers will pass it to the async API's and the platform returns this info object to the corresponding async callback.This parameter is helpful for developers to remember the context when the methods are called in asynchronous fashion.Developers can define any custom keys and values within the info
Object based on the needs. These are not predefined keys with values.
20.12.4 Return Values
None
20.12.5 Exceptions
1300 - i18n error or Locale not supported error
20.12.6 Platform Availability
Available on all platforms.
20.12.7 JavaScript Example function setCurrentLocaleAsync()
{ try
{ kony.i18n.setCurrentLocaleAsync("en_GB", onsuccesscallback,
© 2015 by Kony, Inc. All rights reserved 381 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
onfailurecallback); alert("current locale is set to "+kony.i18n.getCurrentLocale());
} catch(i18nerr)
{ alert("Exception in setCurrentLocaleAsync : "+err );
}
}
20.13 Deprecated APIs
The following APIs have been deprecated from 5.0 onwards and are only supported for backward compatibility.
l
l
20.13.1 kony.i18n.setCurrentLocale
This API provides you the ability to set the specified locale as the current locale of the application. If the locale is not supported by the device, junk characters will be displayed on the screen for the locale specific string.
20.13.1.1 Signature
JavaScript:
kony.i18n.setCurrentLocale( locale
)
20.13.1.2 Input Parameters locale [String] - Mandatory
Specifies the locale that must be set as the current locale of the application
© 2015 by Kony, Inc. All rights reserved 382 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.13.1.3 Return Values errorcode [Number]
A number that denotes the error.
l
0 - Locale is successfully applied l
100 - The supplied locale is not available in the device.
l
101 - The supplied locale is not available in application
20.13.1.4 Error Codes l
100 - if the locale is not supported by device l
101 - if the locale is supported by device but not by the application
20.13.1.5 Implementation Details
This section explains how this API is implemented. This API: l sets the appropriate display language and region for displaying content and images in the application l sets the specified locale as the input locale (keyboard and calendar display) if the specified locale is available - on Android and BlackBerry l displays junk characters for the locale specific string if the specified locale is not supported by the device l does not re-initialize the widgets that have already loaded the i18n content. For example, assume that an application has 2 forms frmA and frmB.
o frmA is the startup form and loads the content using i18n.getlocalizedstring API. The current locale for the device is en_US and English text is populated on the form.
o onclick event of the button on this form invokes i18n.setcurrentlocale("fr_FR")
© 2015 by Kony, Inc. All rights reserved 383 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
o
Invoking this API at this stage will not cause the widgets to reload the data for frmA widgets from fr_FR resource bundle.
20.13.2 Platform Availability l
Android l
BlackBerry l
BlackBerry 10 l
Windows Phone/Windows Kiosk/Mango
20.13.3 kony.i18n.setDefaultLocale
Every application that has support for internationalization needs a locale to be set as a default locale.
This API allows you to set the specified locale as the default locale for the application. You can also set the default locale from the IDE. However, this API allows you to perform that task programmatically.
20.13.3.1 Signature
JavaScript: kony.i18n.setDefaultLocale(
)
20.13.3.2 Input Parameters locale [String] - Mandatory
Specifies the locale that needs to be set as default locale for the application
20.13.3.3 Return Values
None.
20.13.3.4 Error Codes l
100 - if the locale is not supported by device l
101 - if the locale is supported by device but not by the application
© 2015 by Kony, Inc. All rights reserved 384 of 848
20. Internationalization APIs Kony Studio API Developer's Guide
Version 5.0
20.13.3.5 Implementation Details
This API is invoked in the background when the code is generated for an application to set the default locale.
20.13.4 Platform Availability
Available on all platforms except J2ME.
© 2015 by Kony, Inc. All rights reserved 385 of 848
21. Language APIs Kony Studio API Developer's Guide
Version 5.0
21. Language APIs
In JavaScript, exceptions that occur during runtime are usually handled using try/catch blocks.
Language APIs are implemented for exceptions that are not handled using try/catch blocks.
Following are the two Language APIs implemented to handle uncaught exceptions:
1.
kony.lang.setUncaughtExceptionHandler
2.
kony.lang.getUncaughtExceptionHandler
21.1 kony.lang.setUncaughtExceptionHandler
The kony.lang.setUncaughtExceptionHandler API sets a JavaScript function as an exception handler for all uncaught exceptions. The JavaScript function takes one argument that is the JavaScript exception object. A developer can query the properties of this object like any other JavaScript object.
21.1.1 Signature kony.lang.setUncaughtExceptionHandler(
21.1.2 Arguments
JavaScript Function object [Function] - Mandatory
Call back function that is called when an uncaught exception is raised by JavaScript engine.
Following is the signature of the function object:
Function <FuncName> ( exceptionObject)
<handler code>
End
21.1.3 Return Values
None
© 2015 by Kony, Inc. All rights reserved 386 of 848
21. Language APIs Kony Studio API Developer's Guide
Version 5.0
21.1.4 Platform Availability
Available in iOS and Android platforms.
21.1.5 JavaScript Example function uncaughtExceptionHandler(exceptionObject) {
// Converting exception object into a readable string var exceptionString = ""; if("sourceURL" in exceptionObject){ exceptionString += exceptionObject.sourceURL;
} if("line" in exceptionObject){ exceptionString += " line # " + exceptionObject.line;
} if("message" in exceptionObject){ exceptionString += " : " + exceptionObject.message;
}
//Logging the exception string to console kony.print("Unhandled Exception:" + exceptionString);
} kony.lang.setUncaughtExceptionHandler(uncaughtExceptionHandler);
21.2 kony.lang.getUncaughtExceptionHandler
The kony.lang.getUncaughtExceptionHandler API retrieves the reference to a JavaScript function that is currently set as an exception handler for all uncaught exceptions.
© 2015 by Kony, Inc. All rights reserved 387 of 848
21. Language APIs Kony Studio API Developer's Guide
Version 5.0
21.2.1 Signature kony.lang.getUncaughtExceptionHandler()
21.2.2 Return Values
JavaScript value containing the function reference.
21.2.3 Platform Availability
Available in iOS and Android platforms.
21.2.4 JavaScript Example var funtionObject = kony.lang.getUncaughtExceptionHandler();
© 2015 by Kony, Inc. All rights reserved 388 of 848
22. Live Tiles Kony Studio API Developer's Guide
Version 5.0
22. Live Tiles
Live Tiles enable you to represent an application as a tile on the Start Screen of your device. You can launch the application using a Live Tile. Secondary Live tiles are secondary tiles for the same application and can be used for deeplinking to forms. For more information on Live Tiles refer to http://msdn.microsoft.com/en-us/library/hh202948%28v=vs.92%29.aspx.
The APIs in this chapter provide you with the ability to set tiles for an application.
22.1 kony.application.setAppTile
This API enables you to set the data for an application tile. If the user chooses to pin the application tile, the data set is visible. For more information on pinning a tile, refer http://www.microsoft.com/windowsphone/en-us/howto/wp7/start/move-or-delete-tile-on-start.aspx
.
22.1.1 Signature
JavaScript: Mango: kony.application.setAppTile (
)
Windows 8: kony.application.setAppTile(
,
)
Windows 8: setapptile(
))
22.1.2 Input Parameters for Mango frontTileData [Object] - Mandatory, If you do not set the front tile data, a default image and values will be used
Specifies the data to be displayed at the front of a tile. This hash table has the following inputs: l title [String] - Specifies the title to be displayed at the front of a tile.The title appears at the bottom of the tile as white text.
l backgroundImage [String] - Specifies the background image to be displayed at the front of a tile.
© 2015 by Kony, Inc. All rights reserved 389 of 848
22. Live Tiles Kony Studio API Developer's Guide
Version 5.0
Note: The backgroundImage will use the specified image to fill the entire space of the tile, regardless of its actual size.
l count [integer] - specifies a number to be displayed at the top - right corner of the tile. The count value is displayed in a small black circle in white text.
Note: The colors, sizes, and layout of the count and the title do not ever change.
backTileData[Object] - Optional
Specifies the data to be displayed at the back of a tile. This table has the following key - value pairs: l title [String] - specifies the title to be displayed at the back of a tile.The title value appears at the bottom of the tile as white text.
l backBackgroundImage [String] - specifies the background image to be displayed at the back of a tile.
l backcontent [String] - specifies the content to be displayed at the back of a tile. The back content appears at the top of the tile as white text.
Note: The colors, sizes, and layout of the back content and the title do not ever change.
You can also set the backTileData to be nil. In this case, no information will be set on the back of the tile and the tile will not flip.
22.1.3 Input Parameters for Windows 8 tileTemplateType [String] - Mandatory tileTemplateType is a string describing which tile template to use. Refer the tile template catalog for the list of supported tile templates:
© 2015 by Kony, Inc. All rights reserved 390 of 848
22. Live Tiles Kony Studio API Developer's Guide
Version 5.0
tileTemplateData [Array] - Optional tileTemplateData is an array of data for the tile, according to the tileTemplateType being used.
The tile template catalog . contains details of the data required for each tile template.
22.1.4 Return Values
None
22.1.5 UI Behavior - Mango
The Titles of both front and back tiles are displayed in white and this behavior cannot be changed even if the user sets a different theme or a background image. The count value for the front tile is displayed in a small black circle in white text at the top-right corner of the tile. The back content appears at the top-left corner of the tile as white text and is left justified.
Considering we have set values for both the frontTileData and the backTileData, the tiles might appear as follows:
Front Tile Back Tile
22.1.6 UI Behavior - Windows 8
The title and the display name of the tile will be displayed in white or black depending on the setting in
Kony Studio and this behavior cannot be changed even if the user sets a different theme or a background image. Unlike Mango. tiles cannot be flipped on Windows 8. The tile can be updated dynamically in Windows 8.
© 2015 by Kony, Inc. All rights reserved 391 of 848
22. Live Tiles Kony Studio API Developer's Guide
Version 5.0
22.1.7 Platform Availability
Available on Windows Mango, Windows Phone 8, and Windows 8.
22.1.8 JavaScript Example
JavaScript Example1- Mango frontTileData:{"Front Tile Title", "test.png", 20} backTileData:{"Front Tile Title", "test.png", "This is the back tile content"} kony.application.setAppTile( frontTileData, backTileData );
JavaScript Example2 - Windows 8 kony.application.setAppTile( "TileSquareBlock", ["Hello", "World!"]
);
22.2 kony.application.setSecondaryTile
This API enables you to create or update data for a secondary tile for an application. For more information about secondary tiles, refer Secondary tiles .
22.2.1 Signature
JavaScript:Mango
kony.application.setSecondaryTile( id , frontTileData , backTileData
)
© 2015 by Kony, Inc. All rights reserved 392 of 848
22. Live Tiles Kony Studio API Developer's Guide
Version 5.0
Windows 8: kony.application.setSecondaryTile(
,
,
)
Windows 8: setsecondarytile(
,
shortname , displayname , imagename
)
22.2.2 Input Parameters for Mango id [String] - Mandatory
Unique identifier of the secondary tile.
frontTileData [Object] - Mandatory, If you do not set the front tile data, a default image and values will be used
Specifies the data to be displayed at the front of a tile. This hash table has the following inputs: l title [String] - Specifies the title to be displayed at the front of a tile.The title appears at the bottom of the tile as white text.
l backgroundImage [String] - Specifies the background image to be displayed at the front of a tile.
Note: The backgroundImage will use the specified image to fill the entire space of the tile, regardless of its actual size.
l count [integer] - specifies a number to be displayed at the top - right corner of the tile. The count value is displayed in a small black circle in white text.
Note: The colors, sizes, and layout of the count and the title do not ever change.
backTileData[Object] - Optional
Specifies the data to be displayed at the back of a tile. This table has the following key - value pairs: l title [String] - specifies the title to be displayed at the back of a tile.The title value appears at the bottom of the tile as white text.
© 2015 by Kony, Inc. All rights reserved 393 of 848
22. Live Tiles Kony Studio API Developer's Guide
Version 5.0
l backBackgroundImage [String] - specifies the background image to be displayed at the back of a tile.
l backcontent [String] - specifies the content to be displayed at the back of a tile. The back content appears at the top of the tile as white text.
Note: The colors, sizes, and layout of the back content and the title do not ever change.
You can also set the backTileData to be nil. In this case, no information will be set on the back of the tile and the tile will not flip.
22.2.3 Input Parameters for Windows 8 id [String] - Mandatory
Unique identifier of the secondary tile.
shortname [String] - Mandatory
A short name displayed directly on the tile. Anything over 40 characters will be truncated. The user has the option to change this value as part of the pinning process.
displayname[String] - Optional
The text specified here is displayed when you hover over the tile. There is no restriction on the display name length or the characters that it can contain.
imagename [String] - Optional
Name of the image to be displayed on the tile.
22.2.4 Return Values
None
© 2015 by Kony, Inc. All rights reserved 394 of 848
22. Live Tiles Kony Studio API Developer's Guide
Version 5.0
22.2.5 UI Behavior Mango
The Titles of both front and back tiles are displayed in white and this behavior cannot be changed even if the user sets a different theme or a background image. The count value for the front tile is displayed in a small black circle in white text at the top-right corner of the tile. The back content appears at the top-left corner of the tile as white text and is left justified.
Considering we have set values for both the frontTileData and the backTileData, the tiles are rendered as follows:
Front Tile Back Tile
22.2.6 UI Behavior - Windows 8
The title and the display name of the tile will be displayed in white or black depending on the setting in
Kony Studio and this behavior cannot be changed even if the user sets a different theme or a background image. Unlike Mango. tiles cannot be flipped on Windows 8. The tile can be updated dynamically in Windows 8.
© 2015 by Kony, Inc. All rights reserved 395 of 848
22. Live Tiles Kony Studio API Developer's Guide
Version 5.0
22.2.7 Platform Availability
Available on Windows Mango, Windows Phone 8, and Windows 8.
22.2.8 JavaScript Example
The usage of this API on Mango is shown in the code snippet below:
//Setting the front and back tile data frontTileData:{"Front Tile Title", "test.png", 20 backTileData:{"Front Tile Title", "test.png", "This is the back tile content"}
//Set the secondary tile with the front and back tile data witht ile id 1234 kony.application.setSecondaryTile("1234", frontTileData, backTileData );
The usage of this API on Windows 8 is shown in the code snippet below:
//Setting a secondary tile for an application with tile id myTile1.
kony.application.setSecondaryTile("myTile1", "title text", "display name", "orange.png");
22.3 kony.application.removeSecondaryTile
This API enables you to remove and unpin a specified secondary tile which was created earlier.
22.3.1 Signature
JavaScript: kony.application.removeSecondaryTile(
© 2015 by Kony, Inc. All rights reserved 396 of 848
22. Live Tiles
22.3.2 Input Parameters id [String] - Mandatory
Unique identifier of the secondary tile
22.3.3 Return Values
None
22.3.4 Platform Availability
Available on Windows Mango, Windows Phone 8, and Windows 8.
22.3.5 JavaScript Example kony.application.removeSecondaryTile("12345")
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 397 of 848
23. Math APIs Kony Studio API Developer's Guide
Version 5.0
23. Math APIs
The Math Library has APIs that you can use to perform mathematical operations.
The Math Library has the following APIs:
23.1 math.tointeger
This API converts the float value to an integer. The converted integer value is always the integer part of the specified float number (number before the decimal).
23.1.1 Signature
JavaScript: Deprecated. Use the floor() Object method instead.
23.1.2 Return Values integer [Number]
The return value is an integer
23.1.3 Platform Availability
Available on all platforms.
23.2 math.pow
This API raises the first parameter to the power of the second parameter and returns the result.
23.2.1 Signature
JavaScript: Deprecated. User the pow(x,y) Object method instead.
© 2015 by Kony, Inc. All rights reserved 398 of 848
23. Math APIs Kony Studio API Developer's Guide
Version 5.0
23.2.2 Return Values xy
Raises the first parameter to the power of the second parameter
23.2.3 Implementation Details
It is advisable to use the expression x^y as it is much faster when compared to this API.
23.2.4 Rules and Restrictions l
On BlackBerry platform, this API is supported only from versions 4.6 and above.
l
On BlackBerry versions below 4.6, you need to define a custom Java method to achieve this functionality.
23.2.5 Platform Availability
Available on all platforms.
23.3 math.min
This API returns the minimum value among the arguments.
23.3.1 Signature
JavaScript: Deprecated. Use min(x,y,x,...n) Object instead.
23.3.2 Return Values
Minimum Value [Number]
The return value is the minimum value among all the arguments
© 2015 by Kony, Inc. All rights reserved 399 of 848
23. Math APIs
23.3.3 Platform Availability
Available on all platforms.
23.4 math.max
This API returns the maximum value among the arguments.
23.4.1 Signature
JavaScript: Deprecated. Use max (x,y,..n) instead.
23.4.2 Return Values
Maximum Value [Number]
The return value is the maximum value among all the arguments
23.4.3 Platform Availability
Available on all platforms.
23.5 math.sqrt
This API returns the square root of the given number.
23.5.1 Signature
JavaScript: Deprecated. Use sqrt() object method instead.
23.5.2 Return Values square root [Number]
The square root of the number is returned
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
400 of 848
23. Math APIs Kony Studio API Developer's Guide
Version 5.0
nan (not a number)
This value is returned when the input parameter is a negative number
23.5.3 Platform Availability
Available on all platforms.
23.6 math.random
This API generates pseudo-random numbers which are uniformly distributed. This API generates a real number between 0 and 1.
23.6.1 Signature
JavaScript: Deprecated. Use random() math object method instead.
23.6.2 Return Values pseudo-random number [Number]
A pseudo-random number between the value 0 and 1 is generated
23.6.3 Platform Availability
Available on all platforms.
23.7 math.pi
This API returns the value of pi.
Note: math.pi is not a function, but a property in math namespace.
© 2015 by Kony, Inc. All rights reserved 401 of 848
23. Math APIs Kony Studio API Developer's Guide
Version 5.0
23.7.1 Signature
JavaScript: Deprecated. Use PI Math object property instead.i.e Math.PI
23.7.2 Input Parameters
None.
23.7.3 Return Values value of pi [Number]
Value of pi is returned
23.7.4 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 402 of 848
24. Mobile First APIs Kony Studio API Developer's Guide
Version 5.0
24. Mobile First APIs
24.1 Introduction
In Kony Studio, Mobile First APIs help you use native APIs for iOS and Android platforms. The native
APIs are provided as JavaScript APIs. To access these APIs, you need to follow certain guidelines in
and
platforms. Mobile First APIs include: l
l
l
l
l
Near Field Communication (NFC)
l
24.2 Enabling Mobile First APIs in Kony Studio
To enable Mobile First APIs in Kony Studio for iOS platform, follow these steps:
1. From your Kony Studio, go to the Application Properties window.
2. Navigate to Native > iPhone/iPad tab, and select Enable MobileFirst APIs (HealthKit, Apple
Pay).
© 2015 by Kony, Inc. All rights reserved 403 of 848
24. Mobile First APIs Kony Studio API Developer's Guide
Version 5.0
3. Click Finish.
To enable Mobile First APIs in Kony Studio for Android platform, follow these steps:
1. From your Kony Studio, go to Application Properties window.
2. Navigate to Native > Android tab, and select Enable MobileFirst APIs (NFC, JobScheduler,
Speech, Bluetooth).
© 2015 by Kony, Inc. All rights reserved 404 of 848
24. Mobile First APIs Kony Studio API Developer's Guide
Version 5.0
3. Click Finish.
© 2015 by Kony, Inc. All rights reserved 405 of 848
Kony Studio API Developer's Guide
Version 5.0
24.2.1 iOS Guidelines for Using Mobile First APIs in Kony Studio
To use Mobile First APIs in Kony Studio, follow these guidelines:
Category
Accessing classes
Description
To access a class, use the following API:
24.2.1.1 objc.import
This API allows you to import any iOS native class into JavaScript. You must use the keyword "new" to instantiate (create an object) an instance of a JavaScript class. All the
APIs, methods, constants, and all members of the native class are directly accessible with the instantiated object.
Signature
JavaScript: objc.import (objectiveC_class_name)
Input Parameters objc.import (objectiveC_class_name) - Mandatory
Specifies the native class name including the package name that you want to use in
JavaScript.
Return Values
Returns a JavaScript object
Platform Availability
Available on iOS platform.
JavaScript Example
//Sample code var HKHealthStore = objc.import('HKHealthStore');
© 2015 by Kony, Inc. All rights reserved 406 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Invoking static methods
Description
Static methods can be accessed as properties of the JavaScript object returned by the API objc.import
. For example, the static method isHealthDataAvailable of the class
HKHealthStore can be invoked using the following syntax:
Creating instances var HKHealthStore = objc.import('HKHealthStore'); kony.print(HKHealthStore.isHealthDataAvailable());
For the methods that take one or more arguments in JavaScript, refer to
For the methods that are supported, refer to
In Objective-C, instances of a class are created by using the alloc/init combination or convenience constructors. The alloc and convenience constructors are static methods that can be invoked as described in the
section. Invoking init method is described in the
section.
Instances created either way are JavaScript objects that wrap the underlying Objective-C objects.
Invoking instance methods var HKUnit = objc.import('HKUnit'); var unit = HKUnit.unitFromString('count');
Instance methods of an Objective-C object are available as properties of the JavaScript object that represents the Objective-C object. For example, the instance method reciprocalUnit of HKUnit can be invoked as: var HKUnit = objc.import('HKUnit'); var unit = HKUnit.unitFromString('count'); var runit = unit.reciprocalUnit();
© 2015 by Kony, Inc. All rights reserved 407 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Accessing properties of
Objective-C objects
Description
The properties of an Objective-C object are available as properties of the JavaScript object that wraps the Objective-C object.
Note: OBjective-C accessor methods are not exposed. You can access the properties using JS property notation.
Constants
Prefixed properties:
Any property with type selector/class/block must be prefixed by js.
Both enums and global constants are available as JavaScript globals.
Example 1:
The enum value KHMetricPrefixPico of the enum type HKMetricPrefix is available as HKMetricPrefixPico in JavaScript global space.
//prints 1 kony.print(HKMetricPrefixPico)
Example 2:
The global constant HKCorrelationTypeIdentifierFood is available as the
JavaScript global value of type string with the same name.
© 2015 by Kony, Inc. All rights reserved 408 of 848
Kony Studio API Developer's Guide
Version 5.0
Category Description
Method name convention
A selector that takes one or more arguments can be invoked by using a JavaScript property name that is arrived at by removing all colons and capitalizing any lowercase letter that follows a colon. For example, doFoo:withBar: becomes doFooWithBar.
Prefixed methods: l new, copy, and mutableCopy must be invoked as jsnew, jscopy, and jsmutableCopy , respectively.
l
Any instance method that starts with init and accepts no parameters must be prefixed by js.
l
Any method that returns a selector and accepts no parameters has to be prefixed by js .
© 2015 by Kony, Inc. All rights reserved 409 of 848
Kony Studio API Developer's Guide
Version 5.0
Category Description
Type support An Objective-C method is available only if the parameter type and return type belong to any of the following: n
Primitive types such as char, int, and short are represented as JavaScript number .
n
Objective-C objects are represented as JavaScript objects.
n
Structures CGPoint, CGRect, CGSize, and NSRange are represented as
JavaScript objects with the struct field names as properties.
//For example
CGPoint p={0.0,0.0} is represented by a JavaScript object
{x: 0.0, y: 0.0} n
Any other structures that have fields of types in a, b, and c, then nested structures become nested objects.
//For example
CGRect rect={{0.0,0.0},{1.0,2.0}} is represented by a
JavaScript object {origin:{x: 0.0, y: 0.0}, size:
{width:1.0, height:2.0}} n
Opaque types (for example, CFStringRef:) are represented as JavaScript objects.
n
Selectors are represented as strings. That is the value returned by
NSStringFromSelector . If a method accepts a selector, then pass a string. If a method returns a selector, a string is returned.
n
Classes are represented as JavaScript objects as returned by objc.import API.
n
Blocks are represented as JavaScript functions.
o Pass a JavaScript function to a method that accepts a block as a parameter,
The JavaScript function gets invoked when the block is invoked.
o
If a method returns a block, a JavaScript function is returned.
o Only blocks with parameter types and return type as described in above are supported. The exceptions are:
© 2015 by Kony, Inc. All rights reserved n
Blocks that return another block are not supported.
410 of 848 n
Parameter types bool* and id* are supported. When the JavaScript function gets invoked, a JavaScript object is passed in place of these parameters. To set a value to the parameter, set the property 'contents' of the JavaScript object that the JavaScript function receives.
n When a method accepts NSError** as a parameter, pass a JavaScript object.
Upon return, this object will have the property 'error' set if there was an error.
The same types apply for Objective-C properties.
Kony Studio API Developer's Guide
Version 5.0
Category Description
Memory management
Memory management occurs automatically. You need not invoke release/retain/autorelease.
© 2015 by Kony, Inc. All rights reserved 411 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Creating classes
Description
To create a class, use the following API:
Note: This API can only be used from the main thread and JavaScript thread. Do not call it from a worker thread.
24.2.1.2 objc.newClass
At several places in iOS SDK, a protocol needs to be implemented or an abstract class needs to be extended, so that the iOS framework can invoke a user-defined code. For example, asynchronous APIs expect a callback method that gets invoked with the result.
The purpose of this API is to enable such calling. It is not designed to define arbitrary new
Objective-C classes.
Only the instance methods with
as described can be overridden. The exceptions are: l
Methods that return blocks cannot be implemented.
l
Parameter types bool* and id* are supported. While invoking a JavaScript function that implements an Objective-C method that takes a parameter of these types, a
JavaScript object is passed. To set a value to the parameter, set the property contents of the JavaScript object passed.
From JavaScript side, the resulting class behaves like its base class: l
Instances of the class can be created by calling a base class's constructors.
l
Instances of the class can be acted on as if they are the base class's instances.
In addition, instances also have access to a super method when a method is overridden. The super method can be invoked by prefixing super to the method name.
Inside a JavaScript function that defines or overrides a native instance method, the instance can be accessed by "this".
Signature
JavaScript: objc.newClass(native_class_name, base_class_name, interface_name, interface_name_to_override)
Input Parameters
412 of 848
Specifies the native class name including the package name.
base_class_name [String] - Mandatory
Specifies the class name from which the new class is extended or inherited.
interface_name [String] - Mandatory
Specifies the interface name that can be implemented by the new class.
interface_name_to_override [String] - Mandatory
Specifies the interface name that must be overridden or implemented by the new class.
Return Values
Returns the class that is extended.
Platform Availability
Available on iOS platform.
JavaScript Example
//Sample code var ViewController = objc.newClass('ViewController',
'UIViewController',
['PKPaymentAuthorizationViewControllerDelegate'], { paymentAuthorizationViewControllerDidAuthorizePaymentCompletio n: function(controller, payment, completion) {}, paymentAuthorizationViewControllerDidFinish: function
(controller) {}, paymentAuthorizationViewControllerDidSelectShippingMethodComple tion: function(controller, shippingmethod, completion) {}
});
Note: A handle to the JavaScript object has to be retained to be able to add properties, that represents an instance of a class created using objc.newClass API. If the handle is not retained, you will lose the properties that are added as part of callback functions.
Kony Studio API Developer's Guide
Version 5.0
Category
Variadic methods
Autoconverted types
Description
Support for variadic methods is limited. You can pass a maximum of 10 arguments.
The instances of NSNull, NSString, NSNumber, NSDictionary, NSArray, and NSDate and their derivatives are not available in JavaScript because they are automatically converted to and from null, string, number, object, array, and date JavaScript types.
For example, an Objective-C method, (void) doFooWithId: (NSString*) id data: (NSArray*)data must be called in JavaScript as doFooWithId("foo",
[1,2,3]);
Zones
Threads
Note: A "NSNull" in Objective-C is mapped to a "null" in JavaScript, and "nil" in
Objective-C is mapped to "undefined in JavaScript."
The zones are not available.
In an application developed using Kony Studio, most of the JavaScript execution happens on a separate thread (referred to as JavaScript thread). When you need to invoke a Java API that can only be called from the main thread, use the API
. To resume execution back on JavaScript thread, use the API
For more information on Threading APIs,
.
© 2015 by Kony, Inc. All rights reserved 413 of 848
Kony Studio API Developer's Guide
Version 5.0
Category Description
Presenting viewControlle r
If you want to present your own viewController, you have to present it as a modal View
Controller on top of the existing rootView Controller. The current rootViewController can be accessed as UIApplication.sharedApplication
().keyWindow.rootViewController
.
For example, if "vc" is the new viewController, you can use the following methods to present and dismiss the view controllers.
//To display the new UI viewController
UIApplication.sharedApplication().keyWindow.rootViewController.
presentViewControllerAnimatedCompletion(vc, true, null);
//To dismiss the new UI viewController
UIApplication.sharedApplication().keyWindow.rootViewController.
dismissViewControllerAnimatedCompletion(true, null);
© 2015 by Kony, Inc. All rights reserved 414 of 848
Kony Studio API Developer's Guide
Version 5.0
24.2.2 HealthKit
HealhKit is a framework provided Apple Inc., that stores data on your device in a central location called
Health app. Health app is pre built in iOS 8 and above devices. The app has different health parameters to measure your health like sleep analysis, body mass index, etc. The app can store two types of data, characteristic and non-characteristic. A characteristic data is a type of data that is not represented by a sample such as Sex, Birth Date, and Blood Type. HealthKit treats this data differently than the rest of the data it stores as you do not have multiple copies of it. Non-characteristic data are represented by a sample such as Blood Glucose, Body Temperature, Blood Pressure etc., are stored in your Health app. You can decide which information to be shared with your health and fitness apps.
Important: This API is available on iOS platform only.
Some benefits of HealthKit are: l
Users can monitor their own blood pressure and heart beat.
l
Doctors can collate data and monitor the patient’s condition remotely.
l
Users can track the burnt Calories, Body Mass Index (BMI), Body Temperature and so on.
For more information on HealthKit, click here .
24.2.2.1 APIs
Click here , to view HealthKit APIs.
24.2.2.2 Sample Application
Click here to download sample health application.
© 2015 by Kony, Inc. All rights reserved 415 of 848
Kony Studio API Developer's Guide
Version 5.0
24.2.3 Apple Pay
Apple Pay is a secure mobile payment and digital wallet service by Apple Inc., using which you can make contactless payments using your iPhone 6, iPhone 6 Plus, and Apple Watch. Your credit and debit card information is stored in Apple Passbook. Your card information is securely encrypted and a unique Device Account Number is used when you make your payments. If your iPhone is stolen or lost, you can sign in to iCloud and put your device in Lost Mode. This will eventually suspend Apple
Pay from misuse.
Important: This API is available on iOS platform only.
The stores that accept contactless payments will display one of these symbols at checkout.
Some benefits of Apple Pay are: l
Simple to set up and ease of use.
l
Secure and safe payment method.
l
You need not carry your cards all the time to make payments.
For more information on Apple Pay, follow the links: l
Configuring Your Environment l
Creating a Payment Request l
Authorizing a Payment l
Payment Processing
24.2.3.1 APIs
Click here , to view Apple Pay APIs.
© 2015 by Kony, Inc. All rights reserved 416 of 848
Kony Studio API Developer's Guide
Version 5.0
Note: The PKPaymentButton class is not available in JavaScript. Alternatively, you have to download the Apple Pay button resources and use them on a Kony button to achieve the look desired for an Apple Pay button.
24.2.3.2 Sample Application
Click here to download sample application for Apple Pay.
24.2.4 Android Guidelines for Using Mobile First APIs in Kony Studio
To use the Mobile First APIs in Kony Studio, follow these guidelines:
© 2015 by Kony, Inc. All rights reserved 417 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Accessing classes
Description
To access a class, use the following API:
24.2.4.1 java.import
This API helps you import any Android native class into JavaScript. You must use the keyword "new" to instantiate (create an object) an instance of a
JavaScript class. All the APIs, methods, constants, and all members of the native class are directly accessible with the instantiated object.
Signature
JavaScript: java.import (native_class_name)
Input Parameters native_class_name [String] - Mandatory
Specifies the native class name including the package name that you want to use in JavaScript.
Return Values
Returns a JavaScript constructor function that can be used to instantiate the class. The constructor function also has properties that map to the following:
1. Static fields: Any static fields that the Java class exposes.
2. Static methods: Any static methods that the Java class exposes.
3. Inner classes: Any inner classes that the Java class defines.
Platform Availability
Available on Android platform.
JavaScript Example
//Sample code var Thread = java.import('java.lang.Thread');
© 2015 by Kony, Inc. All rights reserved 418 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Instantiating Java classes
Description
The instances of a Java class can be created with the keyword "new" on the constructor function returned by the API java.import. For example, var ArrayList = java.import('java.util.ArrayList'); var alist = new ArrayList();
If the class has overloaded constructor methods, each of them can be called with the keyword "new" by passing the correct parameter types.
Alternatively, the API java.newInstance can be used to instantiate a Java class by passing the instance name as its first argument and the arguments to the constructor method enclosed in a JavaScript array as the second argument.
java.newInstance('class_name', [arg1, arg2, ...]);
Invoking static methods Static methods can be accessed as properties of the constructor function returned by the API java.import. Static methods can be invoked using the following syntax: var c = java.import('...'); c.static_method(arg1, arg2, ...);
Alternatively, the API java.callStaticMethod can be used as follows: java.callStaticMethod('class_name', 'static_method',
[arg1, arg2, ...]);
© 2015 by Kony, Inc. All rights reserved 419 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Accessing static fields
Description
Static fields can be accessed as properties of the constructor function.
c.static_field = 10; var f = c.static_field;
Alternatively, you can use the following APIs: l
The API java.getStaticFieldValue can be used to retrieve a static field by passing the class name as the first argument and the field name as the second argument.
java.getStaticFieldValue('class_name', 'field_ name') l
The API java.setStaticFieldValue can be used to set a static field by passing the class name as the first argument, and the field name as second argument and the value to set as last argument.
java.setStaticFieldValue('class_name', 'field_ name', value)
© 2015 by Kony, Inc. All rights reserved 420 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Accessing inner classes defined by a Java class.
Description
When a Java class defines inner classes, these classes can be accessed as properties of the constructor function that java.import returns. The value returned when such properties are accessed is again another JavaScript constructor function.
var c = java.import('class_name'); var ic = c.ic; var i = new ic(arg1, arg2, ...);
Note: It is possible for a Java class to have a static field, a static method, and an inner class with the same name. In such case, the inner class gets highest priority. Between the field and method, field gets higher priority.
When a method is unavailable as a property, then use the API java.callStaticMethod
to access the static method. When a field is unavailable as a property, then use the API java.setStaticField or java.getStaticField.
Using Java objects The value returned by calling new on the constructor function returned by java.import
is a JavaScript object that represents the underlying Java object.
It has properties that represent the following:
1. Instance methods of the object.
2. Instance fields of the object.
© 2015 by Kony, Inc. All rights reserved 421 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Invoking instance methods
Description
You can invoke instance methods as follows: var c = java.import('class_name'); var i = new c(arg1, arg2, ...); i.instance_method();
Alternatively, the API java.callMethod can be used as follows: java.callMethod(i, 'instance_method',
[arg1,arg2,....]);
Accessing instance fields You can access the instance fields as follows: var if = i.instance_field; i.instance_field = 'abc';
Note: In Java a class can have an instance method and instance field with same name. Fields get priority over method. Therefore when a method is shadowed by a field, the method can be invoked using java.callMethod.
© 2015 by Kony, Inc. All rights reserved 422 of 848
Category
Types
Kony Studio API Developer's Guide
Version 5.0
Description
Java to JavaScript
When Java returns a value to JavaScript, or passes a value to a callback, Java values are converted to JavaScript values, as follows: l null -> null l void -> undefined l boolean -> boolean l
String -> string l byte -> Byte object l long -> Long object l int -> Integer object l short -> Short object l double -> Double object l float -> Float object
Java arrays are converted to JavaScript arrays with individual elements converted, as above.
All other Java objects are wrapped in JavaScript objects. These objects behave as described in
.
JavaScript to Java
When invoking Java methods, JavaScript values passed are converted to Java values, as below: l null, undefined -> null l string -> String object l int -> Integer object l number - >Double object boolean -> Boolean object 423 of 848 l
JavaScript objects that represent Java objects -> Java objects l
All other JavaScript Objects - > null
JavaScript arrays are converted to Java object arrays with individual elements converted as above.
When a Java method parameter type is byte, short, long, char, and float (that do not have an equivalent representation in JavaScript), the APIs java.newByte, java.newShort, java.newLong, java.newChar
, and java.newFloat
can be used to create correct type. Each of these APIs accepts a JavaScript number as argument.
var b = java.newByte (10);
When a Java method parameter type is an array, the API java.newArray can be used to create a Java array. The first argument to java.newArray can be
'byte', 'char', 'short', 'double', 'int', 'boolean' or a class name. The second argument to java.newArray is a JavaScript array with individual elements that belong to the type described by the first argument.
var byteArray = java.newArray(‘byte’, [ java.newByte
(1), java.newByte(2), java.newByte(3) ]);
Category
Exceptions
Kony Studio API Developer's Guide
Version 5.0
Description
When Java throws an exception while performing any of the following operations, an error is thrown in JavaScript. The message property of the error object contains the Java exception in its entirety - exception type, exception message, and stack trace.
n
Import a Java class n
Create instances of a class n Invoke static methods n
Get/Set static fields (including inner classes) n
Invoke instance methods n
Get/Set instance fields
© 2015 by Kony, Inc. All rights reserved 424 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Creating classes
Description
To create a class, use the following API:
24.2.4.2 java.newClass
This API allows you to extend or implement any Android native, Java class, or interface.
Note: This API can only be used from the main thread and JavaScript thread. Do not call it from a worker thread.
Signature
JavaScript: java.newClass(native_class_name)
Input Parameters native_class_name [String] - Mandatory
Specifies the native class name including the package name.
base_class_name [String] - Mandatory
Specifies the class name from which the new class is extended or inherited.
Interface_name [String] - Mandatory
Specifies the interface name that is implemented by the new class.
Interface_name_to_override [String] - Mandatory
Specifies the interface name that must be overridden or implemented by the new class.
Return Values
Returns the class that is created.
Platform Availability
Available on Android platform.
JavaScript Example
© 2015 by Kony, Inc. All rights reserved
//Sample code var c = java.newClass('MyRunnable',
'java.lang.Object', [ 'java.lang.Runnable' ], {
425 of 848 run: function () { print('hello from thread');
}
}); var i = new c(); var Thread = java.import('java.lang.Thread'); var thread = new Thread(i); thread.start();
Note: Memory Management: An Instance of a class created using the API java.newClass
requires a JavaScript object to operate. This JavaScript object becomes “this” in the JavaScript functions that implement the methods of the class. As such the JavaScript object holds a reference to the
Java object (for example, to be able to call super methods) and the Java object holds a reference to the JavaScript object (to be able pass it as
“this” ), creating a circular reference. Hence it is required to call the API java.unref
on an instance of a class created by using java.newClass
when the instance is no longer needed. For example, if a class is created to make an HTTP request, when the HTTP request finishes, java.unref
needs to be called on “this” in both success and failure callbacks.
Category
Other APIs
Threads
Kony Studio API Developer's Guide
Version 5.0
Description
The following is an API that must be used in Mobile First APIs:
24.2.4.3 java.instanceOf
This API is used to find out if a Java object wrapped in a JavaScript object is an instance of a class.
Signature
JavaScript: java.instanceOf (firstargument, secondargument)
Input Parameters firstargument [String] - Mandatory
Specifies the JavaScript object.
secondargument [String] - Mandatory
Specifies the class name.
Return Values
Returns true if the passed Java object is an instance of the class else it returns false.
Platform Availability
Available on Android platform.
In a Kony application, most of a JavaScript execution happens on a separate thread (JavaScript thread). When you need to invoke a Java API that can only be called from the main thread, use the API
. To resume execution back on the JavaScript thread, use the API
For more information on Threading APIs,
© 2015 by Kony, Inc. All rights reserved 426 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Getting Android activity context
Description
The following is a sample code to get the Android activity context: var KonyMain = java.import
('com.konylabs.android.KonyMain'); var context = KonyMain.getActivityContext();
© 2015 by Kony, Inc. All rights reserved 427 of 848
Kony Studio API Developer's Guide
Version 5.0
Category
Lifecycle events
Description
The Kony Android UI framework is based on a single Activity model, and all the application forms are rendered in the same KonyMain activity. You need to be notified about KonyMain activity life cycle events in FFI and MobileFabric APIs space. The Kony Android platform helps you register for KonyMain activity life cycle events using the following API:
KonyMain.addActivityLifeCycleListener(KonyActivityLifeCycleListener listener);
You can also unregister for Activity life cycle events using following API.
KonyMain.removeActivityLifeCycleListener(KonyActivityLifeCycleListener listener)
For more information on Activity lifecycle events, click here .
public class MyKonyActivityLifeCycleListener extends
KonyActivityLifeCycleListener {
@
Override public void onCreate(Bundle savedInstanceState) {}
@
Override public void onStart() {}
@
Override public void onRestart() {}
@
Override public void onResume() {}
@
Override public void onPause() {}
428 of 848
Override public void onStop() {}
@
Override public void onDestroy() {}
@
Override public void onNewIntent(Intent intent) {}
@
Override public void onActivityResult(int requestCode, int resultCode, Intent data) {}
}
//Registering listener
KonyActivityLifeCycleListener listener = new
MyKonyActivityLifeCycleListener();
KonyMain.addActivityLifeCycleListener(listener);
//Unregistering listener when not needed
KonyMain.removeActivityLifeCycleListener(listener);
Kony Studio API Developer's Guide
Version 5.0
24.2.5 Bluetooth
Bluetooth APIs allow a mobile device to scan other devices, connect, and wirelessly exchange data with other Bluetooth devices. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.
Important: This API is available on Android platform only.
Using the Bluetooth APIs, an Android application can perform the following: l
Scan for other Bluetooth devices.
l
Identify paired Bluetooth devices.
l
Establish Radio Frequency Communication (RFCOMM) channels.
l
Connect to other devices through service discovery.
l
Transfer data to and from other devices.
l
Manage multiple connections.
For more information on Bluetooth APIs, click here .
APIs
Click here to view Bluetooth APIs.
24.2.6 JobScheduler
The JobScheduler API helps schedule background tasks that are executed in your application. This
API allows you to execute batch jobs that are nonuser facing jobs or that do not require any interaction, such as jobs that download/upload data from the network.
Important: This API is available on Android platform only.
© 2015 by Kony, Inc. All rights reserved 429 of 848
Kony Studio API Developer's Guide
Version 5.0
You may want to run a task later or under certain conditions, such as when a device is plugged into a power source or connected to a Wi-Fi network. The JobScheduler API performs an operation for your application when such predefined conditions are met.
Following are some examples of when to use JobScheduler APIs: l
Tasks that do not require user interaction.
l
Tasks that should be done once the device is connected to the power supply.
l
Tasks that require network access or a Wi-Fi connection.
l
Tasks that should regularly run as batch where the timing is not critical.
For more information on JobScheduler APIs, click here .
APIs
Click here to view JobScheduler APIs.
Limitations
Following are the limitations of JobScheduler APIs: l
Jobs scheduled using the JobScheduler API will work only when the application is running in the foreground or background.
l
Jobs scheduled using the JobScheduler API will not work when the application is not running, because of the following reasons: n
To schedule any job, a JobService needs to be created and passed as a parameter to
Jobscheduler.
n
A service in Android can run when the app is in the foreground as well as in the background. If you initiate JobService from JavaScript code, the service can run even when the app is in the background.
© 2015 by Kony, Inc. All rights reserved 430 of 848
Kony Studio API Developer's Guide
Version 5.0
n
A JobService can get triggered by an event configured even when the app is in the background. When that occurs JobService will not be available because this class is created at run time from JavaScript code. This class is not a Java class.
l
Other limitations, mostly from Android M developers preview version: n
Every service must be declared in the AndroidManifest.xml file with the Java class name implementing the Service. For example:
<service android:name="<packagename>.TestJobService" android:permission="android.permission.BIND_JOB_SERVICE" android:exported="true"/ > n AndroidManifest.xml
expects the Java class to be exist at the build time to register the service with the Android system.
n
In Kony Studio, using Mobile First APIs, the class that implements this JobService is created at run time using java.newClass API.
n AndroidManifest.xml
restricts the service to be registered with the native Android system. Thus service will not work.
l
To achieve the requirement, follow these steps: n
You can write the JobService class in Java and bundle it as a jar library with the app.
n
A JobService can be mentioned as an entry into the Manifest file through Kony Studio >
Properties > Native > Android > Tags > Child Tag entries under <application>.
n
To enable the communication between JavaScript and JobService, you can write an FFI component and use Function callbacks.
© 2015 by Kony, Inc. All rights reserved 431 of 848
Kony Studio API Developer's Guide
Version 5.0
24.2.7 Near Field Communication
Near Field Communication (NFC) is a technology that enables communication between smartphones and other devices up to a distance of 4cm. The connection between NFC devices happens within a tenth of a second. NFC consumes less power. NFC-supported devices are indicated with NFC Tags or tickets.
Important: This API is available on Android platform only.
Some uses of this technology are: l
You can make payments with your smartphones without using any credit card or cash.
l
You can buy tickets.
l
You can share files, photos, or videos.
The data is stored in tags in a standard format. You can also store data in different formats. For more information on NFC, click here .
24.2.7.1 APIs
Click here to view Near Field Communication APIs.
24.2.7.2 Sample Application
Click here to download a sample application for Near Field Communication.
24.2.8 Speech
The Speech API on the Android platform helps integrate speech input/output capabilities into your application. When you speak into your device, your words are converted into text. Using this API, you can add voice navigation, fill in a form with voice input, and so on. For more information, click here .
Important: This API is available on Android platform only.
© 2015 by Kony, Inc. All rights reserved 432 of 848
Kony Studio API Developer's Guide
Version 5.0
The Text-to-speech functionality allows you to create applications that can convert text into speech.
The Text-to-speech feature can be tailored to different languages and locales, allowing you to create an experience that is targeted to your application users. Using this API, you can enable your phone to read pages of text out loud. You can also change the pitch and speech rate. For more information, click here .
24.2.8.1 APIs
Click here to view Speech APIs.
24.2.8.2 Sample Application
Click here to download a sample application for Speech.
© 2015 by Kony, Inc. All rights reserved 433 of 848
25. Network APIs
25. Network APIs
The APIs under Network APIs are: l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
Any network call goes through the following phases:
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 434 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
1. Phase 1: preparing network request.
2. Phase 2: making a network connection.
3. Phase 3: handling the returned response.
You can view a video on using Network APIs at: http://docs.kony.com/video_ tutorials/default.htm#Network.htm%3FTocPath%3D_____18 .
Note: All network APIs use the post method to fetch data from a specified URL. The post method is not configurable.
25.1 Asynchronous Network Calls
Asynchronous services can be invoked over existing web protocols (http or https). An asynchronous service does not wait for a response, but continues its work and handles the response later during the execution of the application. When you invoke an asynchronous service call, the user interface (UI) is not blocked, and you can perform other actions such as invoking other services such as updating data on the forms. Use asynchronous service calls if you have long running tasks in the application (like querying a database, making another service call etc).
You need to define a separate callback function to handle return values of an asynchronous service call. An asynchronous call always returns a handle to the service call as an immediate response, and the callback function handles logic to process the return values and error codes (if any).
On the Mobile Web platform, where the virtual machine runs the server, an asynchronous network call is also treated like a synchronous call. When the asynchronous network call API is used, the Mobile
Web platform invokes the network call with the URL and the parameters provided. While the native applications continue processing of the next line of code after the network call (without waiting for the network call to return), the Mobile Web platform waits until the response is fetched from the network call, executes the callback function, and then executes the next line of code after the network call.
In native applications, the print statements appear in the following order:
© 2015 by Kony, Inc. All rights reserved 435 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
1. Hello World - Before invoking network call.
2. Hello World - After invoking network call.
3. Hello World - Inside callback function.
On the Mobile Web platform, the print statements appear in the following order:
1. Hello World - Before invoking a network call.
2. Hello World - Inside a callback function.
3. Hello World - After invoking a network call.
Advantages
With an asynchronous service call, you can: l
Make multiple service calls at the same time based on the application requirement.
l
Perform other actions because code execution and user interface are not blocked.
l
Make your application perform better and be more responsive.
l
Use the resources to the fullest extent (of the system on which the application is running).
Disadvantages
You need to define appropriate actions within the callback functions, and manage the application states and the UI.
Use Cases
You should use asynchronous services in the following scenarios:
1. When the service calls are independent of each other, you can use the asynchronous service calls. For example, you can search for flights, hotels, cars, and more (all these tasks are independent of each other).
© 2015 by Kony, Inc. All rights reserved 436 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
2. When the response of a service call is not consumed immediately in the application flow, but is used later.
25.2 kony.net.invokeServiceAsync
This API allows you to invoke a service asynchronously with the specified parameters.
Note: These APIs are generated by Kony Studio for the code generated using mapping editor.
Even though these APIs have been retained as is they have not been published as standard APIs provided by the Kony runtime libraries. These APIs will not be available to a developer not using
Kony Studio in future for development.
function asyncCallback(status, news)
{
// populate UI
}; var news_inputparam = {}; news_inputparam["serviceID"] = "news"; news_inputparam["httpheaders"] = {}; news_inputparam["httpconfig"] = {timeout:5}; news = appmiddlewareinvokerasync(news_inputparam, asyncCallback);
25.2.1 Signature
JavaScript: kony.net.invokeServiceAsync (
,
25.2.2 Input Parameters url [String] - Mandatory
The URL containing the remote location from where the content is to be retrieved.
© 2015 by Kony, Inc. All rights reserved 437 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
inputParamTable [Object] - Mandatory
The inputParamTable is the list of parameters that need to be passed to the remote service. The inputParamTable contains the following key-value pairs: l appID - Unique ID of the application.
l serviceID - Unique ID of the service.
l channel - Indicates the mobile application channel for which the request is been raised.
Valid values are "rc" for native clients and "wap" for Mobile Web and SPA clients.
Important: l
The above fields appID, serviceID, and channel are mandatory only when middleware is used.
l
If you use a third-party URL for invokeServiceAsync API, the URL should return only JSON value.
l httpheaders [Object] - The httpheaders is an optional key in the parameter table . Use this key when you want to pass custom headers to the remote service.
For example: httpheaders={authkey:"myauthkey", authtoken:"myauthtoken"}
Certain headers like useragent are overridden by the underlying SDK and cannot be set using the httpheaders key.
If the remote service requires basic authentication, you can set the header as follows:
Authorization:"Basic" <base64encoding of the username:password>". For example, httpheaders={Authorization:
"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="}
© 2015 by Kony, Inc. All rights reserved 438 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
Note: l
Make sure there is a space between Basic and the actual base64 encoded string.
l
In SPA and Desktop Web, if you use third-party URLs, then apply xmlHTTPRequest APIs and enable Cross-Origin Resource Sharing (CORS) headers on the target servers (that is, the server to which the service request is made).
If you make a third-party URL call without CORS headers, it results in security exception saying that browser has prevented cross origin request.
The following is an example on how to use this parameter: local myhttpheaders={authkey:
"myauthkey",authtoken:"myauthtoken"} local inputParamTable={appID:"SampleApp", serviceID:"accountLogin",channel:"rc", httpheaders:myhttpheaders}; l httpconfig [Object] - The httpconfig is an optional key in the parameter table . Use this key when to pass custom configurations to set the timeout in seconds for network calls.
For example: httpconfig={timeout:5}
Important: On SPA and Desktop Web, if you are using third-party URLs, use the
HTTP request method.
To configure the HTTP request method, use "method." The possible values are:
© 2015 by Kony, Inc. All rights reserved 439 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
o Get o
Post (default value)
Note: An invalid value to method leads to undefined behavior.
For example: httpconfig = { timeout: 5, method: "get"} callback [Function] - Mandatory
The callback function that is called to handle the return values of the asynchronous network call (in case of success) and error messages (in case of failure). The following is the signature: callback(
,
) l status - an integer value - indicating the status o 100 - network call initiated successfully. The resultset is not available, and it is nil.
o
200 - network is in progress (when you start receiving the first byte). The resultset is not available, and it is nil.
o
300 - network call canceled. The resultset is not available and it is nil.
o
400 - network call is finished (called in success and failure scenarios). Actual state can be queried using opstatus in the resultset.
Note: On Mobile Web, the callback function is always invoked with a status of 400. Other intermediate status codes are not applicable on
Mobile Web.
l resulttable - an object with key-value pairs. Follows the same structure (opstatus, errcode, and errmsg along with the actual network returned data).
© 2015 by Kony, Inc. All rights reserved 440 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
The resulttable represents the object returned by the service. This object contains three values: opstatus errcode errmsg
If the opstatus is 0, the service call is a success while a non-zero value indicates a failure.
If the opstatus is a non-zero value, an errcode is generated. The following are the error codes: l
1000- Unknown error while connecting (if the platform cannot differentiate between network errors, the platform reports error code 1000 by default).
l
1011 - Device has no Wi-Fi or mobile connectivity. Try the operation after establishing connectivity.
l
1012 - Request failed.
l
1013 - Middleware returned invalid JSON string.
l
1014 - Request timed out.
l
1015 - Cannot find host.
l
1016 - Cannot connect to host.
l
1200 - SSL - Certificate related error codes.
The error message corresponding to each error code is captured in the errmsg parameter.
Important: The following information is applicable only for iOS and Android platforms.
© 2015 by Kony, Inc. All rights reserved 441 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
The resulttable also contains the httpresponse key. The httpresponse contains a value as a table containing responsecode, url, headers, and cookies keys.
httpresponse:{"headers":{"xxxx":"Basic realm=\"Authentication required\"","Content-Language":"en","Content-
Type":"text/html;charset=utf-8","Date":"Tue, 29 Jul 2014
10:17:04 GMT","Server":"Apache-Coyote/1.1","Content-
Length":"951"},"responsecode":401,"url":"http://x.x.x.x"}.
info [Object] - Optional
A JavaScript object consisting of key value pairs. If the info parameter is specified, it is passed to the callback function as a last parameter. If the info parameter is not specified, the callback function receives the info as null. The info object represents user data where in the application developers will pass it to the async API's, and the platform returns this info object to the corresponding async callback.This parameter helps developers remember the context when the methods are called in asynchronous fashion.Developers can define any custom keys and values within the info object based on the needs. Custom keys are not predefined keys with values.
25.2.3 Return Values connHandle
The connHandle represents the handle to the underlying URL connection. The connHandle helps cancel the network call using the cancel API.
null
If the input parameters are invalid.
25.2.4 Implementation Details
To ensure security, all JavaScript functions within an application are executed in a single thread. There is no separate thread for the asynchronous service callback functions. The callback function for the service call executes serially in the thread, only after the execution of other JavaScript functions
(queued up earlier).
© 2015 by Kony, Inc. All rights reserved 442 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
Any subsequent user actions are queued if they occur during the execution of the callback function.
Therefore, parallel execution of multiple asynchronous calls (even the operation of waiting for the response) cannot be guaranteed.
25.2.5 API Usage
Based on the application requirement and logic, a developer should decide whether to invoke a service synchronously or asynchronously.
25.2.6 UI Behavior
There is no noticeable difference in the user interface because the user can perform other actions while the asynchronous network call is in progress.
25.2.7 Rules and Restrictions
Do not use other service calls or functions that use/update the same data structure that is applied by the asynchronous network call. If you invoke more than one asynchronous service call that accesses the same data structure, the behavior of the application is unpredictable. You should handle such validations or error handling mechanisms in the callback function that is executed when an asynchronous service call is made.
Note: You must sanitize the data such as user input or http response before setting them as http header values. If the data is not sanitized it can lead to various types of header manipulation attacks such as an
HTTP response splitting attack, cross-site scripting, browser hijacking, cookie manipulation, and crossuser defacement.
25.2.8 Exceptions
1200 - Network Error.
25.2.9 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 443 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.2.10 JavaScript Example function callbackfunction(status, resulttable)
{ if(status == 400)
{ if(resulttable["opstatus"] == 0)
{ alert("opstatus is zero");
}
}
} function startup()
{ try
{ var myhttpheaders={authkey:"myauthkey", authtoken:"myauthtoken"}; var inputParamTable=
{ appID:"SampleApp", serviceID:"accountLogin", channel:"rc", httpheaders:myhttpheaders
}; var connHandle = kony.net.invokeServiceAsync(
"http://www.test.kony.com", inputParamTable, callbackfunction);
}
© 2015 by Kony, Inc. All rights reserved 444 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
} catch(err)
{ alert("Error"+err);
}
25.3 Cancel Asynchronous Network Call
This API cancels only async network calls. Synchronous calls have a platform-specific cancellation mechanism provided by the platform (mechanism may vary from platform to platform).
25.3.1 Signature
JavaScript: kony.net.cancel(
Invalid parameters to this API will be ignored.
25.3.2 Input Parameters connHandle - Mandatory
The handle to the asynchronous service.
connHandle is returned by invokeserviceasync.
25.3.3 Return Values
None.
25.3.4 Exceptions
1200 - Network Error.
© 2015 by Kony, Inc. All rights reserved 445 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.3.5 Platform Availability
Available on all platforms except Server-Side Mobile Web, Windows 8, and Windows Phone 8 channels.
25.3.6 JavaScript Example function cancelService()
{ kony.net.cancel(connHandle);
}
25.4 Checking Network Availability
This API enables you to check whether a network is available for data transport on a device.
25.4.1 Signature
JavaScript : kony.net.isNetworkAvailable (
25.4.2 Input Parameters networkType [Integer Constant] - Mandatory
Specifies the network type on the device for data transport. You can specify any of the following as a value: l constants.NETWORK_TYPE_3G - Indicates if the device has sufficient network coverage to send data using the 3G channel. Available on Android, iOS, BlackBerry, and Windows (other platform will always return false when queried using kony.net.isNetworkAvailable
(constants.NETWORK_TYPE_3G).
© 2015 by Kony, Inc. All rights reserved 446 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
Note: Some platforms such as Android do not differentiate between 3G and 2G connectivity. In this case, even if the device is on a 2G connection, the API would still indicate that the device is on 3G connectivity.
l constants.NETWORK_TYPE_WIFI - Indicates if the device has sufficient network coverage to send data using the Wi-Fi channel. Available on Android, iOS, BlackBerry, and Windows (other platforms will always return false when queried using kony.net.isNetworkAvailable
(constants.NETWORK_TYPE_WIFI).
l constants.NETWORK_TYPE_ANY - Indicates if the device has sufficient network coverage to send data over any supported data channels. Available on Android, iOS, BlackBerry, Windows,
HTML5 SPA, Mobile Web, and Desktop Web.
25.4.3 Return Values true
Indicates that the specified data network is available.
false
Indicates that the specified data network is unavailable.
25.4.4 Platform Availability
Available on all platforms except BlackBerry 10. Also, except BlackBerry 6.0.0.141, all other
BlackBerry 6.0 versions give null pointer exception when an incorrect parameter is provided.
25.4.5 JavaScript Example function checkIfNetworkIsAvailable()
{ return kony.net.isNetworkAvailable(constants.NETWORK_TYPE_ANY);
}
© 2015 by Kony, Inc. All rights reserved 447 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.5 Registering for Network Status Change Notifications
This API allows the developer to register for network status changes. You can then change the user experience according to the network availability.
Important: In BlackBerry,this API works as expected. But, when a user goes from offline to online and selects the mobile network and Wi-Fi network options, the API is executed two times. If the user selects mobile network or Wi-Fi, then the API executes only once.
25.5.1 Signature
JavaScript : kony.net.setNetworkCallbacks(
)
25.5.2 Input Parameters callbackconfig [JSON Object] - Mandatory
A JSON object that comprises a property statusChange.
l statusChange [Function] - Mandatory: Invoked by Kony Platform when the device goes offline or is online. This callback receives an input parameter that indicates if the device was online or offline when this callback was invoked.
var config = {}; config.statusChange = function (isOnLine)
{ if(isOnLine)
{ alert("Device is online");
} else
{ alert("Device is offline");
© 2015 by Kony, Inc. All rights reserved 448 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
}
}
25.5.3 Return Values
None
25.5.4 Platform Availability
Available on all platforms except Windows Phone 8, Windows Phone 8.1, Windows 8, BlackBerry 10, and Mobile Web.
25.5.5 JavaScript Example var config = {}; config.statusChange = function (isOnLine)
{ if(isOnLine)
{ alert("Device is online");
} else
{ alert("Device is offline");
}
} kony.net.setNetworkCallbacks(config);
25.6 Fetching Network Type
This API returns the currently active network type. If the device is offline, it will return null. Otherwise, it will return the appropriate connection type.
© 2015 by Kony, Inc. All rights reserved 449 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
For SPA , Mobile Web, and Desktop Web, it will always return constants.NETWORK_TYPE_ANY.
SPA and Desktop Web depend upon the navigator.onLine property to detect if the device is offline or online. The implementation of this property across browsers is uneven. For more information, refer to
Mozilla documentation for browser support .
25.6.1 Signature
JavaScript : kony.net.getActiveNetworkType()
25.6.2 Input Parameters
None
25.6.3 Return Values
Returns one of the following constants: l constants.NETWORK_TYPE_3G - when 3G network is used.
l constants.NETWORK_TYPE_WIFI - when Wi-Fi is used.
l constants.NETWORK_TYPE_ANY - only when SPA , Mobile Web, and Desktop Web applications are used.
25.6.4 Platform Availability
Available on all platforms except BlackBerry 10.
25.6.5 JavaScript Example function checkActiveNetwork()
{ return kony.net.getActiveNetworkType() ;
}
© 2015 by Kony, Inc. All rights reserved 450 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.7 HttpRequest API
The HttpRequest object supports an HTTP or HTTPS request to any resource on the network and fetches the response.
Note: The HttpRequest API is only supported in JavaScript.
Creating HttpRequest object instance: var httpclient1 = new kony.net.HttpRequest()
25.7.1 Input Parameters
None
25.7.2 Return Values
None
25.7.3 Properties
The following are the properties of the HttpRequest object - for example, httpclient1.timeout.
Name timeout [number]
Readable/Writable
Read / Write
Description
The time in milliseconds a request can take before being terminated. By default, the value is zero, which means there is no timeout set. This timeout represents the connection timeout and the response timeout from the server.
© 2015 by Kony, Inc. All rights reserved 451 of 848
25. Network APIs status [number] Read only statusText [string] Read only responseType [string] Read only
Kony Studio API Developer's Guide
Version 5.0
Returns the HTTP status code. Returns 0 if the status of the request is not sent - that is send() API is still not invoked on this object
(or) in case of an exception.
Returns the HTTP reason phrase of the status line. Returns an empty string, if the status of the request is not sent that is send
() API is still not invoked on this object (or) in case of an exception. The reason-phrase for a given status code based on the http specification (RFC 2616). However, these phrases are only recommendations and may vary with other equivalent phrases by individual platform implementations.
Returns or sets the response type. By default, it is empty string. The possible values are: constants.HTTP_RESPONSE_
TYPE_TEXT constants.HTTP_RESPONSE_TYPE_
JSON constants.HTTP_RESPONSE_TYPE_
DOCUMENT constants.HTTP_RESPONSE_TYPE_
RAWDATA.
Note: The RAWDATA type is not supported by SPA .
© 2015 by Kony, Inc. All rights reserved 452 of 848
25. Network APIs response[string] Read only
Kony Studio API Developer's Guide
Version 5.0
Returns the response body. The type of the value depends on the value of the responseType. In case of an exception, it returns empty string.
If responseType is constants.HTTP_
RESPONSE_TYPE_TEXT, then the response value is a response string.
If responseType is constants.HTTP_
RESPONSE_TYPE_JSON, then the response value is a result of Json.parse() on the response content.
If responseType is constants.HTTP_
RESPONSE_TYPE_DOCUMENT, then the response value is an XML string.
If responseType is constants.HTTP_
RESPONSE_TYPE_RAWDATA, then the response value is a platform-specific handle representing the raw data of binary content of type kony.types.RawBytes.
Note: For JSON type, if JSON parse fails, null is returned. For DOCUMENT type, native platforms do not perform any validations on the response.
© 2015 by Kony, Inc. All rights reserved 453 of 848
25. Network APIs readyState[integer] Read only
Kony Studio API Developer's Guide
Version 5.0
Return the current status of the http request object. The possible values are: l constants.HTTP_READY_STATE_
UNSENT = 0 (The state when the object has been constructed) l constants.HTTP_READY_STATE_
OPENED = 1 (The state when the open method has been successfully invoked) l constants.HTTP_READY_STATE_
HEADERS_RECEIVED = 2 (The state when all redirects have been followed and all HTTP headers of the final response have been received) l constants.HTTP_READY_STATE_
LOADING = 3 (The state when the response data is been received) l constants.HTTP_READY_STATE_
DONE = 4 (The state when the data transfer has been completed or something went wrong during transfer)
© 2015 by Kony, Inc. All rights reserved 454 of 848
25. Network APIs onReadyStateChange
[function]
Write only
Kony Studio API Developer's Guide
Version 5.0
The property to register an event callback that is invoked when there is a change in the state of the "readyState" property. Refer readyState description for different states.
Note: In BlackBerry10 platform, the application crashes when an event is invoked dynamically by assigning a
JSObject.
var request = new kony.new.HttpRequest(); request.onReadyStateChange = callbackfunction; //This will not work.
//Alternatively, you can use the below code to set the callback.
var request = new kony.new.HttpRequest(); request.setOnReadyStateChang
e (callbackfunction); //This will work.
//Where callbackfunction is the name of the callback.
25.7.4 Platform Availability
The HttpRequest API is supported in all platforms except Mobile Web and SPA.
© 2015 by Kony, Inc. All rights reserved 455 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.8 open
This method initializes the http request object with a request method type (GET or POST) and the url.
If this method is invoked after send(), it should terminate the current send() request.
25.8.1 Signature
JavaScript : <<HttpRequestobject>>.open(
,
url , async , username , password )
25.8.2 Input Parameters requestMethod [string]- Mandatory
For the http request method, the possible values are: l constants.HTTP_METHOD_GET
l constants.HTTP_METHOD_POST
l case-insensitive match to GET or POST string.
url [string] - Mandatory
The request URL string with character encoded UTF-8.
async [Boolean] - Optional
Sets request type as asynchronous or synchronous. Default value true that is asynchronous.
Note: This parameter is ignored for SPA and only supports asynchronous.
username [string] - Optional
Configure the user credentials for basic authentication.
password [string] - Optional
Configure the user credentials for basic authentication.
© 2015 by Kony, Inc. All rights reserved 456 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.8.3 Return Values
None.
25.8.4 Exceptions
SyntaxError - if the requestMethod is not valid or url cannot be resolved.
25.8.5 Platform Availability
Available on all platforms except Windows and SPA.
25.8.6 JavaScript Example var request = new kony.net.HttpRequest(); request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO");
25.9 setRequestHeader
This appends a header to the list of http request headers.
Note: You must sanitize the data such as user input or http response before setting them as http header values. If the data is not sanitized it can lead to various types of header manipulation attacks such as an
HTTP response splitting attack, cross-site scripting, browser hijacking, cookie manipulation, and crossuser defacement.
25.9.1 Signature
JavaScript :<<HttpRequestObject>>.setRequestHeader(
,
© 2015 by Kony, Inc. All rights reserved 457 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.9.2 Input Parameters header [string]- Mandatory
The header name.
value [string] - Mandatory
The value of the header.
25.9.3 Return Values
None.
25.9.4 Exceptions
InvalidStateError - if this method is called before the open() API call and or after the send() API call.
Note: If this method is called twice on a header, then the values are appended by comma with a space delimiter.
25.9.5 Platform Availability
Available on all platforms except Windows and SPA.
25.9.6 JavaScript Example var request = new kony.net.HttpRequest();
...
request.setRequestHeader("From","[email protected]");
25.10 send
This methods initiates a request.
© 2015 by Kony, Inc. All rights reserved 458 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.10.1 Signature
JavaScript :<<HttpRequestObject>>.send(
25.10.2 Input Parameters data [kony.net.FormData] - Optional
An optional argument specifying the input parameter data along with a request. This parameter is ignored if the request type is GET or HEAD.
Note: send() handles the redirection headers automatically, that is http status codes 301,
302, 303, or 307.
25.10.3 Return Values
None.
25.10.4 Exceptions
InvalidStateError - if this method is called before an open() API call and or after the send() API is called more than once.
Network or DNA errors generate an http status code such as 410 and raise the HEADERS_
RECEIVED state change event.
25.10.5 Platform Availability
Available on all platforms except Windows and SPA.
25.10.6 JavaScript Example var request = new kony.net.HttpRequest();
...
© 2015 by Kony, Inc. All rights reserved 459 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
request.send();
25.11 abort
This cancels the network operation . If the abort is successful in canceling the send request, the readyState is set to UNSENT. Otherwise, the readyState is set to Done.
25.11.1 Signature
JavaScript : <<HttpRequestObject>>.abort()
25.11.2 Input Parameters
None.
25.11.3 Return Values
None.
25.11.4 Platform Availability
Available on all platforms except Windows and SPA.
25.11.5 JavaScript Example var request = new kony.net.HttpRequest();
...
request.abort();
© 2015 by Kony, Inc. All rights reserved 460 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.12 getResponseHeader
This API returns the header field value using the response for a given header, unless the header field name is Set-Cookie or Set-Cookie2.
25.12.1 Signature
JavaScript :<<HttpRequestObject>>.getResponseHeader(
)
25.12.2 Input Parameters headerfield [string] - Mandatory
The name of the header field.
25.12.3 Return Values string - header field value.
If the readyState is UNSENT, OPENED, or any of a failure case, null is returned.
25.12.4 Platform Availability
Available on all platforms except Windows and SPA.
25.12.5 JavaScript Example var request = new kony.net.HttpRequest() request.getResponseHeader("Date");
25.13 getAllResponseHeaders
This API returns all headers using the response for a given header, except the fields with names Set-
Cookie or Set-Cookie2.
© 2015 by Kony, Inc. All rights reserved 461 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.13.1 Signature
JavaScript : <<HttpRequestObject>>.getAllResponseHeaders()
25.13.2 Input Parameters
None.
25.13.3 Return Values
Object
The header field name and the value map object.
If the readyState is UNSENT, OPENED, or any of the failure case, null is returned.
25.13.4 Platform Availability
Available on all platforms except Windows and SPA.
25.13.5 JavaScript Example var request = new kony.net.HttpRequest() print(request.getAllResponseHeaders());
25.14 Constants
The constants used by HttpRequest APIs are: l constants.HTTP_RESPONSE_TYPE_TEXT
l constants.HTTP_RESPONSE_TYPE_JSON
l constants.HTTP_RESPONSE_TYPE_DOCUMENT
l constants.HTTP_RESPONSE_TYPE_RAWDATA
© 2015 by Kony, Inc. All rights reserved 462 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
l constants.HTTP_READY_STATE_UNSENT = 0 l constants.HTTP_READY_STATE_OPENED = 1 l constants.HTTP_READY_STATE_HEADERS_RECEIVED = 2 l constants.HTTP_READY_STATE_LOADING = 3 l constants.HTTP_READY_STATE_DONE = 4 l constants.HTTP_METHOD_GET
l constants.HTTP_METHOD_POST
The delete quotes values are mapped to the corresponding http contentType as below:
HTTP ContentType application/text, text/plain
ResponseType constants.HTTP_RESPONSE_TYPE_
TEXT constants.HTTP_RESPONSE_TYPE_
JSON constants.HTTP_RESPONSE_TYPE_
DOCUMENT constants.HTTP_RESPONSE_TYPE_
RAWDATA application/json application/xml, text/xml, text/html, mime type that ends with +xml
Type except the above values
25.15 FormData APIs
The FormData object represents an ordered collection of entries with name-value pairs.
To create a FormData object, follow this: var httpinputparams1 = new kony.net.FormData()
© 2015 by Kony, Inc. All rights reserved 463 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.16 append
This API appends the specified entry to the collection of the FormData object.
25.16.1 Signature
JavaScript :<<formobject>>.append(
)
25.16.2 Input Parameters name [string] - Mandatory
The name of the entry to be added to the collection.
value [string] - Mandatory
The value of the entry to be added to the collection.
25.16.3 Return Values
None
25.16.4 Platform Availability
Available on all platforms except Windows and SPA.
25.16.5 JavaScript Example function sendbeforeopen()
{ try{ var request = new kony.net.HttpRequest(); glob_req = request;
.....
var frmData= new kony.net.FormData();
© 2015 by Kony, Inc. All rights reserved 464 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
frmData.append("param1","KONY LABS");
}catch(ex){ frmSend.responseTA.text=ex.message;
}
}
25.16.6 Consolidated Working Example var glob_req; function notimeoutset()
{ var request = new kony.net.HttpRequest(); glob_req=request; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.send();
} function timeoutsettozero()
{ try{ var request = new kony.net.HttpRequest(); glob_req=request; request.timeout=0; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.send();
}catch(ex){ frmtimeout.resultTA.text=ex.message();
}
} function timeoutset()
{
© 2015 by Kony, Inc. All rights reserved 465 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
try{ var request = new kony.net.HttpRequest(); glob_req=request; request.timeout=5000;
//request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.open(constants.HTTP_METHOD_GET,
"www.planetsoft.com"); request.send();
}catch(ex){ frmtimeout.resultTA.text=ex.message();
}
} function syncnotimeoutset()
{ var request = new kony.net.HttpRequest(); glob_req=request; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO",false); request.send();
} function synctimeoutsettozero()
{ try{ var request = new kony.net.HttpRequest(); glob_req=request; request.timeout=0; request.open(constants.HTTP_METHOD_GET,
© 2015 by Kony, Inc. All rights reserved 466 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO",false); request.send();
}catch(ex){ frmtimeout.resultTA.text=ex.message();
}
} function synctimeoutset()
{ try{ var request = new kony.net.HttpRequest(); glob_req=request; request.timeout=5000;
//request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO",false); request.open(constants.HTTP_METHOD_GET,
"www.planetsoft.com",false); request.send();
}catch(ex){ frmtimeout.resultTA.text=ex.message();
}
} function synctimeoutsethigh()
{ try{ var request = new kony.net.HttpRequest(); glob_req=request; request.timeout=5000;
© 2015 by Kony, Inc. All rights reserved 467 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO",false); request.send();
}catch(ex){ frmtimeout.resultTA.text=ex.message();
}
} function timeoutsethigh()
{ try{ var request = new kony.net.HttpRequest(); glob_req=request; request.timeout=null; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.send();
}catch(ex){ frmtimeout.resultTA.text=ex.message();
}
} function timeoutStatusClick(){ frmtimeout.statusCd.text=glob_req.status; frmtimeout.StatusTxt.text=glob_req.statusText; frmtimeout.responseType.text=glob_req.responseType; frmtimeout.resultTA.text=glob_req.response; frmtimeout.readyState.text=glob_req.readyState;
} function statusText()
{
© 2015 by Kony, Inc. All rights reserved 468 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
var request = new kony.net.HttpRequest(); glob_req = request; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); frmStatus.statusLabel.text=request.status; frmStatus.statusTextLabel.text=request.statusText; request.send();
} function errorStatusText()
{ var request = new kony.net.HttpRequest(); glob_req = request; request.onReadyStateChange=statusreceived; request.open(constants.HTTP_METHOD_GET,
"http://10.10.5.19:9090/middleware/version1.html"); frmStatus.statusLabel.text=request.status; frmStatus.statusTextLabel.text=request.statusText; request.send();
} function statBtnClick(){ frmStatus.statusAfterSend.text=glob_req.status; frmStatus.statusTextAfterSend.text=glob_req.statusText; frmStatus.readyState.text=glob_req.readyState;
} function statusreceived(){ if(this.readyState == constants.HTTP_READY_STATE_HEADERS_
RECEIVED){
© 2015 by Kony, Inc. All rights reserved 469 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
} frmStatus.statusLabel.text=this.status;
} function jsonResponseType()
{ var request = new kony.net.HttpRequest(); request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.send(); frmResponseType.respTypeLabel.text=request.responseType;
} function xmlResponseType()
{ var request = new kony.net.HttpRequest(); request.open(constants.HTTP_METHOD_GET,
"http://feeds.foxnews.com/foxnews/health"); request.send(); frmResponseType.respTypeLabel.text=request.responseType;
} function rawDataResponseType()
{ var request = new kony.net.HttpRequest(); request.open(constants.HTTP_METHOD_GET,
"http://ilabs.uw.edu/sites/default/files/sample_0.pdf"); request.send(); frmResponseType.respTypeLabel.text=request.responseType;
} function textDataResponseType()
{ var request = new kony.net.HttpRequest(); request.open(constants.HTTP_METHOD_GET,
© 2015 by Kony, Inc. All rights reserved 470 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
"http://10.10.5.19:9090/middleware/version.html"); request.send(); frmResponseType.respTypeLabel.text=request.responseType;
} function readyState1()
{ var request = new kony.net.HttpRequest(); request.onReadyStateChange=callbackHandler1; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.send();
} function readyStateSync()
{ var request = new kony.net.HttpRequest(); request.onReadyStateChange=callbackHandler1; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO",false); request.send();
} function callbackHandler1(){ frmReadyState.readyStateLabel.text=frmReadyState.readyStateLabel.tex
t+","+request.readyState; if(request.readyState == constants.HTTP_READY_STATE_HEADERS_
RECEIVED){ frmReadyState.responseHeadersTA.text=request.getAllResponseHeaders
();
© 2015 by Kony, Inc. All rights reserved 471 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
frmReadyState.headerValue.text=request.getResponseHeader
("Date");
}else if(request.readyState == constants.HTTP_READY_STATE_
DONE){ frmReadyState.responseTA.text=request.response;
}
} function onreadyStateChng()
{ var request = new kony.net.HttpRequest(); request.onReadyStateChange=onreadStateHandler1; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.send();
} function onreadStateHandler1(){ frmReadyState.readyStateLabel.text=frmReadyState.readyStateLabel.tex
t+","+request.readyState; if(request.readyState == constants.HTTP_READY_STATE_HEADERS_
RECEIVED){ frmReadyState.responseHeadersTA.text=request.getAllResponseHeaders; request.onReadyStateChange=onreadStateHandler2;
}else if(request.readyState == constants.HTTP_READY_STATE_
DONE){ frmReadyState.responseTA.text=request.response;
}
}
© 2015 by Kony, Inc. All rights reserved 472 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
function onreadStateHandler2(){ frmReadyState.ovrdlabel.text = "FROM OVERRIDE CALL BACK
METHOD"; frmReadyState.readyStateLabel.text=frmReadyState.readyStateLabel.tex
t+","+request.readyState; if(request.readyState == constants.HTTP_READY_STATE_HEADERS_
RECEIVED){ frmReadyState.responseHeadersTA.text=request.getAllResponseHeaders; request.onReadyStateChange=onreadStateHandler2;
}else if(request.readyState == constants.HTTP_READY_STATE_
DONE){ frmReadyState.responseTA.text=request.response;
}
} function setReqHeader()
{ var request = new kony.net.HttpRequest(); request.open(constants.HTTP_METHOD_GET,
"http://ilabs.uw.edu/sites/default/files/sample_0.pdf"); request.send(); request.setRequestHeader("From","[email protected]");
} function getResponseHeaderValid()
{ var request = new kony.net.HttpRequest(); request.onReadyStateChange=getHeaderValue;
© 2015 by Kony, Inc. All rights reserved 473 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.send();
} function InValidgetResponseHeader()
{ var request = new kony.net.HttpRequest(); request.onReadyStateChange=getHeaderValue; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.send();
} function getResponseHeaderBfrSend()
{ var request = new kony.net.HttpRequest();
//request.onReadyStateChange=getHeaderValue; request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); frmResponseHeaders.headerValue.text=request.getResponseHeader
("Date"); request.send();
} function getSetCookie()
{ var request = new kony.net.HttpRequest(); request.open(constants.HTTP_METHOD_GET,
"http://ws.geonames.org/weatherIcaoJSON?ICAO=KMCO"); request.send(); frmResponseHeaders.headerValue.text=request.getResponseHeader
("Set-Cookie");
© 2015 by Kony, Inc. All rights reserved 474 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
} function getheaderclick()
{ frmResponseHeaders.headerValue.text=request.getResponseHeader
("Set-Cookie");
} function getHeaderValue()
{ if(this.readyState == constants.HTTP_READY_STATE_HEADERS_
RECEIVED){ frmResponseHeaders.headerValue.text=this.getResponseHeader("Date"); frmResponseHeaders.InvalidHeaderlb.text=this.getResponseHeader
("Date11");
}
} function redirectService()
{ var request = new kony.net.HttpRequest(); glob_req=request; request.open(constants.HTTP_METHOD_GET,
"http://10.10.5.19:9090/HttpRequestStub/ServiceStub?testCase_
id=redirect_tc"); request.send();
} function redirectResultClick(){
© 2015 by Kony, Inc. All rights reserved 475 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
req.responseType; frmRedirects.redirectresultTA.text=glob_req.response;
} frmRedirects.redirectStatus.text=glob_req.status; frmRedirects.redirectResponseType.text=glob_
25.17 kony.net.getCookies
In an application where service calls are made through Browser Widget or through native service calls, cookies are sent from the servers to maintain the session. These cookies are stored in cookie store on the client side. The kony.net.getCookies API enables access to the cookies for a particular domain.
The URL is given as an input parameter to kony.net.getCookies API, then all cookies related to that domain are returned.
In the current application context, you can also access cookies for a particular domain stored in cookie store on the client side or device.
Kony.net.getCookies() API returns all the cookies stored in local cookie store on the client side or device for that particular domain. The returned cookies can vary based on the domain (partial or full domain) and as well as the path.
25.17.1 Signature kony.net.getCookies(URL)
25.17.2 Input Parameters
The URL is passed as input and must be a fully formed, valid URL like
http://www.google.com
.
If the URL is invalid or not formed properly,
Null
is returned.
© 2015 by Kony, Inc. All rights reserved 476 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.17.3 Return Values
The return values are an array of cookie. Each cookie follows the format
key=value
string.
Each cookie string can also contain additional information following the Standard HTTP Cookie
Format, such as Domain, Path, Expires, Secure, and HttpOnly.
Null
is returned if no cookies are present for the domain.
If the scheme of the URL is
https
, then all the cookies of
https
as well as
http
are returned.
If the scheme of the URL is
http
, then only the cookies stored for
http
are returned.
For example:
SSID=Ap4P….GTEq; Domain=foo.com; Path=/; Expires=Wed, 13 Jan 2021
22:23:01 GMT; Secure; HttpOnly
25.17.4 Platform Availability
Android, iOS, Windows, and SPA
25.17.5 JavaScript Example var cookies = kony.net.getCookies("http://www.google.com"); for (index = 0; index < cookies.length; index++) { cookie = cookies[index]; kony.print("Cookie is: " + cookie);
}
25.17.6 Limitations l
In Windows, the cookies stored in the Browser Widget cookie store are returned. Cookies stored through native service calls are not returned.
© 2015 by Kony, Inc. All rights reserved 477 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
l
In SPA, the cookies related to a currently loaded domain in a web page are accessible.
l
In SPA, cookies with the
httpOnly
flag cannot be accessed.
25.18 kony.net.clearCookies
In an application where service calls are made through Browser Widget or through native service calls, cookies are sent from the servers to maintain the session. These cookies are stored in the cookie store on the client side. Using this API you can remove the cookies of a particular domain obtained through all of HttpRequest, invokeServiceAsync and browser widget.
If you specify the optional parameters url and cookieName, then all the cookies with the specified name related to that URL are removed from your application. The parameter url should be the complete URL. For example, http://www.gooogle.com
. If the URL is not valid, then this API will not remove the cookies. An exception is shown of type KonyError with the error code as 1005 and error name/message as "invalid input url".
If the scheme of the URL is "https" then all the cookies of https as well as http will be removed. If the scheme of the URL is "http" then only the cookies stored for http will be removed. If the cookies are not present in the application cookie store in the provided array of cookieNames, then this API will not perform any action and does not raise an exception.
25.18.1 Signature kony.net.clearCookies(url, cookieName [] )
25.18.1.1 Input Parameters url [String] - Optional
A valid URL of a domain from where the cookies were obtained.
cookieName [Array] - Optional
Specifies the cookie names that are to be removed from the current application.
© 2015 by Kony, Inc. All rights reserved 478 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.18.2 Return Values
None
25.18.3 Platform Availability
Available on iOS, Android, Windows, and SPA platforms.
25.18.4 JavaScript Example kony.net.clearCookies("http://www.google.com");
25.18.5 Limitations on SPA Platform l
You can remove the cookies related to a currently loaded domain in a web page.
l
Cookies with the
httpOnly
flag cannot be removed. The secured cookies (https) cannot be removed when application is accessed with non-secured protocol.
25.19 Deprecated APIs
This section lists all the deprecated APIs.
25.19.1 kony.net.invokeservice
This API allows you to invoke a service synchronously with the specified parameters.
25.19.1.1 Signature
JavaScript: kony.net.invokeService(url,inputParamTable,isblocking)
25.19.1.2 Input Parameters url [String] - Mandatory
The URL containing the remote location from where the content is to be retrieved.
© 2015 by Kony, Inc. All rights reserved 479 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
inputParamTable [None.]
It is the list of parameters that need to be passed to the remote service. The parametermap is a table that has the following key-value pairs: l appID - Unique ID of the application l serviceID - Unique ID of the service l httpheaders [None.] - The httpheaders is an Optional key in the parameter table . You can use this key when you want to pass custom headers to the remote service.
For example, httpheaders={authkey:"myauthkey", authtoken="myauthtoken"}
Certain headers like User-Agent will be overridden by the underlying SDK and hence cannot be set using this key.
If the remote service requires basic authentication, you can set the header as follows:
Authorization="Basic <base64encoding of the username:password>". For example, httpheaders={Authorization=
"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="}
Note: Make sure there is a space between
Basic
and the actual base64 encoded string.
The following is an example on how to use this parameter: local myhttpheaders={authkey=
"myauthkey",authtoken="myauthtoken"} local inputParamTable={appID="SampleApp", serviceID="accountLogin", httpheaders=myhttpheaders};
© 2015 by Kony, Inc. All rights reserved 480 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
isblocking [Boolean] - Mandatory
Indicates if further actions on the user-interface needs to be blocked or not. If set to true, further clicks or actions on the form are blocked. If set to false, the user can to scroll through the userinterface but cannot perform any actions.
25.19.1.3 Return Values resulttable
This table contains three values: l opstatus l errcode l errmsg.
If the opstatus is 0, it indicates that the service call is a success while a non-zero value indicates a failure.
If the opstatus is a non-zero value, it is captured in errcode . The following are the possible error codes: l
1000 - Unknown Error while connecting (If the platform cannot differentiate between the various kinds of network errors, the platform reports this error code by default) l
1011 - Device has no WIFI or mobile connectivity. Please try the operation after establishing connectivity.
l
1012 - Request Failed l
1013 - Middleware returned invalid JSON string l
1014 - Request Timed out l
1015 - Cannot find host l
1016 - Cannot connect to host l
1022 - Service call is canceled. You can customize the behavior of the application if a service call is canceled.
© 2015 by Kony, Inc. All rights reserved 481 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
Note: When you explicitly call form.show, then the iOS device will cancel the service call.
l
1200 - SSL - Certificate related error codes.
The error message corresponding to each error code is captured in the errmsg parameter.
25.19.1.4 API Usage
Based on the application requirement and logic, the developer should decide whether to invoke a service synchronously or asynchronously. For a synchronous service call, you should use the net.invokeservice API. For an asynchronous service call, you should use the net.invokeserviceasync
API.
25.19.1.5 UI Behavior
When the synchronous service call is in progress, you can scroll through the user-interface but cannot perform any actions until the application receives the response for the synchronous service from the server. A progress indicator (something similar to ) appears on the screen indicating to the user that a service call is in progress.
Note: Currently, iPhone and BlackBerry platforms allow you to cancel a synchronous service call while it is in progress. When a service call is canceled, 1022 error code is thrown and you have to handle the logic that needs to be executed for that specific error code.
On iPhone, if the isblocking parameter is set to true, a message similar to the following message appears at the bottom of the screen allowing you to cancel the service call.
If the isblocking parameter is set to false, this message does not appear.
Note: On iPhone platform, the default value of isblocking parameter is true.
© 2015 by Kony, Inc. All rights reserved 482 of 848
25. Network APIs Kony Studio API Developer's Guide
Version 5.0
25.19.1.6 Rules and Restrictions
Use synchronous service calls only when you need the service output to be consumed immediately for other actions in the application. In other words, use synchronous service calls when you want the code in the application to be executed sequentially.
25.19.2 Platform Availability
Available on all platforms except BlackBerry 10.
local myhttpheaders={authkey="myauthkey",authtoken="myauthtoken"} local params=
{appID="12345",serviceID="test1",httpheaders=myhttpheaders}; local myresulttable=net.invokeservice("http://test.konylabs.net", params,true); if (myresulttable.opstatus == 0) then
// display some other form else// display error end;
© 2015 by Kony, Inc. All rights reserved 483 of 848
26. Notifications Kony Studio API Developer's Guide
Version 5.0
26. Notifications
The notification system allows users to keep informed about relevant and timely events in your app, such as new chat messages from a friend or a calendar event. For example, if you have installed news app in your devices, you will receive timely news updates for that app.
Notifications are of two types. They are local notifications and remote notifications. Remote notifications are also known as push notifications.
l
l
l
26.1 Local Notifications
Local notifications are scheduled by an app and delivered on the same device. They are suited for apps with time-based behaviors, such as calendar events.
Note: Each app on a device is limited to 64 scheduled local notifications. The system discards scheduled notifications exceeding this limit. Recurring notifications are treated as a single notification.
© 2015 by Kony, Inc. All rights reserved 484 of 848
26. Notifications Kony Studio API Developer's Guide
Version 5.0
The local notification APIs are: l
kony.localnotifications.setCallbacks
l
kony.localnotifications.create
l
kony.localnotifications.cancel
© 2015 by Kony, Inc. All rights reserved 485 of 848
26. Notifications Kony Studio API Developer's Guide
Version 5.0
26.1.1 kony.localnotifications.setCallbacks
This API helps you associate online and offline callbacks for local notifications. These callbacks are invoked when local notifications are raised by the underlying system. The online notification callback is involved when the application is running. The offline callbacks are invoked when the application is not running. This API should be called on post app init on the application.
26.1.1.1 Signature
JavaScript:
kony.localnotifications.setCallbacks ( onlinenotification
,
)
26.1.1.2 Input Parameters onlinenotification [Function] - Mandatory
Specifies the callback to be associated with online notification. The arguments are: l actionId [String] - Mandatory: A unique ID to identify the action.
l notificationobject [JSObject] - Mandatory: Specifies the platform-specific notification object.
offlineNotification [Function] - Mandatory
Specifies the callback to be associated with offline notification. The arguments are: l actionId [String] - Mandatory: A unique ID to identify the action.
l notificationobject [JSObject] - Mandatory: Specifies the platform-specific notification object.
26.1.1.3 Return Values
None
26.1.1.4 Platform Availability
Available on iOS and Android platforms.
© 2015 by Kony, Inc. All rights reserved 486 of 848
26. Notifications Kony Studio API Developer's Guide
Version 5.0
26.1.1.5 JavaScript Example
//Register localnotifications setCallbacks in post app init function online_callback(notificationobject, actionid){
//your logic
} function offline_callback(notificationobject, actionid){
//your logic
}
Kony.localnotifications.setCallbacks({onlinenotification:online_ callback, offlinenotification: offline_callback});
26.1.2 kony.localnotifications.create
This API helps you create local notification.
26.1.2.1 Signature
JavaScript : kony.localnotifications.create (notificationId, datetime, message, title, categoryId, pspConfig)
26.1.2.2 Input Parameters notificationId [String] - Mandatory
Specifies a unique ID for the notification.
datetime [String] - Mandatory
Specifies the date and time when the notification must be triggered. It accepts unicode date, time, and Timezone pattern.
© 2015 by Kony, Inc. All rights reserved 487 of 848
26. Notifications Kony Studio API Developer's Guide
Version 5.0
message [String] - Mandatory
Specifies the message for the notification.
title [String] - Mandatory
Specifies the title for the notification.
categoryId [String] - Mandatory
Specifies the categoryId to associate this local notification or null in case no actions to be displayed.
pspConfig [JSObject] - Optional
Specifies the platform specific options. This is applicable to iOS platform only. Following are the parameters: l badge [Number] - Optional: It displays the number on the app icon.
l sound [String] - Optional: To play a sound, assign a sound file from the app's main bundle. If the sound file is not available or the provided file name is incorrect, it will play a default sound from the system (kony.localnotifications.DEFAULT_
SOUND). To know the supported file formats, click here .
26.1.2.3 Return Values
None
26.1.2.4 Platform Availability
Available on iOS and Android platforms.
26.1.2.5 JavaScript Example
//Sample code to create notification.
var notificationId = "01"; var date = "27 Mar 2015 15:00:00 +0530";
© 2015 by Kony, Inc. All rights reserved 488 of 848
26. Notifications Kony Studio API Developer's Guide
Version 5.0
var format = "dd MMM yyyy HH:mm:ss Z"; var message = "Local notification Received"; var title = "Title"; var categoryId ="calendar"; kony.localnotifications.create({
"id": notificationId,
"dateTime": {
"date": date,
"format": format
},
"message": message,
"title": title,
"categoryId": categoryId,
"pspConfig":{
"badge":1,
"sound": kony.localnotifications.DEFAULT_SOUND or
"sound.wav"
}
});
26.1.3 kony.localnotifications.cancel
This API helps you cancel the notification.
26.1.3.1 Signature
JavaScript: kony.localnotifications.cancel (["notificationId"])
26.1.3.2 Input Parameters notificationId [array] - Mandatory
Specifies an array of notificationids to cancel the notifications.
© 2015 by Kony, Inc. All rights reserved 489 of 848
26. Notifications Kony Studio API Developer's Guide
Version 5.0
26.1.3.3 Return Values
None
26.1.3.4 Platform Availability
Available on iOS and Android platforms.
26.1.3.5 JavaScript Example
//Cancelling the notification notificationIdArray = []; notificationIdArray.push("01"); kony.localnotifications.cancel(notificationIdArray);
26.1.4 Modifying localnotificationconfig.xml File in Android Platform
The default behavior of the local notification message can be customized by modifying the localnotificationconfig.xml
file. The localnotificationconfig.xml file contains key value pairs that allow applications to configure individual keys to override the default behavior.
You can customize the notification using the keys provided in localnotificationconfig.xml.
The table below shows a list of key value pairs, each with a brief description.
Notification ID notify_local_msg
Default
Value true
Description
Enable or disable new local message notifications. If false, no status bar notification is shown when application is running in background.
© 2015 by Kony, Inc. All rights reserved 490 of 848
26. Notifications Kony Studio API Developer's Guide
Version 5.0
Notification ID notify_local_msg_notifications_count
Default
Value
1
Description
By default, only the latest local message notification is kept in the status bar. Use this option to control the number of messages to be stored. The maximum limit allowed in Android is 50.
Note: After exceeding the storage limit, older messages are replaced with newer messages. However, sometimes older notifications are replaced with newer messages even before the storage reaches the specified count (this happens when the app is closed by the Android system).
notify_local_msg_icon notify_local_msg_sound notify_local_msg_vibrate notify_local_msg_lights notify_local_msg_clear icon true true true true
Specify icon resource without extension. For example, set a logo to use an image for the message icon for which the file name is logo.png. The default is icon.png.
Enable or disable sound for local message notification.
Enable or disable vibrate for local message notification.
Enable or disable lights for local message notification.
Indicates if a user can clear the unread local message notification.
© 2015 by Kony, Inc. All rights reserved 491 of 848
Kony Studio API Developer's Guide
Version 5.0
26.2 Push Notification APIs
Push Notifications is a mechanism using which you can initiate a message delivery to a device without receiving a request. Remote notifications, also known as push notifications, are sent by Kony Message
Service (KMS) to the Apple Push Notification Service (apns), which pushes the notification to devices.
Note: Remote Notifications will not work in the simulator.
The Notification Payload For Remote Notification
Each remote notification includes a payload In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes. Apple Push Notification service refuses any notification that exceeds this limit. (Prior to iOS 8, the maximum payload size is 256 bytes.)
Note: Delivery of notifications is a “best effort”, not guaranteed. It is not intended to deliver data to your app.
26.2.1 How it Works
The following are the primary processes involved in an application being setup for Push Notifications:
1.
: When an application needs to use the Push Notifications service, it uses the
API and specifies the functions to be executed for Push
Notifications.
The application then uses the
API to register the application and the device with the corresponding Push Notification Service provider of the device os.
2.
Sending Push Notifications : If the registration is successful, the application can receive Push
Notifications on the device from the third-party application server.
3.
: The third-party application server sends a Push Notification to the application and the device extracts the data from the message and passes it to the application.
© 2015 by Kony, Inc. All rights reserved 492 of 848
Kony Studio API Developer's Guide
Version 5.0
4.
: The application can deregister from Push Notification service by using the
API.
26.2.1.1 Platforms Supporting Push Notifications
Push Notifications are currently supported only by Android, BlackBerry, iPhone and Windows Phone platforms.
For Push Notifications to work, the application and the device must first register with the corresponding Push Notification Service provider of the device os.
The following is the list of platforms and their corresponding Push Notifications Service providers they must register with:
Platform
Android/Android Tablet
BlackBerry iPhone
Windows Phone
Push Notifications Service
Google Cloud Messaging (GCM)
Deprecated:Android Cloud to Device Messaging (C2DM)
BlackBerry Infrastructure
Apple Push Notification Service (APNS)
Microsoft Push Notification Service (MPNS)
26.2.1.2 Enabling Push Notifications
To enable Push Notifications for an application do the following:
1. The application uses the
API and specifies the functions to be executed for Push Notifications.
2. The application uses the
API to register for Push Notifications with the corresponding Push Notification Service provider of the device OS.
© 2015 by Kony, Inc. All rights reserved 493 of 848
Kony Studio API Developer's Guide
Version 5.0
3. If the registration is successful, the Push Notification Service provider returns a unique identifier to the device.
The following is the list of Push Notification Service providers and the unique identifier they return:
Push Notifications Service
Google Cloud Messaging(GCM)
Deprecated: Android Cloud to Device
Messaging (C2DM)
BlackBerry Infrastructure
Returned Unique Identifier
Registration ID
Apple Push Notification Service (APNS)
Microsoft Push Notification Service
(MPNS)
Device ID (can be obtained by using the os.platform.deviceid API)
DeviceToken
Unique URL
4. The application sends the identifier to the third-party application server. The third-party application server can use this identifier to send Push Notifications to it.
© 2015 by Kony, Inc. All rights reserved 494 of 848
Kony Studio API Developer's Guide
Version 5.0
The following image illustrates the steps involved in enabling Push Notifications for an application on a device:
26.2.1.3 Sending Push Notifications
The following are the steps involved in a third-party application server sending Push Notifications to an application on a device:
1. The third-party application server uses the unique identifier (sent by the application ) in sending the Push Notifications to the Push Notification Service provider of the device.
2. The Push Notification Service provider then sends the Push Notification message to the application on the device.
© 2015 by Kony, Inc. All rights reserved 495 of 848
Kony Studio API Developer's Guide
Version 5.0
The following image illustrates the steps involved in sending Push Notifications to an application on a device:
26.2.1.4 Receiving a Message
When an application on a device receives a message, the following sequence of events occur:
1. The device receives the incoming Push Notification and extracts the data from the message payload.
2. The device passes the data to the application.
3. The application processes the data and displays it to the user.
26.2.1.5 Disabling Push Notifications
You can use the
API and deregister the application and the device from the
Push Notifications service.
© 2015 by Kony, Inc. All rights reserved 496 of 848
Kony Studio API Developer's Guide
Version 5.0
26.2.2 APIs for Push Notifications
Kony Platform provides APIs that you can use to enable Push Notifications for an application on a device and also an API to deregister from the Push Notifications service.
The following are the APIs for Push Notifications:
1.
2.
3.
Note: The following are the generic error codes for Push Notification APIs:
Error
Code
1400 Invalid number of arguments.
1401
1402
1406
Error Message
Illegal arguments.
Unable to connect to push service - PNS service is not available
Platform-specific issue. Full details are available in the errormessage. For example, received payload but payload is in incorrect format.
Important: Use Error Codes to refer and do not rely on Error Messages as each message may differ from platform to platform.
BlackBerry additionally supports the following APIs: l
l
© 2015 by Kony, Inc. All rights reserved 497 of 848
Kony Studio API Developer's Guide
Version 5.0
26.2.3 kony.push.setCallbacks
When an application on a device (iPhone, Android, BlackBerry, or Windows Phone 7) registers or deregisters for Push Notifications, or if the device receives a Notification, the device executes the function of your choice.
You can specify the functions to be executed for Push Notification in an Object for this API.
26.2.3.1 Signature
JavaScript: kony.push.setCallbacks(
)
26.2.3.2 Input Parameters
Object [Object] - Mandatory
A Hash table has the following key-value pairs: l onsuccessfulregistration [Function] - Mandatory: Specifies the function to be executed when the Push Notifications registration is successful.
l onfailureregistration [Function] - Mandatory: Specifies the function to be executed when the
Push Notifications registration fails.
l onlinenotification[Function] - Mandatory for iPhone, Android, and Windows. Optional for
BlackBerry. Specifies the function to be executed when the device receives a message when the application is running.
The message types for which this function is executed varies.
The message type on various platforms are as follows: iPhone: Sounds, Alerts, or Badges , Windows Phone 7: raw or toast , Blackberry: Text Alert.
l offlinenotification [Function] - Mandatory for iPhone, Android, and Windows. Optional for
BlackBerry. Specifies the function to be executed when the device receives a message when the application is not running.
The message types for which this function is executed varies.
The message type on iPhone is as follows: iPhone: Sounds, Alerts, or Badges
© 2015 by Kony, Inc. All rights reserved 498 of 848
Kony Studio API Developer's Guide
Version 5.0
l onsuccessfulderegistration [Function] - Mandatory. Specifies the function to be executed when the Push Notification deregistration is successful.
l onfailurederegistration [Function] - Mandatory for BlackBerry, Android, and Windows. Optional for iPhone. Specifies the function to be executed when the Push Notification deregistration is a failure.
l offlinecallback [Function] - Mandatory. Specifies the function to be executed when an action is invoked.
l payload [] - <need to update> l actionId [String] - A unique id to identify the action.
26.2.3.3 Return Values
None
26.2.3.4 Exceptions
The following error codes are applicable to onfailureregistration and onfailurederegistration functions: l
1403 - Registration failed by PNS - Account related or device restrictions (thrown by push.register() API during an onfailureregistration callback).
l
1404 - Deregistration failed - Unable to close channel or PNS internal error while deregistration
(thrown by push.deregister() API during an onfailurederegistration callback).
26.2.3.5 API Usage
You must call this API after the application is launched as this API will not be explicitly called by the user.
26.2.3.6 Implementation Details
The following are the implementation details of this API:
© 2015 by Kony, Inc. All rights reserved 499 of 848
Kony Studio API Developer's Guide
Version 5.0
Based on the status of the registration or deregistration attempt (success or failure) and the state of the application on the device (active or inactive) when the Push Notifications arrive, use the following snippet to call the associated functions: object = {onsuccessfulregistration:onsuccess , onfailureregistration:onfailure , onlinenotification:onlineCallback , offlinenotification:offineCallback, onsuccessfulderegistration:onderegsuccess , onfailurederegistration:onderegfailure }; kony.push.setCallbacks
(object); onsuccessfulregistration
If the registration for Push Notifications is successful, this callback is executed by the underlying platform.
The callback takes string as the parameter.
The following code snippet is an example of the onsuccessfulregistration callback: function onsuccess(identifier)
{ kony.print("Registered SUCCESSFULLY :"+identifier);
//Send the identifier to the Push Notifications Sender.
} onfailureregistration
If the registration for Push Notifications is a failure, this callback is executed by the underlying platform.
The callback takes an Object as the parameter.
The following code snippet is an example of the onfailureregistration callback: function onfailure(errortable)
{ kony.print("Registration Failed");
© 2015 by Kony, Inc. All rights reserved 500 of 848
Kony Studio API Developer's Guide
Version 5.0
kony.print(errortable["errorcode"]+errortable["errormessage]);
} onlinenotification
If the device receives a message when the application is running, this callback is executed by the underlying platform.
The callback takes an Object as the parameter.
Note: This function is not applicable on BlackBerry platform.
The following code snippet is an example of the onlinenotification callback: function onlineNotification(payload)
{
//payload is an Object that contains a set of key-value pairs provided by the respective Push Notification Server
} offlinenotification
If the device receives a message when the application is not running, this callback is executed by the underlying platform.
The callback takes an Object as the parameter.
Note: This function is not applicable on BlackBerry platform.
The following code snippet is an example of the offlinenotification callback: function offlineNotification(payload)
{
© 2015 by Kony, Inc. All rights reserved 501 of 848
Kony Studio API Developer's Guide
Version 5.0
//payload is an Object that contains a set of key-value pairs provided by the respective Push Notification Server
} onsuccessfulderegistration
If the deregistration for Push Notifications is successful, this callback is executed by the underlying platform.
The callback takes string as the parameter.
The following code snippet is an example of the onsuccessfulderegistration callback: function onderegsuccess()
{ kony.print("Deregistered Successfully :");
} onfailurederegistration
If the deregistration for Push Notifications is a failure, this callback is executed by the underlying platform.
The callback takes an Object as the parameter.
Note: This function is not applicable on iPhone platform.
The following code snippet is an example of the onfailurederegistration callback: function onderegfailure(errortable)
{ kony.print("Deregistration Failed"); kony.ui.Alert("Message : " +errortable ["errorcode"]+errortable
["errormessage"],null,"info",null,,"Info");
}
© 2015 by Kony, Inc. All rights reserved 502 of 848
Kony Studio API Developer's Guide
Version 5.0
26.2.3.7 JavaScript Example function regSuccessAndroidCallback(regId)
{ kony.print("** JavaScript regSuccessCallback() called **"); kony.print(regId);
} function regFailureAndroidCallback(errormsg)
{ kony.print("* JavaScript regFailureCallback() called *"); kony.print(errormsg["failurereason"]); kony.print(errormsg["description"]);
} function onlinePushNotificationAndroidCallback(msg)
{ kony.print("* JavaScript onlinePushNotificationCallback() called
*"); kony.print(msg); kony.print(msg["message"]);
} function offlinePushNotificationAndroidCallback(msg)
{ kony.print("* JavaScript offlinePushNotificationCallback() called
*"); kony.print(msg);
} function unregSuccessAndroidCallback()
{
© 2015 by Kony, Inc. All rights reserved 503 of 848
Kony Studio API Developer's Guide
Version 5.0
kony.print("* JavaScript unregSuccessCallback() called *");
} function unregFailureAndroidCallback(errormsg)
{ kony.print("* JavaScript unregFailureCallback() called *"); kony.print(errormsg["errorcode"]); kony.print(errormsg["errormessage"]);
} function callbackAndroidSetCallbacks()
{ kony.push.setCallbacks({onsuccessfulregistration: regSuccessAndroidCallback, onfailureregistration: regFailureAndroidCallback, onlinenotification: onlinePushNotificationAndroidCallback, offlinenotification: offlinePushNotificationAndroidCallback, onsuccessfulderegistration: unregSuccessAndroidCallback, onfailurederegistration: unregFailureAndroidCallback});
}
26.2.3.8 Platform Availability
Available on Android, iPhone, iPad, Windows, BlackBerry, and BlackBerry 10.
26.2.4 kony.push.register
This API allows you to register the application and the mobile device for Push Notifications. This API takes an Object as a parameter (the values in the table differ across platforms).
If the registration is successful, the platform invokes the onsuccessfulregistration function. If the
© 2015 by Kony, Inc. All rights reserved 504 of 848
Kony Studio API Developer's Guide
Version 5.0
registration is a failure, the platform invokes the onfailureregistration function.
26.2.4.1 Signature
JavaScript : kony.push.register(configObject)(
/
/
26.2.4.2 Input Parameters configObject [Array] - Mandatory (iPhone)
The Array for iPhone must contain any or all of the following: l
0 - Specifies the Notification type as Badge.
l
1 - Specifies the Notification type as Sound.
l
2 - Specifies the Notification type as Alert.
configObject [Object] - Mandatory (Android)
A Hash table for Android must contain the following key value pairs: l senderid - Specifies the project ID of the account registered to use GCM.
The projectID is the ID for a created API project.For registering projectID for Push Notifications, see http://developer.android.com/guide/google/gcm/gs.html
#create-proj configObject [Object] - Mandatory (BlackBerry)
The Hash table for BlackBerry must contain the following key value pairs: l appid - Specifies the unique application ID.
Note: You receive the application ID only after you register the application for Push
Notification with RIM.
© 2015 by Kony, Inc. All rights reserved 505 of 848
Kony Studio API Developer's Guide
Version 5.0
l port - Specifies the port number on the device where the Push Notifications are received.
Note: You receive the port information only after you register the application for Push Notification with Research in Motion(RIM).
l bpasurl - Specifies an HTTP version of the PPG base URL (Push Proxy Gateway).
You receive the BPAS URL only after you register the application for Push Notification with
RIM.
l appicon - Specifies the icon to be displayed when there are no messages in the queue (typically the application logo).
l starappicon - Specifies the icon to be displayed when there are unread messages in the queue (typically the application logo with a star on the top-right corner of the image (Image dimensions 54x54)).
l statusbaricon - Specifies the icon to be displayed in the status bar (top area on the home screen of the device (Image dimensions 17x17)).
configObject [Object]- Optional (Windows)
Windows Phone does not require any input parameters. However, you can specify the following
Optional key value pairs in the Object: l remoteimageurls (Optional) - Specifies an array of remote images to be displayed for a Tile message.
The sender can specify the image to be displayed on the Tile notification by specifying the image URL.
l enableraw (Optional): This is a Boolean parameter and it specifies if the device must receive raw messages or not. The default value is true (you can receive raw messages). If you do not want the device to receive raw messages, set the value to false .
l enabletile (Optional): This is a Boolean parameter and it specifies if the device must receive tile messages or not. The default value is true (you can receive tile messages). If you do not want the device to receive tile messages, set the value to false .
l enabletoast (Optional): This is a Boolean parameter and it specifies if the device must receive toast messages or not. The default value is true (you can receive toast messages). If you do not want the device to receive toast messages, set the value to false .
© 2015 by Kony, Inc. All rights reserved 506 of 848
Kony Studio API Developer's Guide
Version 5.0
26.2.4.3 Return Values
None
26.2.4.4 Exceptions
The following error codes are applicable to onfailureregistration and onfailurederegistration functions: l
1402 - Unable to connect to push service - PNS service is not available l
1403 - Registration failed by PNS - Account related or device restrictions (thrown by push.register() API during an onfailureregistration callback).
l
1405 - Duplicate Registration - Actual registration details should be provided? (thrown by kony.
push.register() API during an onfailureregistration callback) l
1406 - Platform-specific issue. Full details are available in the errormessage. For example, received payload but payload is in incorrect format.
l
An error is thrown if input type is invalid or does not follow the expected structure.
l
102-Invalid input error
26.2.4.5 API Usage
You must use this API to register the application and the device for Push Notifications with the Push
Notifications service provider.
26.2.4.6 JavaScript Example
The following are the examples for this API on various platforms:
Android
The following code snippet uses the senderid to register for Push Notifications:
//The following code snippet uses the senderid to register for Push
Notifications:
© 2015 by Kony, Inc. All rights reserved 507 of 848
Kony Studio API Developer's Guide
Version 5.0
var config = {senderid="4815162342"}; kony.push.register(config);
BlackBerry
The following code snippet uses the appid, port, bpasurl, appicon, starappicon, and statusbaricon to register for Push Notifications: var config = {appid:"1016-1no1ha3e5111ryMa71",port:20921,bpasurl:
"http://pushapi.eval.blackberry.com",appicon:"icon.png", starappicon:"starappicon.png",statusbaricon:"statusicon.png"} kony.push.register(config); iPhone
The following code snippet uses the notification types to register for Push Notifications:
//The following code snippet uses the notification types to register for
Push Notifications: var config=[0,1,2]; kony.push.register(config);
Windows Phone
The following code snippet uses the remoteimageurls as the key and the link specifies the images to be displayed in the tile notification as the value: var config={remoteimageurls:
["http://www.thisisfanzoo.com/blog/samples/ logo2.png",
"http://www.yahoo.com/samples/logo3.png"],enableraw:true,enabletile
© 2015 by Kony, Inc. All rights reserved 508 of 848
Kony Studio API Developer's Guide
Version 5.0
:false, enabletoast:false}; kony.push.register(config);
Note: Only network URL's are allowed. MPNS allows only images from trusted domains
(registered to MPNS) to be displayed to avoid image policies. There is no such restriction on local images.
26.2.4.7 Platform Availability
Available on Android, iPhone, iPad, Windows, BlackBerry, and BlackBerry 10.
26.2.5 kony.push.deRegister
This API allows an application on a device to deregister from Push Notifications. This API takes an empty Object as the parameter.
If the deregistration is successful, the platform invokes the onsuccessfulderegistration function. If the deregistration is a failure, the platform invokes the onfailurederegistration function.
26.2.5.1 Signature
JavaScript : kony.push.deRegister(
)
26.2.5.2 Input Parameters emptyObject [Object]- Mandatory
Is an empty Object.
26.2.5.3 Return Values
None
26.2.5.4 Exceptions
The following error codes are applicable to onfailureregistration and onfailurederegistration functions:
© 2015 by Kony, Inc. All rights reserved 509 of 848
Kony Studio API Developer's Guide
Version 5.0
l
1402 - Unable to connect to push service - PNS service is not available l
1403 - Registration failed by PNS - Account related or device restrictions (thrown by push.register() API during an onfailureregistration callback).
l
1404 - Deregistration failed - Unable to close channel or PNS internal error while deregistration
(thrown by push.deregister() API during an onfailurederegistration callback).
l
1405 - Duplicate Registration - Actual registration details should be provided? (thrown by kony.
push.register() API during an onfailureregistration callback) l
1406 - Platform-specific issue. Full details are available in the errormessage. For example, received payload but payload is in incorrect format.
l
An error is thrown if input type is invalid or does not follow the expected structure.
l
102-Invalid input error
26.2.5.5 API Usage
You must use this API to deregister the application and the device from the Push Notifications service.
26.2.5.6 JavaScript Example
To deregister from Push Notifications, use the following code snippet: var myhash = new Hash(); kony.push.deRegister(myhash);
26.2.5.7 Platform Availability
Available on Android, iPhone, iPad, Windows, BlackBerry, and BlackBerry 10.
26.2.6 kony.push.getMessageCount
This API fetches the number of unread push notification messages that are stored on the device database.
© 2015 by Kony, Inc. All rights reserved 510 of 848
Kony Studio API Developer's Guide
Version 5.0
26.2.6.1 Signature
JavaScript: kony.push.getMessageCount()
26.2.6.2 Input Parameters
None.
26.2.6.3 Return Values numberOfMessages [Number]
Returns the number of messages.
26.2.6.4 Exceptions
The following error codes are applicable to onfailureregistration and onfailurederegistration functions: l
1402 - Unable to connect to push service - PNS service is not available l
1406 - Platform-specific issue. Full details are available in the errormessage. For example, received payload but payload is in incorrect format.
26.2.6.5 Platform Availability
Available only on BlackBerry and BlackBerry 10.
26.2.6.6 JavaScript Example
The following code snippet is an example of this API: function callbackGetMessageCount()
{ var count = kony.push.getMessageCount(); kony.print("Message Count : "+count);
}
© 2015 by Kony, Inc. All rights reserved 511 of 848
Kony Studio API Developer's Guide
Version 5.0
26.2.7 kony.push.getMessages
Gets the unread notification messages from the device database. Once this function is called, the device database is cleared and the message count is reset to zero.
26.2.7.1 Signature
JavaScript :kony.push.getMessages()
26.2.7.2 Input Parameters
None.
26.2.7.3 Return Values messages [Object]
Returns an Object that has all the messages
26.2.7.4 Exceptions
The following error codes are applicable to onfailureregistration and onfailurederegistration functions: l
1402 - Unable to connect to push service - Push Notification Service (PNS) is not available .
l
1404 - Platform-specific issue. Full details are available in the error message. For example, received payload but payload is in incorrect format.
26.2.7.5 Platform Availability
Available only on BlackBerry and BlackBerry 10.
26.2.7.6 JavaScript Example
The following code snippet is an example of this API: function callbackGetMessages()
{
© 2015 by Kony, Inc. All rights reserved 512 of 848
Kony Studio API Developer's Guide
Version 5.0
var messages = kony.push.getMessages(); alert(messages);
}
26.2.8 Important Considerations for Android
The following are the important considerations you must be aware for Android platform: l
Before you build the application for Android, navigate to the Project Properties of the application and navigate to Native App -> Android tab, and select the GCM under the Push Notification section. Selecting this option will copy the required Push Notification libraries into the application during build time." l
For C2DM to GCM conversion refer, http://developer.android.com/guide/google/gcm/c2dm.html
l
Google may occasionally refresh the Registration ID. Hence, you must design the application to update the third-party Application server with the new ID.
If the Kony Android platform receives a new registration ID, the following takes place: l
If the application is running in the foreground or the background onsuccessfulregistration function is called.
l
If the application is not running - a status bar notification is displayed. If you select the notification, the application is launched and onsuccessfulregistration function is called.
l
If the Kony Android platform receives a new Push Notification message, the following takes place: l
If the application is running in the foreground onlinenotification function is called.
l
If the application is running in the background - status bar notification is displayed. If you select the notification, the application is brought to the foreground and its onlinenotification function is called.
© 2015 by Kony, Inc. All rights reserved 513 of 848
Kony Studio API Developer's Guide
Version 5.0
l
If the application is not running - status bar notification is displayed. If you select the notification, the application is launched and offlinenotification function is called.
l
The status bar notification is displayed by the platform with the default settings.
The default settings are in the pushconfig.xml file (available after the application is built) in "dist\
{APP-ID}\res\values" location.
You can override and configure the notification parameters like title, vibrate and sound by placing the pushconfig.xml in the"resources\mobilerichclient\android\values" directory (located under your project workspace folder).
l
To customize GCM broadcast receiver, refer Kony Studio User Guide .
26.2.9 Important Considerations for BlackBerry
The following are the important considerations that you must be aware of for BlackBerry platform: l
You must test the Push Notifications on an actual device and not on an emulator. Since the emulator does not have a unique device id, you cannot test all network related error cases.
l
Push Notifications is supported on all BlackBerry devices. However, the Home Screen notifications (appicon, starappicon, and statusbaricon) are available only on BlackBerry devices
5.0 and above.
l
Push Notifications service is available only to the users who have subscribed to a Full BIS data plan. Push Notifications service does not work on any other BlackBerry transports. For example, MDS, WAP2, or TCP/IP.
l
The appid and the port must be unique to the application. You can acquire them by registering the application (the registration process takes up to two weeks to complete).
To register, you can use the following links:
For Evaluation: https://www.blackberry.com/profile/?eventId=8121
For Production: https://www.blackberry.com/profile/?eventId=8207
© 2015 by Kony, Inc. All rights reserved 514 of 848
Kony Studio API Developer's Guide
Version 5.0
l
If you receive an error code rc=10002 during registration, it means that there is an issue related to the appid. The appid is either empty or has expired.
26.2.10 Reference Links
You can get detailed information regarding the implementation of Push Notifications on various platforms, by visiting the following links:
Android http://code.google.com/android/c2dm
BlackBerry http://us.blackberry.com/developers/platform/pushapi.JavaScriptp
iPhone http://developer.apple.com/library/ios/documentation/NetworkingInternet/
Conceptual/RemoteNotificationsPG/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008194-
CH1-SW1
Windows Phone: http://msdn.microsoft.com/en-us/library/ff402537(VS.92).aspx
26.3 Notification Settings
Note: Notification setting APIs work on the following OS versions.
• iOS8 and above
• Android 4.1 and above
© 2015 by Kony, Inc. All rights reserved 515 of 848
Kony Studio API Developer's Guide
Version 5.0
You can send actionable notifications using the notification setting APIs. User notifications can have additional custom actions. Two actions can be displayed on the lock screen, in a banner, and in the
Notification Center. In alerts, notifications can display up to four actions when a user taps the Options button. To use notification actions in your app, you need to register the actions, schedule a local notification or a remote notification, and handle the action chosen by the user.
Following are the types of notifications: l
Alert or Banner: Based on the preferences a user sets in the devices, a notification is shown using either an alert view or a banner. Both the alert and banner should contain the message of the notification.
l
Sound: A predefined or a custom sound is played when the notification is fired. In most cases, users will not look at the device all the time, so any notifications could be easily overlooked.
l
Badge: A badge number can also be shown in the app’s icon when a new notification is fired.
The badge number must be increased by one with a new notification, and then decreased when the notification is handled. iOS automatically shows and hides the badge, depending on whether there is a value other than zero to display.
Actions, Categories, Settings
Actions: Specifies the actions that any user can perform to interact with the notification message.
Actions are presented as buttons and defined by the kony.notificationsettings.createAction
.
Categories: Specifies a group of actions into a category. They categories are defined by the kony.notificationsettings.createCategory
.
Settings: The settings must be registered by the application, and they contain all the categories and notification types that we create. These settings are defined by the kony.notificationsettings.registerCategory
.
Following are the notification settings APIs:
© 2015 by Kony, Inc. All rights reserved 516 of 848
Kony Studio API Developer's Guide
Version 5.0
l
kony.notificationsettings.createAction
l
kony.notificationsettings.createCategory
l
kony.notificationsettings.registerCategory
26.3.1 kony.notificationsettings.createAction
This API helps you create an action that can be used with category.
26.3.1.1 Signature
JavaScript: kony.notificationsettings.createAction (actionId, label, pspConfig)
26.3.1.2 Input Parameters actionId [String] - Mandatory
Specifies a unique ID to identify the action chosen by a user.
label [String] - Mandatory
Specifies a label that needs to be associated with a action.
pspConfig [JSObject] - Mandatory
Specifies the configuration function. The parameters follow: l image [Number] - Mandatory: This parameter is applicable only on the Android platform. Set the image to be displayed for notification settings.
l activationMode [Number] - Mandatory: Specifies the activation mode. The options are: l kony.notificationsettings.ACTIVATION_MODE_FORWARDS: If you set this option, the action will occur in the foreground and launches the application interface.
© 2015 by Kony, Inc. All rights reserved 517 of 848
Kony Studio API Developer's Guide
Version 5.0
l kony.notificationsettings.ACTIVATION_MODE_BACKWARDS: If you set this option, the action will occur in the background without launching the application interface.
Note: The activationMode property is applicable only for the iOS platform.
l authenticationRequired [Boolean] - Mandatory: This parameter is applicable only on iOS platform. This parameter is applicable only when you set activationMode as kony.notificationsettings.ACTIVATION_MODE_BACKWARDS. The user needs to unlock the device, and action occurs in the background.
l destructive [Boolean] - Mandatory: This parameter is applicable only on iOS platform. Set this value to true, if the notification is self destructive. Otherwise, set it to false.
l visibleOn [String] - Mandatory: Set this parameter to display the notification on a watch, or both watch and phone. The options are: l kony.notificationsettings.WATCH_ONLY
l kony.notificationsettings.BOTH
26.3.1.3 Return Values
This API returns action as a JavaScript object.
26.3.1.4 Platform Availability
Available on iOS and Android platforms.
26.3.1.5 JavaScript Example
//Using kony.notificationsettings.createAction
© 2015 by Kony, Inc. All rights reserved 518 of 848
Kony Studio API Developer's Guide
Version 5.0
var accept = kony.notificationsettings.createAction({
"id": "Accept",
"label": "Accept",
"pspConfig": {
"activationMode": kony.notificationsettings.ACTIVATION_
MODE_FORWARDS,
"authenticationRequired": true,
"destructive": true
}
}); var reject = kony.notificationsettings.createAction({
"id": "Reject",
"label": "Reject",
"pspConfig": {
"activationMode": kony.notificationsettings.ACTIVATION_
MODE_BACKWARDS,
"authenticationRequired": false,
"destructive": false
}
}); var decline = kony.notificationsettings.createAction({
"id": "Decline",
"label": "Decline",
"pspConfig": {
"activationMode": kony.notificationsettings.ACTIVATION_
MODE_BACKWARDS,
"authenticationRequired": true,
"destructive": false
}
});
© 2015 by Kony, Inc. All rights reserved 519 of 848
Kony Studio API Developer's Guide
Version 5.0
26.3.2 kony.notificationsettings.createCategory
This API helps you create a category with a group of created actions.
26.3.2.1 Signature
JavaScript: kony.localnotifications.createCategory (categoryId, actions, pspConfig:
{minimalActions:[actions] });
26.3.2.2 Input Parameters categoryId [String] - Mandatory
Specifies a unique ID for the group of actions that are defined.
actions [array] - Mandatory
Specifies the actions that are associated with the category. Pass null, if no actions are associated with the category.
Note: In Default Context, you cannot add more than four actions on the iOS platform and three actions in the Android platform.
pspConfig [JSObject] - Mandatory
Specifies the configuration function. The parameter is: l minimalActions [array] - Mandatory: This parameter is applicable only on the iOS platform. Specify the actions that are to be associated for minimal actions for the category.
Note: In default mode, you cannot add more than two actions.
26.3.2.3 Return Values
This API returns category as a JavaScript object.
© 2015 by Kony, Inc. All rights reserved 520 of 848
Kony Studio API Developer's Guide
Version 5.0
26.3.2.4 Platform Availability
Available on iOS and Android platforms.
26.3.2.5 JavaScript Example
//Using kony.notificationsettings.createCategory
var defaultActionContextArr = [accept, reject, decline]; var minimalActionContextArr = [accept, reject]; var categoryObj = kony.notificationsettings.createCategory({
"categoryId": invitation,
"actions": defaultActionContextArr,
"pspConfig": {
"minimalActions": minimalActionContextArr
}
});
26.3.3 kony.notificationsettings.registerCategory
This API helps you register the created category with the application.
26.3.3.1 Signature
JavaScript: kony.notificationsettings.registerCategory (categories, pspConfig)
26.3.3.2 Input Parameters category [array] - Mandatory
Specifies the category objects that are to be registered.
© 2015 by Kony, Inc. All rights reserved 521 of 848
Kony Studio API Developer's Guide
Version 5.0
pspConfig [JSObject] - Optional
This parameter is applicable on iOS platform only. It specifies the platform specific configuration function. The arguments are: l types [String] - Mandatory: Configure this parameter to register the type of notification. The Array for iPhone must contain any or all of the following: l
0 - Specifies the notification type as Badge.
l
1 - Specifies the notification type as Sound.
l
2 - Specifies the notification type as Alert.
Note: If the types are not passed or pspConfig is not defined, then all the notification types are registered by the API.
Note: If the same API is invoked multiple times, the details of the last invoked call are updated.
26.3.3.3 Return Values
None
26.3.3.4 Platform Availability
Available on iOS and Android platforms.
26.3.3.5 JavaScript Example
//Using kony.notificationsettings.registerCategory
var categoryArr = [categoryObj]; kony.notificationsettings.registerCategory({
"categories": categoryArr,
"pspConfig": {
© 2015 by Kony, Inc. All rights reserved 522 of 848
Kony Studio API Developer's Guide
Version 5.0
});
}
"types": [0, 1, 2]
Handling Local and Remote Notifications Callbacks: l
If the app is in the foreground state (app instance alive), an onlinecallback should be invoked.
l
If the app is in background state (app instance alive or not alive), an offlinecallback should be invoked.
© 2015 by Kony, Inc. All rights reserved 523 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27. Offline Data Access APIs
These APIs allow you to store data onto the device data store persistently (available after application or device restart). Such data can be accessed even if the device is offline (not connected to any wireless network [cellular or WIFI]. The API libraries are as follows: l
o
o
o
o
o
o
l
o
o
o
o
o
o
l
o
o
© 2015 by Kony, Inc. All rights reserved 524 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
o
27.1 Local Storage APIs
LocalStorage APIs allow the users to store and retrieve data in HTML pages from the same domain.
The data can be retrieved from all the windows in the same domain even if the browser is restarted.
The data stored using the LocalStorage APIs is accessible only from the client-side as opposed to the data stored in cookies (accessible from both client-side and server-side). You can store huge data using these APIs.
27.1.1 kony.store.key
This API returns the name of the n th key in the list. If n is greater than the number of key/value pairs in the object, then this method returns null for JavaScript.
27.1.1.1 Signature kony.store.key(
27.1.1.2 Parameters index [Number] - Mandatory
Specifies the index for which the key name is to be returned.
27.1.1.3 Return Values keyname [String]
Returns the keyname of the specified index.
null/nil
Returns null/nil when the specified index is greater than the number of key/value pairs in the object.
© 2015 by Kony, Inc. All rights reserved 525 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.1.1.4 Exceptions
LocalStorageError
Error
27.1.1.5 Implementation Details
For implementation details, see http://www.w3.org/TR/webstorage/#the-localstorage-attribute .
27.1.2 Platform Availability
Available on all platforms*. *Dummy Implementation on Mobile Web.
27.1.2.1 JavaScript Example var keyName = kony.store.key(0); alert("first key name is "+keyName);
27.1.3 kony.store.setItem
This API creates a structured clone of the given value. If this raises an exception then the list associated with the object is left unchanged.
27.1.3.1 Signature
JavaScript : kony.store.setItem(
,
27.1.3.2 Parameters key [string] - Mandatory
Specifies the keyname for which the item needs to be set
© 2015 by Kony, Inc. All rights reserved 526 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
value [object] - Mandatory
Specifies the value that must be set at the given index. This value can be a number, string,
Boolean.
27.1.3.3 Return Values
None.
27.1.3.4 Exceptions
LocalStorageError
Error
27.1.3.5 Implementation Details
For implementation details, see http://www.w3.org/TR/webstorage/#the-localstorage-attribute .
27.1.4 Platform Availability
Available on all platforms*. *Dummy Implementation on Mobile Web.
27.1.4.1 JavaScript Example kony.store.setItem("keyValue5", "this is a key value"); kony.store.setItem("keyValue4", true);
27.1.5 kony.store.getItem
This API returns a structured clone of the current value associated with the given key. If the given key does not exist in the list associated with the object then this method returns null for JavaScript.
27.1.5.1 Signature
JavaScript : kony.store.getItem(
© 2015 by Kony, Inc. All rights reserved 527 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.1.5.2 Parameters keyname [String] - Mandatory
Specifies the keyname from which the item needs to be fetched.
27.1.5.3 Return Values myitem [Object]
Returns the item located at the specified index.
27.1.5.4 Exceptions
LocalStorageError
Error
27.1.5.5 Implementation Details
For implementation details, see http://www.w3.org/TR/webstorage/#the-localstorage-attribute .
27.1.6 Platform Availability
Available on all platforms*. *Dummy Implementation on Mobile Web.
27.1.6.1 JavaScript Example var myValue = kony.store.getItem("name"); alert("name is "+myValue);
27.1.7 kony.store.removeItem
This API removes the item identified by the key, if it exists. If no item with that key exists, the method does not perform any action.
© 2015 by Kony, Inc. All rights reserved 528 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.1.7.1 Signature
JavaScript
:kony.store.removeItem( keyname
)
27.1.7.2 Parameters keyname [String] - Mandatory
Specifies the keyname for which the item needs to be removed.
27.1.7.3 Return Values
This API does not return a value.
27.1.7.4 Exceptions
LocalStorageError
Error
27.1.7.5 Implementation Details
For implementation details, see http://www.w3.org/TR/webstorage/#the-localstorage-attribute .
27.1.8 Platform Availability
Available on all platforms*. *Dummy Implementation on Mobile Web.
27.1.8.1 JavaScript Example kony.store.removeItem("name"); alert("name removed");
© 2015 by Kony, Inc. All rights reserved 529 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.1.9 kony.store.clear
This API allows you to empty the database by clearing all the key-value pairs. If there are no key-value pairs, then the API does not do anything.
27.1.9.1 Signature
JavaScript : kony.store.clear()
27.1.9.2 Parameters
None
27.1.9.3 Return Values
None.
27.1.9.4 Exceptions
LocalStorageError
Error
27.1.9.5 Implementation Details
For implementation details, see http://www.w3.org/TR/webstorage/#the-localstorage-attribute .
27.1.10 Platform Availability
Available on all platforms*. *Dummy Implementation on Mobile Web.
27.1.10.1 JavaScript Example try
{ kony.store.clear();
© 2015 by Kony, Inc. All rights reserved 530 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
alert("store is cleared");
} catch(err)
{ alert("error occurred in clear() and the error is :"+err);
}
27.1.11 kony.store.length
This API returns the length of the local storage.
27.1.11.1 Signature
JavaScript : kony.store.length()
27.1.11.2 Parameters
None
27.1.11.3 Return Values mylength [String]
Returns the length of the local storage.
27.1.11.4 Exceptions
LocalStorageError
Error
27.1.11.5 Implementation Details
For implementation details, see http://www.w3.org/TR/webstorage/#the-localstorage-attribute .
27.1.12 Platform Availability
Available on all platforms*. *Dummy Implementation on Mobile Web.
© 2015 by Kony, Inc. All rights reserved 531 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.1.12.1 JavaScript Example mylength = kony.store.length(); alert("length is "+mylength);
27.2 Web SQL APIs
The WebSQL APIs allow you to manipulate client-side databases using SQL. You can use these APIs to store data in databases that can be queried using a variant of SQL.
For BlackBerry, these APIs are supported only on 5.0 and above versions.
Important: WebSQL implementation utilizes the database engines bundled along with the underlying SDK (SQLite in most of the cases). Kony Platform ensures that the WebSQL semantics are same across platforms, but the uniformity of SQL semantics across native platforms is not guaranteed. For example, the WebSQL APIs have no control over the way CONSTRAINTS are supported as per the SQL92 specification. For more information on SQLite refer
.
Important: WebSQL APIs are not supported on Internet Explorer and Firefox.
Important: The framework does not store the password argument to kony.db.openDatabase()
API, it is the responsibility of application developer to secure the password.
The actual database used for storing the data and its visibility to other applications is defined in the following table:
Platform iPhone/iPad
Client Database
Engine
SQLite
Accessible to other applications
The storage area is unique to the application.
© 2015 by Kony, Inc. All rights reserved 532 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
Android/Android Tablet
BlackBerry
Windows 6x
Windows Phone 7.5
Windows Phone 8
Windows Phone 8.1
Windows Desktop/Kiosk
Windows 8
Windows 8.1
Symbian
Platform
Single Page Application
(SPA)
Client Database
Engine
SQLite
SQLite
SQL Server CE
SQLite
SQLite
SQLite
SQLite
SQLite
SQLite
SQLite
SQLite
Accessible to other applications
The storage area is unique to the application.
SDCard. Data is accessible to other applications.
File System. Data is accessible to other applications.
The storage area is unique to the application.
The storage area is unique to the application.
The storage area is unique to the application.
The storage area is unique to the application.
The storage area is unique to the application.
The storage area is unique to the application.
The storage area is unique to the application.
Determined by the browser implementation.
© 2015 by Kony, Inc. All rights reserved 533 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
The following table indicates the JavaScript datatypes and their corresponding SQLite datatypes:
JavaScript Datatype string number byte array (rawbytes) boolean
SQLite Datatype
TEXT
REAL
BLOB
BOOLEAN
Note: You must create an SD Card to use the WebSQL APIs on a BlackBerry emulator.
To create the SD card, follow these steps:
1. Launch the required BlackBerry emulator.
2. Go to Simulate -> Change SD Card -> Mount Directory.
3. Point the location to any directory of your choice.
4. Click OK.
5. Click Close.
27.2.0.1 Limitations
This section describes the limitations of WebSQL APIs: l
Table names and Column names are case-sensitive. For example, "Employee" and "employee" refer to two different tables. It is observed that table names and columns name are caseinsensitive on Android and BlackBerry platforms, but case-sensitive on iPhone platform. For a cross platform uniform behavior, assume that the table names and column names are casesensitive.
© 2015 by Kony, Inc. All rights reserved 534 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
l
When using the binding "?" placeholders, ensure that the number of binding parameters and the number of values are the same. Else, the database can be inconsistent.
For example, the following statement can cause the database to be inconsistent as the number of binding parameters are 6 and the number of values are 3: local stmt3 = "insert into EMP_DETAILS values(?,?,?,?,?,?)" kony.db.executeSql(tx,stmt3,{'1','2','3'}, successCallback,errorCallback); l
Nested database transactions are not supported across platforms. Avoid starting a new transaction in the successcallback function of an existing transaction.
l
The error codes might vary between the platforms. This is due to the fact that underlying SDKs do not expose all the errors that can be mapped to HTML5 WebSQL Specification. The application should not build its business logic around these error codes. These error codes are only for diagnostic purpose.
l
Accessing insertid key in the resultset rows leads to an error in SPA.
l
The WebSQL APIs are not supported on Internet Explorer and Firefox.
27.2.1 kony.db.openDatabase
This API allows you to open the specified version of a database. This is an asynchronous API.
Important: The passphrase parameter in this API is not supported in 6.5 plugins, so database encryption is not available in 6.5 plugins.
27.2.1.1 Signature kony.db.openDatabase(
,
displayName , estimatedSize , passphrase
)
© 2015 by Kony, Inc. All rights reserved 535 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.2.1.2 Parameters dbname [String] - Mandatory
Specifies the actual name of the database that you want to open.
version [String] - Mandatory
Specifies the version of the database that you want to open.
displayName [String] - Mandatory
Specifies the display name of the database that you want to open.
estimatedSize [Number] - Optional
Specifies the approximate size of the database in bytes.
Note: This parameter is applicable only on the SPA platform.
passphrase
This is applicable for
and
iOS passphrase[Array] - Optional
In iOS, this argument is used to specify Pragma statements (Array) to encrypt database.
Usage l
To link the SQLCipher library, extract the KAR file with -sqlcipher option. After the extraction, pass the passphrase for the SQL engine to encrypt the database. perl extract.pl /Users/PLATFROM/Downloads/konyappipad.KAR – sqlcipher
Note: For more information on this parameter and Pragma statements, see https://www.zetetic.net/sqlcipher/sqlcipher-api/ .
© 2015 by Kony, Inc. All rights reserved 536 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
Android passphrase [String] - Optional
In Android, this argument is used to specify password (String) to encrypt the database.
The developer needs to enable Support SQL DB Encryption (FIPS) option in Kony Studio
> Application Properties > Native > Android section in order to support database encryption using passphrase.
Windows Phone 8/8.1
If a password is provided to the openDatabase API, the database will be encrypted.
For database encryption a set of licensed components must be obtained from Zetetic inc. for
Windows Phone 8 and Windows Phone 8.1. For more information, see https://www.zetetic.net/sqlcipher/buy/ .
The dll/class library is provided by Zenetic Inc as a zipped file. It contains the sqlcipher dlls built for arm and x86 architectures and should be copied to the windowsphone8 folder, as shown in the following figure.
© 2015 by Kony, Inc. All rights reserved 537 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
During the build process these dlls are unzipped and added to the xap file used for application deployment. The name of the zip file for Windows Phone 8 must be sqlcipherwp8.zip. The zip file for Windows Phone 8.1 must be sqlcipherwp81.zip. The zip files should have folders for each architecture type, where the dlls for each architecture are placed.
Each architecture folder should contain the following 3 files: l
Sqlite.winmd
l
Sqlite.dll
l sqlite3.dll
Windows 8.1 and Windows Kiosk
A free version of the sqlite library is available to support encryption. Therefore a license is not needed and you do not need to copy the zip files.
Important:
The database will not be encrypted in the following conditions:
1. If Support SQL DB Encryption (FIPS) option is enabled and empty string is passed as passphrase.
2. If Support SQL DB Encryption (FIPS) option is not enabled ,passphrase will be ignored and database is non encrypted.
3. If passphrase is not passed.
Important: Encrypted and non-encrypted databases cannot be interchangeably opened using this
API.
© 2015 by Kony, Inc. All rights reserved 538 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
Important: The other Web SQL APIs operate on encrypted DB seamlessly if the
databaseObjectId
passed to them is opened using
kony.db.openDatabase()
API with passphrase.
Important: The framework does not store the passphrase argument to
kony.db.openDatabase()
API, it is responsibility of application developer to secure the password.
27.2.1.3 Return Values databaseObjectId [userdata]
Returns the unique ID of the database. The identifier is userdata ( platform specific instance) and is not specifically String. Developers must not rely on the type of the identifier.
27.2.2 Platform Availability
Available on all platforms(dummy implementation on MobileWeb) except for SPA in Windows Phone
7.5 browser, and for desktop IE8, IE9, and IE10 browsers.
27.2.2.1 JavaScript Example
//The below function will invoke openDatabase function openDatabase()
{ var dbName="konytestDB"; var version="1.0"; var displayName="demo web SQL Database"; var estimatedSize=5*1024*1024; //5*1024*1024 indicates 5 MB
//Note: Use only one of the statements depending on platform is Android or iOS
//Passphrase is string in case of android.
© 2015 by Kony, Inc. All rights reserved 539 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
var passphrase = "samplepassword";
//Passphrase is pragma array in case of android.
passphrase = ["PRAGMA key = 'old passphrase';"]; var databaseObjectId =kony.db.openDatabase(dbName,version, displayName, estimatedSize,passphrase);
//databaseObjectId contains the unique ID of the database
}
//Android Example using password parameter var databaseObjectId =kony.db.openDatabase("konytestDB",1.0,"demo web SQL Database",5*1024*1024,"samplepassword");
27.2.3 kony.db.transaction
This API allows you to execute the specified transaction on the given database. When you invoke this
API, it returns immediately and asynchronously executes the transaction.
This is an asynchronous API. This API creates an
SQLTransaction
object.
Important: The table names and column names are case sensitive.
27.2.3.1 Signature
JavaScript : kony.db.transaction(
,
,
,
27.2.3.2 Parameters dbaseObjectId [String] - Mandatory
Specifies the unique ID of the database
© 2015 by Kony, Inc. All rights reserved 540 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
transactionCallback [Function] - Mandatory
Specifies the callback function that contains the transactions.
For example, function callback(dbId)
{
//SQLTransaction contains implementation of executeSql method
// invoke database.executesql method for sql trasaction
}; transactionErrorCallback [Function] - Optional
Specifies the callback that must be executed if there is an error in executing the transaction. This callback function is used to roll back the updates to the database.
For example, function errorCallback(SQLError)
{
//write code here
} successCallback [Function] - Optional
Specifies the callback that must be executed if the transaction is successful.
For example, function successCallback()
{
//code here
}
© 2015 by Kony, Inc. All rights reserved 541 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
When the transaction is successful, this callback is executed along with the callback function of the kony.db.executeSql API.
27.2.3.3 Return Values
None.
27.2.4 Platform Availability
Available on all platforms* except for SPA in Windows Phone 7.5 and windows Phone 8 browsers, for desktop IE8, IE9, IE10 browsers.*Dummy Implementation on Mobile Web.
27.2.4.1 JavaScript Example
//The below function specifies the callback function that contains the transactions.
function myTransactionCallback(dbId)
{
//SQLTransaction contains implementation of executeSql method
// invokekony.db.executeSql method for sql trasaction
}
//The below function specifies the callback that must be executed if there is an error in executing the transaction. This callback function is used to roll back the updates to the database.
function myTransactionErrorCallback(SQLError)
{
// proceed with the logic
}
//The below function specifies the callback that must be executed if the transaction is successful.
function mySuccessCallback()
© 2015 by Kony, Inc. All rights reserved 542 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
{
}
// proceed with the logic
//The below function will invoke transaction function transaction()
{ var dbName="konytestDB"; var version="1.0"; var displayName="demo web SQL Database"; var estimatedSize=5*1024*1024; //5*1024*1024 indicates 5 MB var databaseObjectId =kony.db.openDatabase(dbName,version, displayName, estimatedSize);
//databaseObjectId contains the unique ID of the database kony.db.transaction(databaseObjectId, myTransactionCallback, myTransactionErrorCallback, mySuccessCallback);
}
27.2.5 kony.db.readTransaction
This API allows you to read a specified transaction. This API creates a SQLTransaction object for read-only transactions.
When you invoke this API, it returns immediately and asynchronously reads the transaction.
Important: You can only read queries using this API. The kony.db.readTransaction API results in a SYNTAX_ERR in case of DML commands in the SQL statement. DML commands are not supported in this API.
Important: The table names and column names are case sensitive.
© 2015 by Kony, Inc. All rights reserved 543 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.2.5.1 Signature
JavaScript : kony.db.readTransaction
(
,
,
)
27.2.5.2 Parameters dbaseObjectId [String] - Mandatory
Specifies the unique ID of the database.
TransactionCallback [Function] - Mandatory
Specifies the callback function that contains the transactions.
For example, function callback(dbId)
{
//Code
}
TransactionErrorCallback [Function] - Optional
Specifies the callback that must be executed if there is an error in executing the transaction. This callback function is used to roll back the updates to the database.
For example, function errorCallback(SQLError)
{
//Code
}
© 2015 by Kony, Inc. All rights reserved 544 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
SuccessCallback [Function] - Optional
Specifies the callback that must be executed if the transaction is successful.
For example, function successCallback()
{
//code
}
27.2.5.3 Return Values
None.
27.2.6 Platform Availability
Available on all platforms* except for SPA in Windows Phone 7.5 and windows Phone 8 browsers, for desktop IE8, IE9, IE10 browsers.*Dummy Implementation on Mobile Web.
27.2.6.1 JavaScript Example
//The below function specifies the callback function that contains the transactions.
function myTransactionCallback(dbId)
{
//SQLTransaction contains implementation of executeSql method
// invokekony.db.executeSql method for sql trasaction
}
//The below function specifies the callback that must be executed if there is an error in executing the transaction. This callback function is used to roll back the updates to the database.
function myTransactionErrorCallback(SQLError)
{
© 2015 by Kony, Inc. All rights reserved 545 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
// proceed with the logic
}
//The below function specifies the callback that must be executed if the transaction is successful.
function mySuccessCallback()
{
// proceed with the logic
}
//The below function will invoke readTransaction function readTransaction()
{ var dbName="konytestDB"; var version="1.0"; var displayName="demo web SQL Database"; var estimatedSize=5*1024*1024; //5*1024*1024 indicates 5 MB var databaseObjectId =kony.db.openDatabase(dbName,version, displayName, estimatedSize);
//databaseObjectId contains the unique ID of the database kony.db.readTransaction(databaseObjectId, myTransactionCallback, myTransactionErrorCallback, mySuccessCallback);
}
27.2.7 kony.db.executeSql
This API allows you to execute a specified SQL statement on the given database. This is an asynchronous API.
Important: The table names and column names are case sensitive.
© 2015 by Kony, Inc. All rights reserved 546 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.2.7.1 Signature
JavaScript: kony.db.executeSql(
,
,
,
27.2.7.2 Parameters transactionId [String] - Mandatory
Specifies the unique ID of the transaction.
SQLStatement [String] - Mandatory
Specifies the SQL statement that must be executed.
arguments [Object] - Optional
Specifies the arguments for executing the SQL statement. If this parameter is not specified or is nil, then the statement is executed without any arguments.
The supported argument types are: l
NULL in JavaScript l
REAL l
TEXT l
BLOB.
No type affinity is performed.
SQLStatementSuccessCallback [Function] - Optional
Specifies the callback function that must be executed when the execution of the SQL statement is a success
SQLStatementErrorCallback [Function] - Optional
Specifies the callback function that must be executed when the execution of the SQL statement is a failure.
© 2015 by Kony, Inc. All rights reserved 547 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
This callback returns a boolean value.
l true - ends the execution of the transaction. true is returned if there is no callback function specified as a parameter.
Important: When true is returned, the transaction is rolled back.
l false - continues executing the transaction.
The default return value is false for this callback.
27.2.7.3 Return Values
None.
27.2.7.4 Error Codes
The following table lists the error codes along with its corresponding error messages:
Error
Code
Error Message
1 UNKNOWN_
ERR
Description
The statement failed for database reasons not covered by any other error code.
2 DATABASE_
ERR
3 TOO_LARGE_
ERR
The operation failed because the actual database version was not what it should be. For example, a statement found that the actual database version no longer matched the expected version of the
Database
or
DatabaseSync
object, or the
Database.changeVersion()
or
DatabaseSync.changeVersion()
methods were passed a version that doesn't match the actual database version.
The statement failed because the data returned from the database was too large. The SQL "LIMIT" modifier might be useful to reduce the size of the result set.
© 2015 by Kony, Inc. All rights reserved 548 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
Error
Code
Error Message
4 QUOTA_ERR
Description
The statement failed because there was not enough remaining storage space, or the storage quota was reached and the user declined to give more space to the database.
5
6
SYNTAX_ERR
CONSTRAINT_
ERR
The statement failed because of a syntax error, or the number of arguments did not match the number of ? placeholders in the statement, or the statement tried to use a statement that is not allowed, such as BEGIN, COMMIT, or ROLLBACK, or the statement tried to use a verb that could modify the database but the transaction was read-only.
An INSERT, UPDATE, or REPLACE statement failed due to a constraint failure. For example, because a row was being inserted and the value given for the primary key column duplicated the value of an existing row.
7 TIMEOUT_ERR A lock for the transaction could not be obtained in a reasonable time.
For more information, refer SQL Error Codes
27.2.8 Platform Availability
Available on all platforms* except for SPA in Windows Phone 7.5 and windows Phone 8 browsers, for desktop IE8, IE9, IE10 browsers.*Dummy Implementation on Mobile Web.
27.2.8.1 JavaScript Example
//The below function specifies the callback function that must be executed when the execution of the SQL statement is a success function sql_success(transactionId, resultset)
{
//logic to process the resultset
© 2015 by Kony, Inc. All rights reserved 549 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
}
//The below function specifies the callback function that must be executed when the execution of the SQL statement is a failure.
{ function sql_errorCallBack(err) alert("Error processing sql statement error code=" + err["code"]);
}
//The below function specifies the callback function that contains the transactions also invokes executeSql
{ function myTransactionCallback(dbId)
//SQLTransaction contains implementation of executeSql method
// invokekony.db.executesql method for sql trasaction var sqlStatement = "SELECT * FROM employee"; kony.db.executeSql(transactionID, sqlStatement, null, sql_success, sql_errorCallBack);
}
27.2.9 kony.db.sqlResultsetRowItem
This API returns the row available at the specified index. If there is no such row, then the API returns null for JavaScript.
Important: The table names and column names are case sensitive.
27.2.9.1 Signature
JavaScript : kony.db.sqlResultsetRowItem(
,
)
© 2015 by Kony, Inc. All rights reserved 550 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.2.9.2 Parameters transactionID [String] - Mandatory
Specifies the unique ID of the transaction
SQLResultSet [Array of JS Objects] - Mandatory
Specifies the name of the SQL result set index [Number] - Mandatory
Specifies the index from which the row is to be retrieved
27.2.9.3 Return Values rowitem [Array of Objects]
Returns the row item at the specified index null/nil
Returns null/nil if there is no row available at the specified index
27.2.10 Platform Availability
Available on all platforms* except for SPA in Windows Phone 7.5 and windows Phone 8 browsers, for desktop IE8, IE9, IE10 browsers.*Dummy Implementation on Mobile Web.
27.2.10.1 JavaScript Example
//The below function specifies the callback function that must be executed when the execution of the SQL statement is a success also invokes sqlResultsetRowItem.
function sql_success(transactionId, resultset)
{
//logic to process the resultset for (var i=0; i<resultset.length;i++)
© 2015 by Kony, Inc. All rights reserved 551 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
{ var rowItem =kony.db.sqlResultsetRowItem
(transactionId,resultset,i); alert("empID:" + rowItem["empID"] + " empName:" + rowItem
["empName"] + " depID:" + rowItem["depName"]);
}
}
//The below function specifies the callback function that must be executed when the execution of the SQL statement is a failure.
{ function sql_errorCallBack(err) alert("Error processing sql statement error code=" + err["code"]);
}
27.2.11 kony.db.changeVersion
The changeVersion method allows scripts to automatically verify the version number and change it at the same time during a schema update. This method creates an SQLTransactionSync object
(executeSQL) for a read/write transaction. The database's actual version changes to newVersion only if the first argument (oldVersion) exactly matches the database's actual version, otherwise throws a
SQLException.
When you invoke this API, it returns immediately and asynchronously reads the transaction.
27.2.11.1 Signature
JavaScript
: kony.db.changeVersion( dbaseObjectId
,
SQLTransactionCallback ,SQLTransactionErrorCallback, SQLTransactionVoidCallback )
27.2.11.2 Parameters dbaseObjectId [String] - Mandatory
Specifies the unique ID of the database
© 2015 by Kony, Inc. All rights reserved 552 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
oldVersion [String] - Mandatory
Specifies the older version of the database.
newVersion [String] - Mandatory
Specifies the newer version of the database.
SQLTransactionCallback [Function] - Mandatory
Specifies the callback function that contains the transactions.
For example, function callback(dbId)
{
//SQLTransaction contains implementation of executeSql method
// invoke database.executesql method for sql trasaction
};
SQLTransactionErrorCallback [Function] - Optional
Specifies the callback that must be executed if there is an error in executing the transaction. This callback function is used to roll back the updates to the database.
For example function errorCallback(SQLError)
{
//code
}
SQLVoidCallback [Function] - Optional
Specifies the callback that must be executed if the transaction is successful.
For example
© 2015 by Kony, Inc. All rights reserved 553 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
function successCallback()
{
//code
}
27.2.11.3 Return Values
None.
27.2.11.4 Example kony.db.changeVersion
("1.0","1.1",transactioCall,errorCall,sucessCall); function transactioCall ()
{
//respective code
} function sucessCall()
{
//respective code
} function errorCall()
{
//respective code
}
27.2.12 Platform Availability
Available on all platforms* except BlackBerry 10 and SPA in Windows Phone 7.5 and windows Phone
8 browsers, for desktop IE8, IE9, IE10 browsers. *Dummy implementation on Mobile Web.
© 2015 by Kony, Inc. All rights reserved 554 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.3 Deprecated APIs
The DataStore Library is deprecated from 5.0 onwards.
27.3.1 Data Store Library
A data store is a storage area on the mobile device that is capable of holding persistent data. The data store is available on the mobile device at a location that is dependent on the underlying platform. The data store is not directly exposed to the users.
The underlying platform of the mobile device maintains the integrity of the persistent data stored in the following scenarios when: l the application accesses the data l the device reboots l the battery is changed l the application upgrades: o
Native Clients - data stored earlier is not deleted when an application upgrades. On some of the J2ME phones, the user is prompted with an option to delete the data during the application upgrade process. If the end user chooses the delete option then the data will be lost even on application upgrade.
o
Mobile Web when storage mode is cookie - the data is lost when you delete the cookies on the client browser.
o Mobile Web when storage mode is cache - the data is lost every time you restart the application server.
o
Mobile Web when storage mode is session- the data is lost as soon as the server-side session is terminated/expired.
The actual storage used to store this data depends upon the underlying Operating System:
© 2015 by Kony, Inc. All rights reserved 555 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
Operating
System iPhone
Storage Space
No
Accessible to other applications
Android/Android
Tablet
BlackBerry
J2ME
Windows 6x
Within a file in the application sandbox. The storage area is unique to the application.
Within a file in the application sandbox. The storage area is unique to the application.
RMS (Record Management Store)
RMS (Record Management Store)
Within a file
No
No
No
Yes
Windows
Phone
Symbian
Within a file in the application sandbox. The storage area is unique to the application.
Within a file in the application sandbox. The storage area is unique to the application.
Browser Cookie
No
No
Mobile Web
(mode set as cookie)
Mobile Web
(mode set as cache)
Application Context
No
No (but shared across all the users for the same application)
Mobile Web
(mode set as session)
HTTP Session No
The previous stored data is lost (permanently) in the following cases when : l the application is deleted from the device l the kony.ds.delete API is used to delete the data.
© 2015 by Kony, Inc. All rights reserved 556 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
Kony provides APIs that allow the application to: l save data on the data store l read data from the data store l delete data on the data store.
27.3.2 kony.ds.save
This API allows you to save the given data using the specified name identifier in the data store of the mobile device. In case of Mobile Web applications, you have the option to specify where to store the data (cache/session/cookie).
27.3.2.1 Use Cases
You can use this API to store data on the mobile device that you may require even after quitting the application.
27.3.2.2 Signature
JavaScript: kony.ds.save(
,
27.3.2.3 Parameters inputtable [Array] - Mandatory
Specifies the table that needs to be saved (array of values) name [String] - Mandatory
Specifies the name identifier for the table. The data is stored on the data store with this name identifier. You must use this identifier if you want to retrieve data from the data store.
metainfo [Table] - Optional
Specifies a table with key-value pairs. These key-value pairs are useful for Mobile Web and indicate where to store the data. You have an option to store the data in the user session or cache or create a cookie to be placed on the device.
© 2015 by Kony, Inc. All rights reserved 557 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
Important: The following points are applicable only to metainfo [Table] parameter: l
The parameter is mandatory for Server Side Mobile Web.
l
Example code to use: kony.ds.save(["John","Joe","Jack"],"friends",
{dsmode:"session"}) secure means that the data stored on the device store is stored using a secure mode.
Note: secure is applicable only on Mobile Web and must be used in conjunction with dsmode="cookie". For example, {dsmode="cookie", secure="true"}.
You should provide a key value in the metainfo as key:
"dsmode" value:"cache/session/cookie" l cache: Data is stored in the application context and shared across all users of the Web
Application l session: Data is stored in the HTTP session created for a particular user l cookie: Data is stored in client browser's cookie store.
Based on the mode you specify here, the availability of the data after you quit the application varies.
For example, dsmode="session".
27.3.2.4 Return Values
None.
27.3.2.5 Error Codes
The following error codes are returned:
© 2015 by Kony, Inc. All rights reserved 558 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
l
700 Unknown error l
701 Invalid parameters specified l
702 Invalid parameter type.
l
703 Invalid parameter type. A non-string type specified as input l
704 Unknown error l
705 Invalid parameters l
706 Invalid parameter type. A non-string type specified as the name of the datastore
27.3.2.6 Implementation Details
If you save some other data on the data store with the same name identifier used earlier, data is overridden.
27.3.2.7 API Usage
We recommend you not to store save sensitive data like passwords, account numbers, and so on using this API.
27.3.3 Platform Availability
Available on all platforms.
27.3.4 kony.ds.read
This API provides you an ability to read the data stored on the data store of the mobile device using the given name identifier. A reference to the data table is returned.
27.3.4.1 Use Cases
You can use this API when you want to:
© 2015 by Kony, Inc. All rights reserved 559 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
l fetch the data stored on the mobile device and re-use it.
l know the data associated with a name identifier before you delete it.
27.3.4.2 Signature
JavaScript: kony.ds.read(
27.3.4.3 Parameters name [String] - Mandatory
Specifies the unique name identifier that represents the data on the data store
27.3.4.4 Return Values
Reference [String]
A reference to the table is returned nil [nil] nil is returned if no record is found
27.3.4.5 Error Codes
The following error codes are returned: l
704 Unknown error l
705 Invalid parameters l
706 Invalid parameter type. A non-string type specified as the name of the datastore
27.3.4.6 Implementation Details
If you use secure=true, while saving the data in ds.save, then the ds.read API fetches the correct values only if you are invoking the API on a form enabled for Secure Submit. Else, it will return nil.
© 2015 by Kony, Inc. All rights reserved 560 of 848
27. Offline Data Access APIs Kony Studio API Developer's Guide
Version 5.0
27.3.5 Platform Availability
Available on all platforms.
27.3.6 kony.ds.remove
This API allows you to delete the data stored on the data store that corresponds to a specific name identifier.
27.3.6.1 Signature
JavaScript: kony.ds.remove (
)
27.3.6.2 Parameters name [String] - Mandatory
Specifies the name identifier using which the table was saved.
27.3.6.3 Return Values status [Boolean] true - if the table is deleted successfully false - if the table is not deleted, or if no datastore exists with the key specified
27.3.7 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 561 of 848
28. Operating System APIs
28. Operating System APIs
This chapter explains the APIs available in the OS namespace.
l
l
l
l
l
l
l
kony.os.startSecureTransaction
l
l
l
kony.os.hasAccelerometerSupport
l
l
kony.os.deviceInfo().httpheaders
l
l
l
l
l kony.os.hasCameraSupport
l
© 2015 by Kony, Inc. All rights reserved
Kony Studio API Developer's Guide
Version 5.0
562 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
l
l
kony.os.getDeviceCurrentOrientation
l
l
Deprecated APIs
28.1 kony.os.toNumber
This API converts the argument to a number. If the argument is already a number or a string convertible to a number, then the API returns this number; otherwise, it returns null for JavaScript.
28.1.1 Signature
JavaScript: kony.os.toNumber(
28.1.2 Input Parameters argument [String or Number] - Mandatory
The argument that must be converted to a number.
28.1.3 Return Values
Converted Number [Number]
The input string or number that has been converted to a number and returned.
null/nil
The argument cannot be converted to a number.
28.1.4 Rules and Restrictions
The input parameter must be a number or a string.
© 2015 by Kony, Inc. All rights reserved 563 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.1.5 Exceptions
An error is thrown if input is invalid or does not follow the expected structure.
102 - Invalid input error
28.1.6 Platform Availability
Available on all platforms.
28.1.7 JavaScript Example
In this example, only the string which can be converted to a number returns a number otherwise it returns n.
kony.os.toNumber (ms34rd);
//returns null as the string passed cannot be converted to a number kony.os.toNumber ("58");
//returns 58 as the string could be converted to a number
28.2 kony.os.toCurrency
This API allows you to convert the given number to represent currency. At present, only USA currency is supported.
© 2015 by Kony, Inc. All rights reserved 564 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.2.1 Signature
JavaScript : kony.os.toCurrency(
)
28.2.2 Input Parameters number[Number] - Mandatory
Specifies the number that must be converted to represent currency.
If the input number is a negative number, the negative number is treated as a positive number (this is because a currency does not have any negative symbol) and the converted value is returned.
28.2.3 Return Values
Currency [String]
A string with the number formatted as currency.If the input string has decimal points, the return value is truncated till two decimal points.
28.2.4 Exceptions
An error is thrown if input is invalid or does not follow the expected structure.
102 - Invalid input error
28.2.5 Platform Availability
Available on all platforms.
28.2.6 JavaScript Example
Perform a kony.os.toCurrency operation on the number "10000".
© 2015 by Kony, Inc. All rights reserved 565 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
var tocurrency = kony.os.toCurrency(10000); kony.print(tocurrency);
//prints $ 10,000
28.3 kony.os.freeMemory
This API provides the ability to query and fetch the system-wide memory available on the mobile device for allocation.
28.3.1 Use Case
You can use this API to: l
Check the amount of free memory on the mobile device before you go ahead with installation of any software or applications.
l
Find out the free memory on the mobile device, clear unwanted objects, and thus improve the performance of the application.
28.3.2 Signature
JavaScript: kony.os.freeMemory()
28.3.3 Input Parameters
None
28.3.4 Return Values
Free memory[Number]
The available memory for allocation is returned. The returned memory always indicates the number of bytes available.
© 2015 by Kony, Inc. All rights reserved 566 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.3.5 Platform Availability
Available on all platforms* except Windows Phone 8, Windows Phone 8.1, Windows Tablet 8, and
Windows 7 / Kiosk. *Dummy implementation on Server Side Mobile Web, SPA, and DesktopWeb and returns a dummy value.
28.3.6 JavaScript Example
In the following example, kony.os.freeMemory returns the freememory available for allocation.
var freememory = kony.os.freeMemory(); kony.print(freememory);
//After the kony.os.freeMemory operation, the memory available for allocation is printed.
//For example, 1070404 (indicates that 1046 KB of memory is available for allocation)
28.4 kony.os.userAgent
This API returns a unique identifier of the mobile device that is extracted from the useragent. This unique ID represents the device model and the manufacturer. Kony Application Server uses this information to adjust the content to match the screen resolution of the device. For example, the content is adjusted to fit the screen width, height, or memory required etc.
The useragent contains the following information: l device model l manufacturer l
OS version l browser version l
Java capabilities, and so on.
© 2015 by Kony, Inc. All rights reserved 567 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
The following are a few sample useragents:
Useragent
Nokia6230i/2.0 (03.25) Profile/MIDP-2.0
Configuration/CLDC-1.1
SonyEricssonT610/R501 Profile/MIDP-1.0
Configuration/CLDC-1.0
BlackBerry9500/4.7 Profile/MIDP-2.0
Configuration/
BlackBerry9700/5.0 Profile/MIDP-2.1
Configuration/
Mozilla/4.0 (compatible; MSIE 7.0; Windows
Phone OS 7.0)
OPWV-SDK/62 UP.Browser/6.2.2.1.208 (GUI)
MMP/2.0
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
5.0)
Description
Nokia 6230i model mobile device
SonyEricsson
T610 model mobile device
BlackBerry
9500 mobile device
BlackBerry
9700 mobile device
Windows
Phone mobile device
Openwave
Mobile
Browser 6.2.2
Microsoft
Internet
Explorer 6
© 2015 by Kony, Inc. All rights reserved 568 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
Useragent
Mozilla/5.0 (Windows; U; Windows NT 5.0; en-
US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7
Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like
Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314
Safari/531.21.10
Device Model. For example, Galaxy Nexus.
Description
Mozilla
Firefox 1.0.7
running on
Windows
2000 iPad
Android and
Android
Tablet.
28.4.1 Use Case
You can use this API in the following scenarios when you need to identify: l
The model of a specific mobile device.
l
The mobile devices based on the manufacturer.
l
If the device is a web browser, mobile device, micro browser, or a computer.
28.4.2 Signature
Javascript: kony.os.userAgent()
28.4.3 Input Parameters
None
© 2015 by Kony, Inc. All rights reserved 569 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.4.4 Return Values
Device ID [String]
Any of the available Device ID is returned in the order Device Model, OS Version, Browser
Version, Java Capabilities, and Manufacturer.
Note: l
For Android and Android Tablet, device model is returned as an user agent.
l
For iOS Devices, user agent is returned as a string.
28.4.5 Platform Availability
Available on all platforms except Windows 7.
28.4.6 JavaScript Example
In the following example, the uid returned by the kony.os.userAgent is displayed in the alert.
var devID =kony.os.userAgent(); alert("User Agent return value is::"+devID);
28.5 kony.os.addHiddenField
This API helps the developers to pass dynamic values when the form needs to be submitted to external sites.
28.5.1 Signature
JavaScript : kony.os.addHiddenField(
)
© 2015 by Kony, Inc. All rights reserved 570 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.5.2 Input Parameters key [String] - Mandatory
Specifies the key of the hidden field that you would like to add.
value [String] - Mandatory
Specifies the value that corresponds to the specified key in the hidden field.
private [String] - Optional
Specifies if the hidden field can be read using the
kony.os.readHiddenField
API. The expected values for this field are either "private" or "public". The default value of this field id
"public".
Note: Only when this value is specified, you can read the hidden value through
kony.os.readHiddenField
API.
28.5.3 Return Values
None.
28.5.4 Platform Availability
Available only on Mobile Web.
28.5.5 JavaScript Example function addHiddenField()
{ kony.os.addHiddenField("myhiddenfield","myvalue","private")
// private value is specified and hence this hiddenfield can be read through the kony.os.readHiddenField API kony.os.addHiddenField("myhiddenfield1","myvalue")
© 2015 by Kony, Inc. All rights reserved 571 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
// As private value is not specified and hence this hiddenfield cannot be read through the kony.os.readHiddenField API
}
28.6 kony.os.readHiddenField
This API allows the developers to read the hidden fields added by the
os.addHiddenField
API.
28.6.1 Signature
JavaScript : kony.os.readHiddenField(
28.6.2 Input Parameters key [String] - Mandatory
Specifies the key of the hidden field that you would like to read.
28.6.3 Return Values value[String]
Returns the value that corresponds to the specified key.
nil nil is returned if there is no value assigned to the corresponding key.
28.6.4 Platform Availability
Available only on Mobile Web.
© 2015 by Kony, Inc. All rights reserved 572 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.6.5 JavaScript Example function readHiddenField()
{ kony.os.readHiddenField("myhiddenfield")
// Reads the value that corresponds to the myhiddenfield key, i.e., myvalue
}
28.7 kony.os.startSecureTransaction
This API can be invoked on an event of a widget. When this API is invoked it makes all the data and subsequent transactions of the application secure. For example, the login page of an application has the following: user name field, password field, and a button. On the onclick event of the button, the user is verified and navigated to pages with sensitive information. If you want to prevent cross site request forgery or double submissions, you can invoke this API ensuring that all the subsequent transactions are secure.
28.7.1 Signature
JavaScript : kony.os.startSecureTransaction(callback, scope)
28.7.2 Input Parameters callback [Function] - Mandatory
If there are instances where cross site request forgery is attempted, this parameter should comprise a session/request expiry function.
scope [Integer] - Mandatory
Specifies whether this API will be valid per request or per session of the application. The possible values are as follows: l
0 - Request Scope: The data in the application is secure only on a per request basis.
© 2015 by Kony, Inc. All rights reserved 573 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
Note: If you press the browser back button on BJS, the token is rendered invalid on the browser back request.
l
1 - Session Scope. The data is secure for an entire user session. This is the default value.
28.7.3 Return Values
This API has no return values.
28.7.4 Implementation Details
Whenever os.startsecuretransaction is invoked, a krfid for that session or request is generated internally as a hidden field. The krfid is validated for each transaction/request. If the krfid is invalid, the callback function of os.startsecuretransaction API is invoked, and the request processing fails or a message appears stating that the session has expired.
28.7.5 Platform Availability
Available only on Mobile Web.
28.7.6 JavaScript Example function callback()
{
} kony.os.startSecureTransaction(callback, 1)
28.8 kony.os.endSecureTransaction
This API can be invoked on an event of a widget. This API should be invoked on forms of the application where user validation is not required or cross site request forgery is not a concern.
© 2015 by Kony, Inc. All rights reserved 574 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.8.1 Signature
JavaScript: .kony.os.endSecureTransaction()
28.8.2 Input Parameters
None
28.8.3 Return Values
None
28.8.4 Platform Availability
Available only on Mobile Web.
28.8.5 JavaScript Example kony.os.endSecureTransaction();
28.9 kony.os.getAppContext
This API allows the developers to get information about the mode in which the application is launched.
28.9.1 Signature
JavaScript: kony.os.getAppContext()
28.9.2 Input Parameters
None
© 2015 by Kony, Inc. All rights reserved 575 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.9.3 Return Values contextDetails[Object]
Returns an object with key-value pairs: l
launchmode:0
indicates that the application is launched in normal mode.
l
launchmode:1
indicates that the application is launched in full screen mode.
28.9.4 Platform Availability
Applicable only on Mobile Web.
28.9.5 JavaScript Example function getAppContext()
{ var mycontext=kony.os.getAppContext(); kony.print(mycontext) //prints {launchmode=0} if the application was launched in normal mode ,prints {launchmode=1} if the application was launched in full screen mode
}
28.10 kony.os.hasAccelerometerSupport
This API returns whether accelerometer is supported on a device.
28.10.1 Signature
JavaScript : kony.os.hasAccelerometerSupport()
© 2015 by Kony, Inc. All rights reserved 576 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.10.2 Input Parameters
None.
28.10.3 Return Values value[Boolean]
Returns whether accelerometer is supported on a device.
28.10.4 Platform Availability
Applicable only on iPhone, Android, BlackBerry, BlackBerry 10, and Windows platforms.
28.10.5 JavaScript Example kony.print(kony.os.hasAccelerometerSupport());
//prints true if device has accelerometer support
28.11 kony.os.deviceInfo
This API allows the developers to get information about the device in which the application is launched.
You can view a video on using Device Info API at: http://docs.kony.com/video_ tutorials/default.htm#Device_Info.htm%3FTocPath%3D_____9 .
28.11.1 Signature
JavaScript : kony.os.deviceInfo()
28.11.2 Input Parameters
None
© 2015 by Kony, Inc. All rights reserved 577 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.11.3 Return Values values[Object]
Returns a hash table in JavaScript and with the following keys: l
The following return values are available on all platforms: o screenWidth: Specifies the screen width of the device by considering the device orientation at the time of query. The returned value is in device independent pixels
(Dp). This attribute is supported in iOS, Android, Windows, and SPA platforms.
o screenHeight: Specifies the screen height of the device by considering the device orientation at the time of query. The returned value is in device independent pixels
(Dp). This attribute is supported in iOS, Android, Windows, and SPA platforms.
Note: The values returned by the screenWidth and screenHeight properties describe the screen space where widgets can be placed using layout parameters. This includes app menu height, headers, and footers, but excludes the screen space occupied by status bar.
o deviceid: The unique device identifier. The following are the device IDs returned by the platforms: l
BlackBerry: PIN (Personal Identification Number) l
Windows Phone: Device Unique ID (20 bytes in length), a unique hash for the device. This value is constant across all applications and does not change even if the phone is updated with a new version of the operating system.
l
For iOS 7 and above, this API returns a fixed value 02:00:00:00:00:00 l
Android: Returns the unique device ID, for example, the IMEI for GSM and the
MEID or ESN for CDMA phones. Return null if device ID is not available. Set the following permission in the Android Manifest file: READ_PHONE_STATE to view the device ID. For more information,
© 2015 by Kony, Inc. All rights reserved 578 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
http://developer.android.com/reference/android/telephony/TelephonyManager.html
#getDeviceId().
o SERIAL_NO: If Device ID is not present in any of the devices such as tablets, SERIAL Number of the device is returned for the devices with
Android version greater than 2.2. A hardware serial number, if available.
Alphanumeric only, case-insensitive. For more information refer, http://developer.android.com/reference/android/os/Build.html#SERIAL.
o
ANDROID_ID: If both are not present then ANDROID_ID is returned as a device-id. A 64-bit number (as a hex string) that is randomly generated on the device's first boot and should remain constant for the lifetime of the device.
(The value may change if a factory reset is performed on the device.) For more information refer, http://developer.android.com/reference/android/provider/Settings.Secure.ht
ml#ANDROID_ID o customdeviceid: l
For iPhone, a custom device identifier is returned. It internally uses the MAC address of the iOS device and the Bundle Identifier of the application to generate this.
l
For iOS 7 and above, this property returns a fixed value 02:00:00:00:00:00.
Note: The new iPhone retina display contains double the pixels (640) as that of the standard display (320), but iOS treats the resolution as a standard display for measurement and screen output. Websites built for non-retina versions will look very tiny and zoomed out.
o identifierForVendor: An alphanumeric string that uniquely identifies a device to the app’s vendor. The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps on the same device that come from different vendors, and for apps on different devices regardless of vendor.
© 2015 by Kony, Inc. All rights reserved 579 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
If (iOS version is less than 6.0)
{ kony.os.deviceInfo().customdeviceid
} else
{ kony.os.deviceInfo().identifierForVendor
}
Important: This property is only applicable for iOS 6 and above.
o name: Specifies the name of the platform as iPhone, iPad, blackberry,Windows
Phone, thin client (The name thin client is used for SPA/ Desktop Web / Mobile
Web), Android, and J2ME.
o model: Specifies the model number of the platform. For example 8900 etc. Not applicable for Mobile Web.
o version: Specifies the version of the platform in a string format Not applicable for
Mobile Web.
o deviceWidth: The device width in pixels Valid only on Native Apps channels and not applicable for Mobile Web.
o deviceHeight: The device height in pixels Valid only on Native Apps channels and not applicable for Mobile Web.
o channel for all platforms.
l
API Level: Provides the Android API Level based on the SDK Version.The following are the mappings between Android SDK Version and the API Level that is returned: o SDK 1.5 3 o
SDK 1.6 4 o
SDK 2.1 7
© 2015 by Kony, Inc. All rights reserved 580 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
o
SDK 2.2 8 o
SDK 2.3 9 o SDK 2.3.3 10 o
SDK 3.0 11
Note: The API Level is returned only for Android.
l
For Mobile Web, the following values are returned: o type [String] - Specifies if the Mobile Web is Advanced or Basic.
o category [String] - Provides the Mobile Web category.
For Advanced Mobile Web, the return value can be iPhone, Android, or Palm.
o tcsession [String] - Provides the session ID of the current user.
o imagecat [String] - Image category based on the device width available in Kony Device
Database or returns a default value.
28.11.4 Platform Availability
Available on all platforms.
28.11.5 JavaScript Example var deviceInfo=kony.os.deviceInfo(); alert(deviceInfo); for (var key in deviceInfo)
{ if (deviceInfo.hasOwnProperty(key))
{ alert(key+":"+deviceInfo[key]);
© 2015 by Kony, Inc. All rights reserved 581 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
}
}
28.12 kony.os.deviceInfo().httpheaders
This API returns the http headers configured in the HTTP request object.
28.12.1 Signature
JavaScript : kony.os.deviceInfo().httpheaders
28.12.2 Input Parameters
None.
28.12.3 Return Values value[Object]
A hash table of httpheaders with keys as the header name and values as the header value.
28.12.4 Platform Availability
Available only on SPA.
28.12.5 JavaScript Example kony.print(kony.os.deviceInfo().httpheaders);
//prints the array of http headers
© 2015 by Kony, Inc. All rights reserved 582 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.13 kony.os.hasGPSSupport
This API returns whether GPS is supported on a device.
28.13.1 Signature
JavaScript : kony.os.hasGPSSupport()
28.13.2 Input Parameters
None.
28.13.3 Return Values value[Boolean] true: the platform supports GPS.
false: the platform does not support GPS.
28.13.4 Platform Availability
Available on all platforms except Mobile Web and Windows 7 / Kiosk.
28.13.5 JavaScript Example kony.print(kony.os.hasGPSSupport());
//prints true if device has GPS support
28.14 kony.os.hasCameraSupport
This API returns whether Camera is supported on a device.
© 2015 by Kony, Inc. All rights reserved 583 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.14.1 Signature
JavaScript : kony.os.hasCameraSupport()
28.14.2 Input Parameters
None.
28.14.3 Return Values value[Boolean] true: the platform supports Camera false: the platform does not support Camera
28.14.4 Platform Availability
Available on all platforms* except Mobile Web and Windows 7 / Kiosk. *Dummy implementation for
SPA and Desktop Web that always returns False.
28.14.5 JavaScript Example kony.print(kony.os.hasCameraSupport());
//prints true if device has camera support
28.15 kony.os.hasTouchSupport
This API returns whether Touch is supported on a device.
28.15.1 Signature
JavaScript : kony.os.hasTouchSupport()
© 2015 by Kony, Inc. All rights reserved 584 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.15.2 Input Parameters
None.
28.15.3 Return Values value[Boolean] true: the platform supports touch.
false: the platform does not support touch.
28.15.4 Platform Availability
Available on all platforms except Mobile Web and Desktop Web.
28.15.5 JavaScript Example kony.print(kony.os.hasTouchSupport());
//prints true if device is a touch device
28.16 kony.os.hasOrientationSupport
This API returns whether Orientation is supported on a device.
You can view a video on using Display Orientation at: http://docs.kony.com/video_ tutorials/default.htm#DisplayOrientation.htm%3FTocPath%3D_____12 .
28.16.1 Signature
JavaScript: kony.os.hasOrientationSupport()
28.16.2 Input Parameters
None.
© 2015 by Kony, Inc. All rights reserved 585 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.16.3 Return Values value[Boolean] true: the platform supports orientation.
false: the platform does not support orientation.
28.16.4 Platform Availability
Available on all platforms except Mobile Web.
28.16.5 JavaScript Example var orientation = kony.os.getDeviceCurrentOrientation(); if(orientation == constants.DEVICE_ORIENTATION_PORTRAIT)
{ alert("PORTRAIT");
} else if(orientation == constants.DEVICE_ORIENTATION_LANDSCAPE)
{ alert("LANDSCAPE");
} else
{ alert("UNKNOWN");
}
28.17 kony.os.getDeviceCurrentOrientation
This API returns the current orientation of the device. The possible values are portrait or landscape.
© 2015 by Kony, Inc. All rights reserved 586 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.17.1 Signature
JavaScript : kony.os.getDeviceCurrentOrientation()
28.17.2 Input Parameters
None
28.17.3 Return Values
This API returns whether the device orientation is landscape or portrait.
l constants.DEVICE_ORIENTATION_PORTRAIT
l constants.DEVICE_ORIENTATION_LANDSCAPE
28.17.4 Platform Availability
Available on iPhone, iPad, Windows 8, Android, BlackBerry, BlackBerry 10, Windows 7 / Kiosk, and
Desktop Web ( Always returns DEVICE_ORIENTATION_PORTRAIT in Desktop Web Channel)
28.17.5 JavaScript Example kony.os.getDeviceCurrentOrientation(); Returns the device orientation
28.18 kony.os.addMetaTag
This API adds a meta tag in html header. This API result will effect only on header reload.
28.18.1 Signature
JavaScript : kony.os.addMetaTag (key, value)
© 2015 by Kony, Inc. All rights reserved 587 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.18.2 Input Parameters key [String] - Mandatory
Adds a meta tag in html header value [Object] - Mandatory
Adds meta tag attributes in the html header as key value pairs.
28.18.3 Return Values
This API has no return values.
28.18.4 Platform Availability
Applicable only on Mobile Web.
28.18.5 JavaScript Example kony.os.addMetaTag("test2", { "http-equiv":"refresh","content":"30"
});
28.19 kony.os.removeMetaTag
This API removes a specific meta tag from a html header. This API result will effect only on header reload.
28.19.1 Signature
JavaScript : kony.os.removeMetaTag (key)
© 2015 by Kony, Inc. All rights reserved 588 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.19.2 Input Parameters key [String] - Mandatory
Removes a meta tag with the specific key in html header.
28.19.3 Return Values
This API has no return values.
28.19.4 Platform Availability
Applicable only on Mobile Web.
28.19.5 JavaScript Example kony.os.removeMetaTag("test1")
28.20 kony.os.removeAllMetaTags
This API removes all the user defined meta tags from a html header. This API result will effect only on header reload.
28.20.1 Signature
JavaScript : kony.os.removeAllMetaTags ()
28.20.2 Input Parameters
None.
28.20.3 Return Values
This API has no return values.
© 2015 by Kony, Inc. All rights reserved 589 of 848
28. Operating System APIs Kony Studio API Developer's Guide
Version 5.0
28.20.4 Platform Availability
Applicable only on Mobile Web.
28.20.5 JavaScript Example kony.os.removeAllMetaTags()
28.21 kony.os.print
When invoked without any parameter, this API prints the entire form that is currently in view.
28.21.1 Signature
JavaScript : kony.os.print(containerID)
28.21.2 Input Parameters containerID [Number] - Optional
The containerID can be a ID of any container widget that can be directly referenced from a form.
Note: l
If the user is typing in a text box, the typed content will not be printed.
l
Print API can be used only after the target Form, Popup or Datagrid is rendered on the browser.
l
Print API cannot be used in pre-show, post-show, pre and post app init or any other functionality that is run before the target Form, Popup, or Datagrid is fully rendered.
l
When printing the form with widgets like ScrollBox, Image Strip, the print functionality prints only those widgets that are in the view or potentially occupy the available print space in portrait or landscape views.
© 2015 by Kony, Inc. All rights reserved 590 of 848
28. Operating System APIs
28.21.3 Return Values
None.
28.21.4 Platform Availability
Applicable only on Desktop Web.
28.21.5 JavaScript Example kony.os.print()
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 591 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
29. Phone APIs
The APIs in this chapter helps you to access default applications in the underlying platform of the mobile device and perform operations. The following are a few operations that you can perform using the APIs in this library: l
Send text messages (SMS).
l
Call a specified number.
l
Capture location details (GPS or Non-GPS).
l
Add/find/delete contacts (from the underlying native Address Book.
l
Add/find/delete events (from the native device calendar).
l
Access the maps application of the underlying platform.
l
Access the media from the media gallery of the device or from an external URL.
The Phone API library comprises the following: l
l
l
l
l
l
kony.phone.removeCalendarEvent
l
l
l
© 2015 by Kony, Inc. All rights reserved 592 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
l
l
You can view a video on using Device Address Book at: http://docs.kony.com/video_ tutorials/default.htm#DeviceContacts.htm%3FTocPath%3D_____10 .
29.1 kony.phone.sendSMS
This API provides access to the Messaging service of the underlying platform. You can send a text message to a specified number. This API accesses the messaging application of the underlying platform and uses that application to send text message to the specified number.
Important: You can send only text messages and multimedia messages are not supported.
Note: When you send messages using this API, the charges as imposed by the Service Provider are applicable. On iPhone this API opens the Messages application with a prepopulated text and number.
29.1.1 Use Case
You can use this API to send messages to other numbers without leaving the application.
29.1.2 Signature
JavaScript: kony.phone.sendSMS(
,
)
29.1.3 Input Parameters phonenumber [String] - Mandatory
Number to which the SMS must be sent.
text [String] - Mandatory
Content of the SMS.
© 2015 by Kony, Inc. All rights reserved 593 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
29.1.4 Return Values
None
29.1.5 Exceptions
PhoneError
The following error codes are defined for Phone APIs l
2100 - Unable to send the Message.
l
2101 - Insufficient Permissions.
29.1.6 Implementation Details
When you send messages using this API, the messaging application of the underlying platform is used to send the message with the number and text you specified i.e., the phone number and the message are pre-populated in the messaging application.
29.1.7 Platform Availability
Available on all platforms except BlackBerry 10, Desktop Web,SPA, Mobile Web, Android Tablets, iPad, Kiosk.
29.1.8 JavaScript Example function sendSMS()
{ try
{ var phNo="123456789"; var msg= "hello world"; kony.phone.sendSMS(phNo,msg);
© 2015 by Kony, Inc. All rights reserved 594 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
} catch(err)
{ alert("error in sending sms:: "+err);
}
}
Note: This API allows you to send only text messages. It does not support multimedia messages.
29.2 kony.phone.dial
This API provides you with the ability to make a call to the specified telephone number.
Note: When you make calls using this API, the call charges as imposed by the Service Provider are applicable. This API is a dummy call on the iPhone simulator. You need to test this API on an iPhone device.
29.2.1 Use Case
You can use this API to make calls to other numbers without leaving the application.
29.2.2 Signature
JavaScript: kony.phone.dial(
)
29.2.3 Input Parameters number [String] - Mandatory
Number to which the call must be made.
© 2015 by Kony, Inc. All rights reserved 595 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
Note: Only numbers, +, - and space are treated as valid characters.
29.2.4 Return Values
None
29.2.5 Exceptions
PhoneError
The following error codes are defined for Phone APIs l
2101 - Insufficient Permissions
29.2.6 Implementation Details
When you make a call to the specified number using this API, the underlying OS is used to make the call.
29.2.7 Platform Availability
Not supported on Windows Kiosk,Windows 8, iPad, Android Tablets, Desktop Web, and Mobile Web platforms. You can use the phone widget to achieve the same functionality on Mobile Web.
29.2.8 JavaScript Example function CallTheNumber()
{ try
{ var number="123456789"; kony.phone.dial(number);
}
© 2015 by Kony, Inc. All rights reserved 596 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
catch(err)
{ alert("error in dial:: "+err);
}
}
29.3 kony.phone.openMediaGallery
This API allows you to open the picture gallery of the mobile device and pick an existing picture.
29.3.1 Use Case
You can use this API to use any of the multimedia resources (image files, audio files, or video files) available in the device media gallery within your application.
For iPad, openMediaGallery will show the Photos/Videos in the native popover. The popover can be anchored to a widget. The widget to which the popup should be anchored will be provided as a third parameter to openMediaGallery API.
You can view a video on using iPad Popover at: http://docs.kony.com/video_ tutorials/default.htm#iPadPopOver.htm%3FTocPath%3D_____16 .
29.3.2 Signature
JavaScript: kony.phone.openMediaGallery(
)
29.3.3 Input Parameters onselectioncallback [Function] - Mandatory
This callback function is invoked when a media is selected.
© 2015 by Kony, Inc. All rights reserved 597 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
querycontext [Table] - Optional
Query context is an Object that can be populated with key-value pairs for fine tuning the media items for display (currently only one key "mimetype" supported to query the gallery items ). The possible values of the mimetype key can be image/*, video/*, audio/*.
widgetref [Widget Reference] - Optional
Applicable only on iPad. The widget to which the popup will be anchored to. For e.g.
formname.widgetname
29.3.4 Return Values
None
29.3.5 Exceptions
PhoneError
The following error codes are defined for Phone APIs l
2100 - Unable to send the Message l
2101 - Insufficient Permissions l
2102 - Cannot open mail, mail not configured l
2103 - Cannot open media gallery
29.3.6 Platform Availability
Supported on all platforms except BlackBerry 10, Mobile Web, Windows 8, SPA, Kiosk, and Desktop
Web.
29.3.7 JavaScript Example function openMediaGallery()
{
© 2015 by Kony, Inc. All rights reserved 598 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
function onselectioncallback(rawbytes)
{ querycontext); alert("in selection callback"); if (rawbytes == null)
{ alert("nothing selected"); return;
} alert("return status is "+returnStatus);
//(convert the rawbytes to base64 and can be assigned to a image widget or use base64 to upload) var base64 = convertToBase64(rawbytes); frmTest.imgone.base64 = base64;
//Assigning rawbytes directly to a image widget
/*formid.imageid.rawdata = rawbytes;*/
} var querycontext = {mimetype:"video/*"}; returnStatus = kony.phone.openMediaGallery(onselectioncallback,
} catch(err)
{ alert("error in openMediaGallery:: "+err);
}
} try
{
© 2015 by Kony, Inc. All rights reserved 599 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
29.4 kony.phone.openEmail
This API allows the application to launch the native email client with predefined email addresses, subject, body, and attachments.
29.4.1 Use Case
You can use this API to send emails without leaving the application.
29.4.2 Signature
JavaScript: kony.phone.openEmail(
,
,
bccrecipients , subject , messagebody
,
ismessagebodyhtml , attachments )
29.4.3 Input Parameters torecipients [Array of Strings] - Mandatory
List of email addresses to be included in the "to" list. For example,
"[email protected]","[email protected]" "[email protected]".
ccrecipients [Array of Strings] - Optional
List of email addresses to be included in the "cc" list. For example,
"[email protected]","[email protected]" "[email protected]".
bccrecipients [Array of Strings] - Optional
List of email addresses to be included in the "bcc" list. For example,
"[email protected]","[email protected]" "[email protected]".
subject [String]- Optional
Subject to be part of the email.
messagebody [String] -Optional
Body to be part of the email.
© 2015 by Kony, Inc. All rights reserved 600 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
ismessagebodyhtml [Boolean] - Optional l true: message body must be treated as HTML content l false: message body must not be treated as HTML content
Note: BlackBerry does not support HTML body. This is an underlying SDK limitation.
attachments [Array of Objects] - Optional
Each attachment is a Hash-table with the following key-value pairs: l mimetype [String] Standard mime types like image/png or image/jpg or image/* etc.
l attachment [Object] Rawbytes received from the camera, image widget, or openmediagallery api.
l filename (Optional) [String] name of the file to appear as attachment.
Note: l
In Android, filename property is not supported.The Android SDK does not provide any provision for giving file name in attachments while launching native email Application.
l
For Windows 8 applications, attachments cannot be added programmatically. This is a limitation from Microsoft.
29.4.4 Return Values
None
29.4.5 Exceptions
PhoneError
The following error codes are defined for Phone APIs
© 2015 by Kony, Inc. All rights reserved 601 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
l
2100 - Unable to send the Message l
2101 - Insufficient Permissions l
2102 - Cannot open mail, mail not configured l
2103 - Cannot open media gallery
29.4.6 Platform Availability
Available on all platforms except Server Side Mobile Web, SPA, Kiosk, and Desktop Web. For these platform you can launch the native email client by using Richtext widget with an href tag similar to the one shown below:
<a href="mailto:[email protected]?subject=Foo&body=Bar">Email Me</a>
29.4.7 Rules and Restrictions l
BlackBerry does not support HTML tags in the body.
l
Android does not support base64 string as attachments. You can attach only those files on disk that are accessible by the native Email app and that can be accessed by the app.For example,
Images from Gallery, Kony Camera captured image that is available on the disk with public access.
29.4.8 JavaScript Example function openEmail()
{ try
{ var to=["[email protected]"]; var cc=["[email protected]"]; var bcc = ["[email protected]"]; var sub = "Hello";
© 2015 by Kony, Inc. All rights reserved 602 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
} catch(err)
{ var msgbody = "Testing openEmail"; kony.phone.openEmail(to,cc,bcc,sub,msgbody,false,[]); alert("error in opening Email:: "+err);
}
}
29.5 kony.phone.addCalendarEvent
This API adds a new event to the device calendar.
You can view a video on using Device Calendar at: http://docs.kony.com/video_ tutorials/default.htm#DeviceCalendar.htm%3FTocPath%3D_____11 .
Note: In Windows Phone 7.5, the calendar event is only added at the application level and not on the phone's default calendar application.
29.5.1 Signature
JavaScript: kony.phone.addCalendarEvent(
)
29.5.2 Input Parameters eventDetails [Object] - Mandatory
A table that contains the following key-value pairs: l summary [String] - Short description for the event.
l start [String] - The start date and time for the event. The format for date is "dd/mm/yyyy", and time is "hh:mm:ss".
© 2015 by Kony, Inc. All rights reserved 603 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
l finish [String] - The finish date and time for the event. The format for date is "dd/mm/yyyy", and time is "hh:mm:ss".
l alarm [Number] - Time in seconds before the start time at which the phone must trigger an alarm.
l note [String] - Long description for the event.
l access [String] - Indicates the privacy setting for the event. The values can be one of the following:
1. public (default)
2. private
3. confidential
29.5.3 Return Values
None
29.5.4 Exceptions
PhoneError
The following error codes are defined for Phone APIs l
2100 - Unable to send the Message l
2101 - Insufficient Permissions l
2102 - Cannot open mail, mail not configured l
2103 - Cannot open media gallery
Error l
100 – invalid type of parameters l
101 – invalid number of arguments
© 2015 by Kony, Inc. All rights reserved 604 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
l
102 – invalid input – thrown when the input is invalid based on the context.
l
103 – invalid operation – thrown when the operation is invalid based on the context.
l
104 – not supported error – thrown when the method is not supported at all.
l
105 – index out of range.
l
106 – unknown error.
29.5.5 Platform Availability
Available on all platforms except BlackBerry 10, Mobile Web, Windows 8, Kiosk, Desktop Web, and
SPA.
Few conditions:
1. In Android: l
READ_CALENDAR and WRITE_CALENDAR permissions are needed for this API.
l
This API is supported for Android 4.0 version and above (that is, Android API level later to
13 ). Invocation on Android version less than 4.0 ( that is, Android API level earlier to 14) will be ignored.
l
For alarm parameter, seconds will be rounded off to nearest minute. That is, it rounds off to Floor or Ceil based on < 30sec or >= 30sec.
l
Events will be added to Local Calendar (not syncable to email accounts) with Calendar name same as application name.
2. Events cannot be added in past time.
3. Time zone of event added is same as the device Time Zone.
29.5.6 Rules and Restrictions
The finish input parameter must be greater than the start input parameter.
© 2015 by Kony, Inc. All rights reserved 605 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
29.5.7 JavaScript Example function addCalendarEvent()
{ try
{ alert("calendar event is about to start"); var evtobj={summary:"Event started", start:"15/04/2012
11:23:45", finish:"21/12/2012 12:59:45", alarm:40,note:"Event will ends at 12.59 PM", access:"public"};
} catch(PhoneError)
{ kony.phone.addCalendarEvent(evtobj);
//Adds a event to the device calendar alert("error in addCalendarEvent:: "+PhoneError);
}
}
29.6 kony.phone.findCalendarEvents
This API finds an event in the device calendar.
29.6.1 Signature:
JavaScript: kony.phone.findCalendarEvents(
)
29.6.2 Parameters: evtobj [Object] - Mandatory
A Hash table that has the following key-value pairs (details of the event):
© 2015 by Kony, Inc. All rights reserved 606 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
l type [String] - Specifies the criteria for searching the event. The criteria can be starting, ending, or occurring.
l starting - Searches for events starting between "start" and "finish".
l ending - Searches for events ending between "start" and "finish".
l occurring (default) : Searches for events that have any part of the event occurring during the period specified between "start" and "finish".
l start [String] - Specifies the start date and time for the event. The format for date is
"dd/mm/yyyy", and time is "hh:mm:ss" l finish [String] - Specifies the finish date and time for the event. The format for date is
"dd/mm/yyyy", and time is "hh:mm:ss"
Note: The finish date must be greater than the start date.
29.6.3 Return Values: eventHandle
Handle to the event (s) that match the specified input string in the device calendar. An array of objects contains: l summary [String] - Short description for the event.
l start [String] - The start date and time for the event. The format for date is
"dd/mm/yyyy", and time is "hh:mm:ss".
l finish [String] - The finish date and time for the event. The format for date is
"dd/mm/yyyy", and time is "hh:mm:ss".
l alarm [Number] - Time in seconds before the start time at which the phone must trigger an alarm.
l event ID [Number] - Identification number for that event.
© 2015 by Kony, Inc. All rights reserved 607 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
l note [String] - Long description for the event.
l access [String] - Indicates the privacy setting for the event. The values can be one of the following:
1. public (default)
2. private
3. confidential null
If there is no event found that matches the specified criteria.
29.6.4 Exceptions:
PhoneError
The following error codes are defined for Phone APIs l
2100 - Unable to send the Message l
2101 - Insufficient Permissions l
2102 - Cannot open mail, mail not configured l
2103 - Cannot open media gallery
Error l
100 – invalid type of parameters l
101 – invalid number of arguments l
102 – invalid input – thrown when the input is invalid based on the context.
l
103 – invalid operation – thrown when the operation is invalid based on the context.
l
104 – not supported error – thrown when the method is not supported at all.
© 2015 by Kony, Inc. All rights reserved 608 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
l
105 – index out of range.
l
106 – unknown error.
29.6.5 Platform Availability
Available on all platforms except BlackBerry 10, Mobile Web, Windows 8, Kiosk, Desktop Web, and
SPA.
29.6.6 Rules and Restrictions l
READ_CALENDAR permission is needed for this API.
l
This API is supported for Android 4.0 version and above (that is, Android API level later to 13).
Invocation on Android version less than 4.0 ( that is, Android API level earlier to 14) will be ignored.
l
This API searches only those events that are added by the application .
29.6.7 JavaScript Example function findCalendarEvent()
{ try
{ alert("Finding the calendar events"); var evtobj={type:"starting",start:"15/03/2012 12:46:45", finish:"24/12/2012 12:59:45"}; var events = kony.phone.findCalendarEvents(evtobj); alert("Found calendar event(s)");
} catch(err)
{ alert("error in findCalendarEvents:: "+err);
© 2015 by Kony, Inc. All rights reserved 609 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
}
}
29.7 kony.phone.removeCalendarEvent
This API deletes an event that matches the specified event handled from the device calendar.
Note: To delete an event, you must first search the event using the find API and delete the event
29.7.1 Signature:
JavaScript:
kony.phone.removeCalendarEvent( eventHandle )
29.7.2 Parameters: eventHandle [Object] - Mandatory
Event handle is returned by the find operation.
Note: To delete an event, you must first search the event using the find API and delete the event.
29.7.3 Return Values:
None.
29.7.4 Exceptions:
PhoneError
The following error codes are defined for Phone APIs
© 2015 by Kony, Inc. All rights reserved 610 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
l
2100 - Unable to send the Message l
2101 - Insufficient Permissions l
2102 - Cannot open mail, mail not configured l
2103 - Cannot open media gallery
Error l
100 – invalid type of parameters l
101 – invalid number of arguments l
102 – invalid input – thrown when the input is invalid based on the context.
l
103 – invalid operation – thrown when the operation is invalid based on the context.
l
104 – not supported error – thrown when the method is not supported at all.
l
105 – index out of range.
l
106 – unknown error.
29.7.5 Platform Availability
Available on all platforms except BlackBerry 10, Mobile Web, Windows 8, Kiosk, Desktop Web, and
SPA.
29.7.6 Rules and Restrictions l
READ_CALENDAR and WRITE_CALENDAR permissions are needed for this API.
l
This API is supported for Android 4.0 version and above (that is, Android API level later to 13).
Invocation on Android version less than 4.0 ( that is, Android API level earlier to 14) will be ignored.
l
If this API removes last calendar event added to local calendar, then the local calendar account will be deleted.
© 2015 by Kony, Inc. All rights reserved 611 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
29.7.7 JavaScript Example: function removeCalendarEvent() { try { var evtobj = { type: "starting", start: "20/03/2014", finish: "21/03/2014"
}; var events = kony.phone.findCalendarEvents(evtobj); kony.phone.removeCalendarEvent(events[1]); alert("Event deleted successfully");
// It deletes an event that matches the specified
// event handle from the device calendar
} catch (err) { alert("error in removeCalendarEvent:: " + err);
}
}
29.8 kony.contact.add
This API adds a contact to the address book of the mobile device.
Important: On Windows Phone 7.5, you have to manually click the Save button to add the contact.
29.8.1 Signature
JavaScript: kony.contact.add(
© 2015 by Kony, Inc. All rights reserved 612 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
29.8.2 Parameters contactDetails [Table] - Mandatory
A table that has the following key-value pairs: l firstname - specifies the first name of the contact l lastname - specifies the last name of the contact l phone - array of arrays containing Label and number
Note: The phone number can contain a + (for country code), - (hyphen) (to separate country code, STD code, and the number), and space ((to separate country code, STD code, and the number). No other characters are allowed within a phone number.
Note: For example, +919999999999, +91 99999 99999, or +91-99999-99999.
l email - array of arrays containing Label and emailID l postal - array of arrays containing Label and address in a table with defined keys l company - array of arrays containing Label followed by table with company name and title keys
Note: firstname and phone fields are mandatory with at least one phone number in phone field
The following are the Labels for different fields in the table:
Keys in the Table phone
Possible Labels
•Mobile •Home •Work •Other
© 2015 by Kony, Inc. All rights reserved 613 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
email postal company
•Home •Work •Other
•Home •Work •Other
•Work •Other
29.8.3 Return Values
The following are the return values for this API:
Reference [Table]
Table containing the information related to the newly created contact is returned.
nil
If the contact was not created.
29.8.4 Error Codes
If any of the field is not stored, the field is ignored. If no field is stored, an error is raised.
29.8.5 Implementation Details
The following are the implementation details: l firstname and phone field with empty string or nil does not create a contact and the API call is ignored.
l
Other fields with empty string or nil or invalid data type assignment are ignored.
l id field is read only property and must not be modified by the application.
29.8.6 API Usage
When you use this API with Android emulator that uses Android SDK 2.0 and above, you will be prompted to create an account to add contacts.
© 2015 by Kony, Inc. All rights reserved 614 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
Creating an account (Google/GMail) is a mandate to add contacts. This is an Android platform limitation.
Ensure that the following permissions are set for Android: l
READ_CONTACTS l
WRITE_CONTACTS l
GET_ACCOUNTS.
You can set these permissions for Android under Manifest Properties in Project Properties ->
Native App -> Android. For more information about Android Manifest permissions, see Kony Studio
User Guide.
29.8.7 Platform Availability
Available on all platforms except SPA, Desktop Web, Mobile Web, Kiosk, Windows 8, and Win Mobile
6x.
29.9 kony.contact.find
This API parses through the address book of the mobile device and looks for contacts that match the input string.
29.9.1 Signature
JavaScript: kony.contact.find(
)
29.9.2 Parameters firstName [String] - Mandatory
A string that represents the firstname of the contact.
© 2015 by Kony, Inc. All rights reserved 615 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
needdetails [boolean] - Optional
When the needdetails parameter is not passed, the default value set is true. When needdetails is set to true, this API returns the complete details of the contact. If needdetails is false, contact.find
returns a list of contacts with a new field called displayname in the existing contact structure. All other fields of contact structure are not populated.
displayname is a combination of firstname and lastname.
displayname is a platform specific Android property.
29.9.3 Return Values
Reference [Object]
Table containing the list of all the contacts that contain the input string nil
If there is no contact with the specified first name
29.9.4 Implementation Details
This API searches and matches only the contacts that have the firstname as the specified input string.
29.9.5 Platform Availability
Available on all platforms except SPA, Desktop Web, Mobile Web, Kiosk, and Win Mobile 6x.
29.10 kony.contact.remove
This API deletes the contact (s) that was returned by the contact.find operation.
29.10.1 Signature
JavaScript: kony.contact.remove(
)
© 2015 by Kony, Inc. All rights reserved 616 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
29.10.2 Parameters
ReferenceTable - Mandatory
Specifies the reference table returned by the contact.find API
29.10.3 Return Values
Reference [Table]
Table of the contacts that is deleted nil
If no contact is deleted
29.10.4 Platform Availability
Available on all platforms except SPA, Desktop Web, Mobile Web, Kiosk, Windows 8, Windows
Phone 7.5, and Win Mobile 6x.
29.11 kony.contact.details
This API displays the details of a given contact and returns a new instance of the contact structure.
The API is introduced to improve the performance and for effective utilization of memory. In platforms like Android, contact information is stored in multiple database tables, one table contains the contact id, first name, and lastname, and the another table contains the entire contact details. The contacts application displays only firstname, lastname in the initial screen, and when the user selects a particular contact, the details are shown in next screen.
When you to accommodate the contact details in one call to contact.find API, the memory is not sufficient when the contacts are numerous. This results in an out of memory issue and results in performance issues in many applications.
© 2015 by Kony, Inc. All rights reserved 617 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
29.11.1 Signature
JavaScript:
kony.contact.details( ReferenceTable
)
29.11.2 Parameters
ReferenceTable - Mandatory
Specifies the reference table returned by the contact.find API
29.11.3 Return Values
Reference [Table]
Table of the contacts retrieved. The reference table retrieved contains a field photorawbytes. This is a new property in the existing contact structure that should be populated with raw bytes, just like camera or gallery raw bytes.
Example of the reference table returned:
{ firstname="John", lastname="Xyz",
//array of arrays containing "Label" and "number" phone={{name="mobile",number="99999999999"},
////array of arrays containing "Label" and "emailid"
{name="home",number="99999999999"},
{name="home",number="5555555555"},.....}, email={{name="home",id="[email protected]" },
{name="work",id="[email protected]"},....},
////array of arrays containing "Label" and address in a table with
© 2015 by Kony, Inc. All rights reserved 618 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
defined keys.
postal=
{name="home",street="ABC",city="hyderabad",state="AP",zipcode="50031
0"}
,
{name="work",street="XYZ",city="hyderabad",state="AP",zipcode="50001
0"}
,...},
//array of arrays containing "Label" followed by table with company name and title keys.
company={{name="work",company="kony",title="Tester"},
{name="other",company="abc",title="VP"},...}, id="platform specific identifier for the contact" photorawbytes=rawbytes
} nil
If no contact is retrieved.
29.11.4 Platform Availability
Available on all platforms except SPA, Desktop Web, BlackBerry 10, Mobile Web, Kiosk,Windows 8, and Windows Mobile 6x.
29.11.5 JavaScript Example function form1_button15681600315097_onClick_seq0(eventobject) { var array = kony.contact.find('John', false)
© 2015 by Kony, Inc. All rights reserved 619 of 848
29. Phone APIs Kony Studio API Developer's Guide
Version 5.0
}; var dict = array[0] kony.print(kony.contact.details(array[0]))
© 2015 by Kony, Inc. All rights reserved 620 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30. Standard Kony APIs
This chapter explains the APIs that are not tied to any specific namespace.
The following APIs are explained in this chapter: l
l
l
l
l
l
l
30.1 kony.convertToBase64
This API provides you the ability to convert rawbytes (returned by the camera or the encryption API) to a base64 encoded string.
30.1.1 Use Cases
The rawbytes returned by the camera or the encryption API are a set of junk characters that are not readable. When you want to display this data in a readable format to the user, you can use this API.
30.1.2 Signature
JavaScript
: kony.convertToBase64 ( rawbytes )
© 2015 by Kony, Inc. All rights reserved 621 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30.1.3 Input Parameters rawbytes [userData]: The datatype for the rawbytes differs per platform]- Mandatory
The rawbytes that you want to convert to an encoded base64 string. These rawbytes can be those that are returned from a camera or the encryption API.
30.1.4 Return Values mybase64String [String]
The encoded base64 string that was converted from the provided rawbytes. This converted encoded base64 string can be displayed on the screen to the user whenever required as this string is readable.
null/nil
JavaScript returns null null/nil is returned if the rawbytes cannot be converted to base64 string or the provided input is not of type rawbytes.
30.1.5 Exceptions
An error is thrown if the input type is invalid or follows an unexpected structure.
102-Invalid input error
30.1.6 Platform Availability
Available on all platforms except Desktop Web and Server Side Mobile Web.
30.1.7 JavaScript Example var base64
="MIICKTCCAZKgAwIBAgIESrI6bzANBgkqhkiG9w0BAQUFADBZMQswCQYDVQQGEwJp
© 2015 by Kony, Inc. All rights reserved 622 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
bjELMAkGA1UECBMCYXAxDDAKBgNVBAcTA2h5ZDENMAsGA1UEChMEa29ueTENMAsGA1UE
CxMEa29ue
TERMA8GA1UEAxMIcGF0dGFiaGkwHhcNMDkwOTE3MTMzMjMxWhcNMDkxMjE2MTMzMjMxW jBZMQswCQ
YDVQQGEwJpbjELMAkGA1UECBMCYXAxDDAKBgNVBAcTA2h5ZDENMAsGA1UEChMEa29ueT
ENMAsGA1U
ECxMEa29ueTERMA8GA1UEAxMIcGF0dGFiaGkwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIG
JAoGBAIGP dqCQCtFgsy1sM494o1F07aN+UXgsilTuKsNRExOb03RGrg2WpAI8PqMXD1XzGZAg+qC9 iQexpWHUj
XgCYCbYrETvB3wNAToOrRE6mhZ0iaJij/0tLZACocLiTnvmzZU1B/xowvlioD3zsEs5N
5n0U0fIsv
W/22MZ6WtZuAZTAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAXfOB1Mhx2R9ameeZz0hvCz
YYSGcWsWN
ZaM7lMdBHFPzASYcVrmLj7JlLpuMm679A2p2JwXBsfetmhKse1ixqVeWdbe/FUfESU+8
Krdvkcknv
ZaDqXYFxQAaVjTwWOn+zcDHf7LjjDohgDsMOJWXHkVQj2jooXqiktrBrpccm864="; var rawBytes = kony.convertToRawBytes(base64); var newbase64 = kony.convertToBase64(rawBytes);
30.2 kony.convertToRawBytes
This API provides you the ability to read rawbytes from a base 64 encoded string.
© 2015 by Kony, Inc. All rights reserved 623 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30.2.1 Signature
JavaScript: kony.convertToRawBytes(
)
30.2.2 Input Parameters base64String [String]- Mandatory.
The base64 encoded string from which you want to read the rawbytes.
30.2.3 Return Values
This API returns the modified rawbytes of the image.
rawbytes - Userdata.
The datatype of the rawbytes varies per platform. In JavaScript, there is no specific type for rawbytes and every platform represent the rawbytes in a unique way.
null/nil null/nil is returned if the input is not a base64 encoded string
30.2.4 Exceptions
An error occurs if input type is invalid or does not follow the expected structure.
30.2.5 Platform Availability
Available on all platforms except Desktop Web and Server Side Mobile Web. On SPA, reading base64 from an image src is not supported, but you can read the base64 from an image which is displayed through base64.
© 2015 by Kony, Inc. All rights reserved 624 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30.2.6 JavaScript Example var base64
="MIICKTCCAZKgAwIBAgIESrI6bzANBgkqhkiG9w0BAQUFADBZMQswCQYDVQQGEwJpbj
ELMAkGA1UECBMCYXAxDDAKBgNVBAcTA2h5ZDENMAsGA1UEChMEa29ueTENMAsGA1UECx
MEa29ueTERMA8GA1UEAxMIcGF0dGFiaGkwHhcNMDkwOTE3MTMzMjMxWhcNMDkxMjE2MT
MzMjMxWjBZMQswCQYDVQQGEwJpbjELMAkGA1UECBMCYXAxDDAKBgNVBAcTA2h5ZDENMA sGA1UEChMEa29ueTENMAsGA1UECxMEa29ueTERMA8GA1UEAxMIcGF0dGFiaGkwgZ8wDQ
YJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIGPdqCQCtFgsy1sM494o1F07aN+UXgsilTuKs
NRExOb03RGrg2WpAI8PqMXD1XzGZAg+qC9iQexpWHUjXgCYCbYrETvB3wNAToOrRE6mh
Z0iaJij/0tLZACocLiTnvmzZU1B/xowvlioD3zsEs5N5n0U0fIsv
W/22MZ6WtZuAZTAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAXfOB1Mhx2R9ameeZz0hvCz
YYSGcWsWNZaM7lMdBHFPzASYcVrmLj7JlLpuMm679A2p2JwXBsfetmhKse1ixqVeWdbe
/FUfESU+8Krdvkcknv
ZaDqXYFxQAaVjTwWOn+zcDHf7LjjDohgDsMOJWXHkVQj2jooXqiktrBrpccm864="; kony.convertToBase64(myVal) var rawBytes = kony.convertToRawBytes(base64);
30.3 kony.getError
This API uses the handle to the error object and returns the actual error object.
30.3.1 Signature
JavaScript : kony.getError(
30.3.2 Input Parameters error-[Error] / [object/handle] - Mandatory
The input parameters of this API is either the Original Error object or a handle received in try/catch block.
© 2015 by Kony, Inc. All rights reserved 625 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30.3.3 Return Values
Returns the JavaScript error object.
30.3.4 Exceptions
If the input type is invalid or there is an unexpected structure.
30.3.5 Special considerations:
Use getError APIs for cross platform applications to handle exceptions consistently.
30.3.6 Platform Availability
Available on all platforms except BlackBerry 10, Windows 8 and Windows 7 / Kiosk.
30.3.7 JavaScript Example try
{
// Label to check UserData Type.
var basicconf = { id : "lblWithUserData", text:"userdata", isVisible:true,skin:"sknlbl"}; var layoutconf = {containerWeight:100, hExpand: true,vExpand:true}; var lbl1 = new kony.ui.Label(basicconf, layoutconf, {}); hbox.add(lbl1);
} catch ( e )
{ var err = kony.getError(e);
© 2015 by Kony, Inc. All rights reserved 626 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
if (err instanceof KonyError) alert("A Kony error"); else (err instanceof EvalError) alert("A JavaScript Eval Eror");
}
30.4 kony.props.getProperty
This API is used to access parameters from an external properties file. All the external properties files must be appended to the
<appID>.properties
file and be deployed at the following folder on the Kony Application Server:
<middlewarehome>\middleware\middlewarebootconfig\tc\<appID>.properties
30.4.1 Signature
JavaScript: kony.props.getProperty(
)
30.4.2 Input Parameters group - Mandatory
Current value is null for JavaScript, this parameter will be used and enhanced in the future.
key [String] - Mandatory
The key for which you want to access the value.
30.4.3 Return Values value [String]
The value that matches the given key
© 2015 by Kony, Inc. All rights reserved 627 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
null/nil null or nil is returned if there is no value matching the given input key in the
properties file
30.4.4 Platform Availability
Available on Mobile Web and SPA.
30.4.5 JavaScript Example frmhome.label103982946332169.text=kony.props.getProperty
(null,"key1");
30.5 kony.print
This API receives a string as an argument. If any other type of argument is passed a string representation of that input is passed. It prints the value to the Standard Output specific to the platform.
It prints their values to stdout, using the
tostring
function to convert them to strings. print is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted output, use
string.format
.
Note: To view the log in BlackBerry 10, see Viewing log for BlackBerry 10 section.
30.5.1 Signature
JavaScript : kony.print(
30.5.2 Input Parameters myString[String] - Mandatory
Specifies the string to be printed
© 2015 by Kony, Inc. All rights reserved 628 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30.5.3 Return Values
None.
30.5.4 Platform Availability
Available on all platforms.
30.5.5 JavaScript Example kony.print ("This is a test message.");
30.6 kony.type
This API retrieves the data type of the specified input. The possible return values in JavaScript are: l string l number l boolean l function l userdata - not JavaScript type but the platform specific type that platform returns and consumes like rawBytes.
l
In case of kony custom objects, this API returns the fully qualified name of the class from which object is instantiated. for e.g
kony.ui.Form2
l null
Use the typeof operator instead of kony.type to achieve the same result. If the typeof operator cannot be used, use kony.type instead.
© 2015 by Kony, Inc. All rights reserved 629 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30.6.1 Signature
JavaScript : kony.type(
30.6.2 Input Parameters variable [String] or [Number] or [Boolean] or [Function] - or [userdata] or nil/null - Mandatory
Specifies the value for which you want to retrieve the data type.
30.6.3 Return Values returnValue [String]
Returns a string that determines the data type of the specified input. Possible values are: l string this value is returned when you pass a string as the input parameter.
l number this value is returned when you pass a number as the input parameter.
l boolean this value is returned when you pass a boolean value as the input parameter.
l function this value is returned when you pass a function as the input parameter.
l userdata this value is returned when the input parameter is not a string, number, boolean or function.
Note: Any data type which is not a string, number, boolean, or function is treated as userdata.
l null/nil this value is returned when the variable is assigned null/nil l
In case of kony custom objects, this API returns the fully qualified name of the class from which object is instantiated. for e.g
kony.ui.Form2
. When you pass any custom / built in
JSObject to this API, it should return the name of the custom JSObject.
30.6.4 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 630 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30.6.5 JavaScript Example var myVal = 2000; var varType = kony.type(myVal);//Returns a number var myVal1= "hello"; var varType = kony.type(myVal1);//Returns a string
30.7 Deprecated APIs
The APIs in this section are supported only for backward compatibility. This section lists all the deprecated APIs: l
kony.application.setAppHeaders
l
kony.application.setAppFooters
l
l
30.7.1 kony.application.setAppHeaders
This API allows you to set header at the application level with the given input values.
30.7.1.1 Signature
JavaScript: kony.application.setAppHeaders(
30.7.1.2 Input Parameters headerlist [Array] - Mandatory
Specifies the list of attributes for the header
30.7.1.3 Return Values
None.
© 2015 by Kony, Inc. All rights reserved 631 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30.7.2 Platform Availability
Available on all platforms.
30.7.3 kony.application.setAppFooters
This API allows you to set footer at the application level with the given input values.
Note: This API is deprecated and only works for backward compatibility.
30.7.3.1 Signature
JavaScript: kony.application.setAppFooters(
30.7.3.2 Input Parameters footerlist [Array] - Mandatory
Specifies the list of attributes for the footer
30.7.3.3 Return Values
None.
30.7.3.4 Implementation Details
To access the footer elements, use the following syntax: app.footers.hboxID.widgetID
30.7.4 Platform Availability
Available on all Platforms.
© 2015 by Kony, Inc. All rights reserved 632 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
30.7.5 kony.application.appReset
This API is used to reset the application. When this method is called, the data which was loaded during transactionaldataload event of forms is cleared (reset).
Note: This API is deprecated and only works for backward compatibility.
30.7.5.1 Signature
JavaScript :kony.application.appReset()
30.7.5.2 Input Parameters
None
30.7.5.3 Return Values
None.
30.7.6 Platform Availability
Available on all platforms except BlackBerry 10.
30.7.6.1 Example kony.application.appReset(); Resets the application data.
30.8 readfrombase64
This API provides you the ability to read rawbytes from a base 64 encoded string.
30.8.1 Input Parameters
The following table explains the input parameters for this API:
© 2015 by Kony, Inc. All rights reserved 633 of 848
30. Standard Kony APIs Kony Studio API Developer's Guide
Version 5.0
Parameter/Type Required base64String
[String] yes
Description
The base64 encoded string from which you want to read the rawbytes
30.8.2 Return Values
The following are the return values for this API:
Value/Type myrawbytes [JSObject] nil
Interpretation of return value
The rawbytes of the specified base64 encoded string nil is returned if the input is not a base64 encoded string
Remarks
30.8.3 Platform Availability
Android, BlackBerry, Windows, and SPA.
30.8.4 JavaScript Example
-- Converts the base64String to rawbytes.
local myrawbytes = readfrombase64(base64String)
-- The rawbytes extracted from the readfrombase64 API are passed to the crypto.decrypt API.
local decryptedstring = crypto.decrypt("aes",aeskey,myrawbytes);
© 2015 by Kony, Inc. All rights reserved 634 of 848
31. Streaming APIs Kony Studio API Developer's Guide
Version 5.0
31. Streaming APIs
Streaming is a feature that enables the device to listen to a continuous data stream and use the data.
The data is available on Streaming Servers. The common use of streaming is to utilize the multimedia from an external source (like audio or video) in your application. Streaming data uses different protocols to fetch the data.
Note: Kony currently supports only HTTP 1.1 protocol.
This chapter explains the various streaming APIs. The APIs available are: l
kony.stream.registerDataStream
l
kony.stream.deregisterDataStream
l
31.1 kony.stream.registerDataStream
This API registers the application for streaming with the OS provider of the underlying platform.
31.1.1 Signature
JavaScript: kony.stream.registerDataStream(
,
31.1.2 Input Parameters protocol [String] - Mandatory
Specifies the underlying streaming protocol to be used. Kony currently supports only HTTP1.1
protocol.
configparams [Table] - Mandatory
Specifies an Object with key-value pairs of configuration parameters required for the underlying protocol.
© 2015 by Kony, Inc. All rights reserved 635 of 848
31. Streaming APIs Kony Studio API Developer's Guide
Version 5.0
The following are the configuration parameters for HTTP1.1 protocol: l url [String] - Mandatory: Specifies the URL of the streaming server of a web site that has data that can be streamed. For example: url="http://www.mobilestreaming.kony.com.
l cookie [Object] - Optional:Specifies an Object with the following key-value pairs: o streamingid (String) o jessessionid (String) cookie={streamingid:"12218181agdgdhjhjd", jessessionid:"198181819919agagah1t1g1"} l headers [Object] - Optional: Specifies the header parameters.
//For example: {authmode:basic} l params [Object] - Optional: Specifies any additional parameters.
For example: {quote:"goog"} l method [String] - Mandatory: Specifies the method. Possible values are: o get o post(Default value is post)
For example: "post" outputformat [String] - Mandatory.
Specifies the output format of the stream. Currently supported values are: l
String (default) l
JSON
© 2015 by Kony, Inc. All rights reserved 636 of 848
31. Streaming APIs Kony Studio API Developer's Guide
Version 5.0
Note: If JSON is the output format specified, output from the streaming server is converted to an
Object and is passed as an input parameter to the callback function.
callback [Function] - Mandatory.
Specifies the function that needs to be executed when the streaming data is available.
Note: This function is also executed incase of any network error or system error in listening to the data stream.
The callback function has the following signature:
,
l status [Number] - indicates the status of the streaming operation. Possible values are: o
0 - indicates success o
1011 - Device has no wifi or mobile connectivity. Please try the operation after establishing connectivity.
o
1012 - Request Failed .This is a generic error and is thrown if the platform is not able to differentiate between various errors.
o
1014 - Request timed out o
1015 - Cannot find host.
o
1016 - Cannot connect to host.
o 1002 - Error reading from stream.
o
1019 - Error writing into stream.
o
1020 - End of stream with errors.
o
1021 - End of stream.
© 2015 by Kony, Inc. All rights reserved 637 of 848
31. Streaming APIs Kony Studio API Developer's Guide
Version 5.0
l data[Object or String] - If the output format is JSON it is an Object and if the output format is string, it is a String. Incase of any error, data will be null/nil.
l context[Object] - Contains additional information that needs to be passed to the underlying streaming API. For HTTP1.1 protocol, this table contains a value httpresponsecode.
31.1.3 Return Values
StreamID [String]
Stream identifier for this registration. This identifier is to be used during deregistration. Null incase there is any input error for a JavaScript application.
31.1.4 Exceptions l
StreamingError: Error thrown by Streaming API. Various error conditions related to Stream
Error will be covered through following error codes.
l
Error
31.1.5 Platform Availability
Available on all platforms except BlackBerry 10, Desktop Web and Windows Kiosk*. *Dummy
Implementation on Mobile Web.
31.1.6 JavaScript Example function myCallbackFunction(status, data, context)
{
//Execute the logic here
} function registerDataStream()
{
//Defining config parameters to register stream.
var configParams =
© 2015 by Kony, Inc. All rights reserved 638 of 848
31. Streaming APIs Kony Studio API Developer's Guide
Version 5.0
{url:"http//www.mobilestreaming.kony.com",method:
"post"};
//Registers stream var streamObj = kony.stream.registerDataStream("http1.1", configParams, "json", myCallbackFunction);
//Reading the stream ID alert("Stream id is ::"+streamObj["streamID"]);
}
31.2 kony.stream.deregisterDataStream
This API allows you to deregister the application that was registered earlier with the Streaming Server.
31.2.1 Use Case
Use this API when you want to discontinue an application from streaming the data from a streaming server.
31.2.2 Signature
JavaScript: kony.stream.deregisterDataStream(
)
31.2.3 Input Parameters streamingidentifer [String] - Mandatory
Streaming identifier returned during registration.
31.2.4 Return Values
None.
© 2015 by Kony, Inc. All rights reserved 639 of 848
31. Streaming APIs Kony Studio API Developer's Guide
Version 5.0
31.2.5 Exceptions: l
StreamingError l
Error
31.2.6 Platform Availability
Available on all platforms except BlackBerry 10, Desktop Web and Windows Kiosk*. *Dummy
Implementation on Mobile Web.
31.2.7 JavaScript Example function deregisterDataStream()
{
//Defining config parameters to register stream.
var configParams = {url:"http//www.mobilestreaming.kony.com", method:"post"};
//Registers stream var streamObj = kony.stream.registerDataStream("http1.1", configParams, "json", myCallbackFunction);
//Reading the stream ID alert("Stream id is ::"+streamObj["streamID"]);
Windows
//Deregisters the data stream with the specified identifier on
Phone var status = kony.stream.deregisterDataStream(streamObj
["streamID"]);
//Reading the status
© 2015 by Kony, Inc. All rights reserved 640 of 848
31. Streaming APIs Kony Studio API Developer's Guide
Version 5.0
alert("Status is ::"+status);
}
31.3 kony.stream.setCallback
This API specifies the callback function that needs to be executed for a registered data stream.
31.3.1 Signature
JavaScript:
kony.stream.setCallback( streamingid
,
31.3.2 Input Parameters streamingid [String] - Mandatory
Specifies the unique ID that identifies the stream.
callbackfunction [Function] - Mandatory
Specifies the callback function that needs to be executed.
31.3.3 Return Values
None
31.3.4 Exceptions l
StreamingError: Error thrown by Streaming API. Various error conditions related to Stream
Error will be covered through following error codes.
l
Error
© 2015 by Kony, Inc. All rights reserved 641 of 848
31. Streaming APIs Kony Studio API Developer's Guide
Version 5.0
31.3.5 Platform Availability
Available on all platforms except BlackBerry 10, Desktop Web and Windows Kiosk*. *Dummy
Implementation on Mobile Web.
31.3.6 JavaScript Example
//Callback function for setCallback function myCallbackFunction1(status, data, context)
{
//Execute the logic here
} function setCallback()
{
//Invoking setCallback with the streamID :"1" kony.stream.setCallback("1", myCallbackFunction1);
}
© 2015 by Kony, Inc. All rights reserved 642 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32. String APIs
The string Library has APIs that you can use to manipulate strings. The kony.string name space provides static string APIs. These static APIs augment the APIs in the Global string object which is available by default. For more information refer, https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/string.
32.1 Distinction between string primitives and string objects
Note that JavaScript distinguishes between String objects and primitive string values.
String literals (denoted by double or single quotes) and strings returned from String calls in a nonconstructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives and String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs. JavaScript automatically wraps the string primitive and calls the method or performs the property lookup.
All the APIs in the string library have the namespace kony.string. The following APIs are described in the sections below: l
l
l
l
l
l
l
l
kony.string.isAsciiAlphaNumeric
l
© 2015 by Kony, Inc. All rights reserved 643 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
l
l
kony.string.containsOnlyGivenChars
l
kony.string.containsNoGivenChars
l
All the APIs that are deprecated in JavaScript are available at:
32.2 kony.string.endsWith
This API returns a boolean value indicating if the source string ends with the specified string.
32.2.1 Signature
JavaScript: kony.string.endsWith(
,
)
32.2.2 Input Parameters sourcestring [String] - Mandatory
Specifies the source string.
comparestring [String] - Mandatory
Specifies the string to be compared with the source string.
ignorecase [Boolean] - Optional
Default value is true, i.e, the comparison is not case sensitive.
If you want the comparison to be case sensitive, you must specify the value as false.
32.2.3 Return Values boolean true - source string ends with compared string.
© 2015 by Kony, Inc. All rights reserved 644 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
false - source string does not end with compared string.
32.2.4 Platform Availability
Available on all platforms.
32.2.5 JavaScript Example
//Returns true since comparison is not case sensitive.The resultant is assigned to a label text.
var resultantString = kony.string.endsWith("Kony
Solutions","solutions",true); frmEndsWith.endsWithLabel.text = resultantString;
32.3 kony.string.equalsIgnoreCase
Determines whether two strings contain the same data, ignoring the case of the letters in the String.
32.3.1 Signature
JavaScript:
kony.string.equalsIgnoreCase( string1
,
32.3.2 Input Parameters string1 [String] - Mandatory
Specifies the content of the first string.
string2 [String] - Mandatory
Specifies the content of the second string.
© 2015 by Kony, Inc. All rights reserved 645 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.3.3 Return Values boolean true - both strings contain exactly the same data.
false - both strings do not contain exactly the same data
32.3.4 Platform Availability
Available on all platforms.
32.3.5 JavaScript Example
Perform a kony.string.equalsIgnoreCase on the string "Hello" with another string "HEllo": var ignorecase = kony.string.equalsIgnoreCase("Hello","HEllo") kony.print (ignorecase);
The kony.string.equalsIgnoreCase compares the strings "Hello" and "HEllo" without case sensitivity and returns a Boolean indicating if the strings are a match.
In this example, true is the value returned.
32.4 kony.string.rep
This API generates a string which is equivalent to " n copies of the source string concatenated together".
32.4.1 Signature
JavaScript: kony.string.rep(
)
© 2015 by Kony, Inc. All rights reserved 646 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.4.2 Input Parameters sourcestring [String] - Mandatory
Specifies the source string.
no [Number] - Mandatory
Specifies the number of times the source string must be repeated.
32.4.3 Return Values concatenatedstring [String]
A string containing n copies of the source string concatenated together is returned .
32.4.4 Exceptions
An error is thrown if input type is invalid or does not follow the expected structure.
102-Invalid input error.
32.4.5 Platform Availability
Available on all platforms.
32.4.6 JavaScript Example
Perform a kony.string.rep operation on the source string "kony": var resultantString = kony.string.rep("kony",5); frmRep.concatenatedStringLabel.text = resultantString;
The resultant string contains konykonykonykonykony.
© 2015 by Kony, Inc. All rights reserved 647 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.5 kony.string.reverse
This API reverses the characters in the source string.
32.5.1 Signature
JavaScript: kony.string.reverse(
)
32.5.2 Input Parameters string [String] - Mandatory
Specifies the source string.
32.5.3 Return Values reversedstring [String]
A string containing the characters of the source string in reverse is returned.
32.5.4 Exceptions
An error is thrown if input type is invalid or does not follow the expected structure.
102-Invalid input error
32.5.5 Platform Availability
Available on all platforms.
32.5.6 JavaScript Example
Perform a reverse operation on the source string "kony":
© 2015 by Kony, Inc. All rights reserved 648 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
var resultantString = kony.string.reverse("kony"); frmReverse.reversedStringLabel.text = resultantString;
The resultant string will contain ynok.
32.6 kony.string.startsWith
This API returns a boolean value indicating if the source string begins with the specified string.
32.6.1 Signature
JavaScript: kony.string.startsWith(
,
)
32.6.2 Input Parameters sourcestring [String] - Mandatory
Specifies the source string.
comparestring [String] - Mandatory
Specifies the string to be compared with the source string.
ignorecase [Boolean] - Optional
Default value is true. If you do not specify the ignorecase parameter, the comparison of the string will be case insensitive. If you want the comparison to be case sensitive, you must specify the value as false.
32.6.3 Return Values boolean true - source string begins with the compared string.
false - source string does not begin with the compared string.
© 2015 by Kony, Inc. All rights reserved 649 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.6.4 Exceptions
An error is thrown if input type is invalid or does not follow the expected structure.
102-Invalid input error.
32.6.5 Platform Availability
Available on all platforms.
32.6.6 JavaScript Example
Perform a kony.string.startsWith on the source string "Kony Solutions" for the string "kony" specifying the ignorecase parameter: var resultantString = kony.string.startsWith("Kony
Solutions","kony",true); frmStartsWith.startsWithLabel.text = resultantString;
The kony.string.startsWith compares the source string "Kony Solutions" with the string "kony" without case sensitivity and returns a boolean indicating if the source string begins with the specified string.
In this example, true is the value returned.
32.7 kony.string.trim
This API removes the leading and ending spaces from the source string.
32.7.1 Signature
JavaScript: kony.string.trim(
)
© 2015 by Kony, Inc. All rights reserved 650 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.7.2 Input Parameters string [String] - Mandatory
Specifies the source string.
32.7.3 Return Values trimmedstring [String]
A string without the leading and ending spaces is returned.
32.7.4 Exceptions
An error is thrown if input type is invalid or does not follow the expected structure.
102-Invalid input error
32.7.5 Platform Availability
Available on all platforms.
32.7.6 JavaScript Example
Remove the leading and ending spaces in " kony solutions ": var resultantString = kony.string.trim("
"); kony solutions frmTrim.trimmedStringLabel.text = "\""+resultantString+"\"";
In this example, kony solutions is the value returned.
© 2015 by Kony, Inc. All rights reserved 651 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.8 kony.string.isAsciiAlpha
This API verifies if the input string contains only ASCII alphabet characters and returns a boolean value.
32.8.1 Signature
JavaScript:
kony.string.isAsciiAlpha ( inputstring
)
32.8.2 Input Parameters inputstring [String] - Mandatory
Specifies the input string that needs to be verified.
32.8.3 Return Values status [Boolean] true - if the input string contains only alphabetic characters.
false - if there is an error in the input or the input string contains characters other than alphabet.
32.8.4 Exceptions
An error is thrown if input type is invalid or follows an unexpected structure.
102-Invalid input error.
32.8.5 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 652 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.8.6 JavaScript Example
In this example, the kony.string.isAsciiAlpha API returns true or false based on the input string entered.
var inputstring = "abdcdADV"; kony.print(kony.string.isAsciiAlpha(inputstring));
//prints true var inputstring = "123ab3dcdADV"; kony.print(kony.string.isAsciiAlpha(inputstring));
//prints false
32.9 kony.string.isAsciiAlphaNumeric
This API verifies if the input string contains only ASCII alphabet characters and numbers, and returns a boolean value.
32.9.1 Signature
JavaScript: kony.string.isAsciiAlphaNumeric (
)
32.9.2 Input Parameters inputstring [String] - Mandatory
Specifies the input string that needs to be verified.
32.9.3 Return Values status [Boolean] true - if the input string contains only alphanumeric characters. i.e it can contain a string of numbers, characters or a string containing both numbers and characters.
© 2015 by Kony, Inc. All rights reserved 653 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
false - if there is an error in the input or the input string contains characters other than alphanumeric.
32.9.4 Exceptions
An error is thrown if input type is invalid or follows an unexpected structure.
102-Invalid input error.
32.9.5 Platform Availability
Available on all platforms.
32.9.6 JavaScript Example
In this example, kony.string.isAsciiAlphaNumeric returns true or false based on the input string.
var inputstring = "abdcdADV"; kony.print(kony.string.isAsciiAlphaNumeric(inputstring));
//prints false because the string is not a combination of alphanumeric characters var inputstring ="abcd1234" kony.print(kony.string.isAsciiAlphaNumeric (inputstring));
//prints true because the string is a combination of alphanumeric characters
32.10 kony.string.isNumeric
This API verifies if the input string contains only numeric characters, and returns a boolean value.
32.10.1 Signature
JavaScript: kony.string.isNumeric (
)
© 2015 by Kony, Inc. All rights reserved 654 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.10.2 Input Parameters inputstring [String] - Mandatory
Specifies the input string that needs to be verified.
32.10.3 Return Values status [Boolean] true - if the input string contains only numeric characters.
false - if there is an error in the input or the input string contains characters other than numbers.
32.10.4 Exceptions
An error is thrown if input type is invalid or follows an unexpected structure.
102-Invalid input error.
32.10.5 Platform Availability
Available on all platforms.
32.10.6 JavaScript Example
In this example, kony.string.isNumeric returns true if the input string has only numbers.
kony.print(kony.string.isNumeric("123ab3dcdADV"));
// prints false kony.print(kony.string.isNumeric("12344")) ;
// prints true
© 2015 by Kony, Inc. All rights reserved 655 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.11 kony.string.containsChars
This API verifies if any one of the specified set of characters is available in the given string and returns a boolean value.
32.11.1 Signature
JavaScript: kony.string.containsChars (
inputstring , characterArray )
32.11.2 Input Parameters inputstring [String] - Mandatory
Specifies the input string that needs to be verified.
characterArray [Array] - Mandatory
Specifies the set of characters that need to be searched within the input string.
32.11.3 Return Values status [Boolean] true - if the given input string contains any one of the characters in the specified list.
false - if there is an error in the input or if the given input string does not contain any of the specified input characters.
32.11.4 Exceptions
An error is thrown if input type is invalid or follows an unexpected structure.
102-Invalid input error.
32.11.5 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 656 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.11.6 JavaScript Example
In this example, kony.string.containsChars returns true if the input string consists the characters specified in the characterArray. For example, since the input string "abcd|ADV" consists the characters specified in the character array, kony.string.containsChars returns true.
var inputstring = "abdcdADV"; var charsArr = ["|","-"]; kony.print(kony.string.containsChars(inputstring, charsArr));
// prints false as | and - are NOT contained in the input var inputstring = "abdcd|ADV" kony.print(kony.string.containsChars(inputstring, charsArr));
// prints true as | is contained in the input
32.12 kony.string.containsOnlyGivenChars
This API verifies if only (and only) the specified set of characters is available in the given string and returns a boolean value.
32.12.1 Signature
JavaScript: kony.string.containsOnlyGivenChars (
inputstring , characterArray )
32.12.2 Input Parameters inputstring [String] - Mandatory
Specifies the input string that needs to be verified.
characterArray [Array] - Mandatory
Specifies the set of characters that need to be searched within the input string.
© 2015 by Kony, Inc. All rights reserved 657 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.12.3 Return Values status [Boolean] true - if the given input string contains only the characters in the specified list.
false - if there is an error in the input or if the given input string contains any other characters apart from the specified input characters.
32.12.4 Exceptions
An error is thrown if input type is invalid or follows an unexpected structure.
102-Invalid input error.
32.12.5 Platform Availability
Available on all platforms.
32.12.6 JavaScript Example
In this example, kony.string.containsOnlyGivenChars returns true only if the input string consists the characters specified in the characterArray. For example, since the input string "abdcdADV" consists only the characters specified in the character array, kony.string.containsOnlyGivenChars returns true.
//Test case where API returns true var inputStr = "abdcdADV"; var charsArr = ["a","b", "d", "c", "A", "D", "V"]; var resultantString = kony.string.containsOnlyGivenChars
(inputStr,charsArr); frmContainsOnlyGivenChars.containsOnlyGivenCharsLabel.text = resultantString;
//Test case where API returns false var inputStr = "abdcdADH";
© 2015 by Kony, Inc. All rights reserved 658 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
var charsArr = ["a","b", "d", "c", "A", "D", "V"]; var resultantString = kony.string.containsOnlyGivenChars
(inputStr,charsArr); frmContainsOnlyGivenChars.containsOnlyGivenCharsLabel.text = resultantString;
32.13 kony.string.containsNoGivenChars
This API verifies that the input string does not contain any of the specified characters and returns a boolean value.
32.13.1 Signature
JavaScript:
kony.string.containsNoGivenChars ( inputstring , charsArray
)
32.13.2 Input Parameters inputstring [String] - Mandatory
Specifies the input string that needs to be verified.
charsArray [Array] - Mandatory
Specifies the set of characters that need to be searched within the input string.
32.13.3 Return Values status [Boolean] true - if the given input string contains none of the characters in the specified list.
false - if there is an error in the input or if the given input string contains any of the specified input characters.
32.13.4 Exceptions
An error is thrown if input type is invalid or follows an unexpected structure.
© 2015 by Kony, Inc. All rights reserved 659 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
102-Invalid input error.
32.13.5 Platform Availability
Available on all platforms.
32.13.6 JavaScript Example
In this example, kony.string.containsNoGivenChars returns true only if the input string does not consist the characters specified in the characterArray. For example, since the input string "abdcdADV" consists none of the characters specified in the character array, kony.string.containsNoGivenChars
returns true.
var inputstring = "abdcdADV"; var charsArr = ["|","-"]; kony.print(kony.string.containsNoGivenChars(inputstring, charsArr));
//prints true as string does not contain the given characters
(| and - are NOT contained in the input) var inputstring = "abdcd|ADV"; var charsArr = ["|","-", "a" ]; kony.print(kony.string.containsNoGivenChars(inputstring, charsArr));
//prints false as string contains the given character "a".
32.14 kony.string.isValidEmail
This API verifies if the input string is a valid email address and returns a boolean value.
32.14.1 Signature
JavaScript: kony.string.isValidEmail (
)
© 2015 by Kony, Inc. All rights reserved 660 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.14.2 Input Parameters inputstring [String] - Mandatory
Specifies the input string that needs to be verified if it is a valid email address.
32.14.3 Return Values status [Boolean] true - if the given input string satisfies the email rules and is a valid email address.
false - if there is an error in the input or if the given input string does not satisfy email rules.
32.14.4 Rules and Restrictions
The API performs the following validations on the input string: l has at least 6 characters.
l has @.
l has at least 4 characters after @.
l has . (dot) followed by at least 2 characters.
l has at least 1 character before @.
32.14.5 Exceptions
An error is thrown if input type is invalid or follows an unexpected structure.
32.14.6 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 661 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.14.7 JavaScript Example
In this example, kony.string.isValidEmail returns true only if the input string comprises a valid email address.
var inputstring = "abcd@"; kony.print(kony.string.IsValidEmail(inputstring));
//prints false as there are no chars after @ var inputstring = "abcd@tccc" kony.print(kony.string.IsValidEmail(inputstring));
//prints false as the chars after @ does not have . followed by at least 2 chars
32.15 Deprecated APIs
The following APIs are deprecated in JavaScript: l
l
l
l
l
l
l
l
© 2015 by Kony, Inc. All rights reserved 662 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.16 string.compare
This API compares the contents of two strings numerically. For example, "Adam" is smaller than
"adam" as per the ASCII table because A(65) is smaller than a(97).
32.16.1 Signature
JavaScript: Deprecated. Use less-than and greater-than operators for comparing strings instead.
32.16.2 Return Values
Status [Number]: status of the compare operation l
1 - s1 > s2 l
0 - s1 = s2 l
-1 - s1 < s2
32.16.3 Platform Availability
Available on all platforms.
32.17 string.charat
This API returns a string which contains a single character from the source string at the specified index.
32.17.1 API Signature
JavaScript: Deprecated. Use the charAt() string object method
© 2015 by Kony, Inc. All rights reserved 663 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.17.2 Return Values character [String]
Character at the specified index in the source string.
nil index is lesser or greater than the length of the source string
32.17.3 Platform Availability
Available on all platforms.
32.18 string.len
This API returns the length of the source string.
32.18.1 Signature
JavaScript: Deprecated. Use the length string object property instead.
32.18.2 Return Values length [Number]
The value returned is the length of the source string
32.18.3 Rules and Restrictions
If the input string has an escape character in it, this API returns the length of the string as 0.
32.18.4 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 664 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.19 string.lower
This API changes the upper case characters of the source string to lower case characters.
32.19.1 Signature
JavaScript: Deprecated. Use toLowerCase() string object method instead
32.19.2 Return Values lower case [String]
A string containing lower case characters is returned.
32.19.3 Platform Availability
Available on all platforms
32.20 string.upper
This API changes the lower case characters of the source string to upper case characters.
32.20.1 Signature
JavaScript: Deprecated. Use the toUpperCase() string object method instead.
32.20.2 Return Values upper case [String]
A string containing upper case characters is returned
32.20.3 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 665 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.21 string.sub
This API returns the substring of the source string.
32.21.1 Signature
JavaScript: Deprecated. Use the substring() string object method instead.
32.21.2 Return Values substring [String]
The substring of the source string is returned.
If j is not given, the substring will begin from the character specified in i and ends at the end of the source string.
If j is given, the substring will begin from the character specified in i and ends at the character specified in j and includes j.
32.21.3 Platform Availability
Available on all platforms.
32.22 string.split
This API splits the source string based on the separator (default is comma) and returns a table containing the string.
32.22.1 Signature
JavaScript: Deprecated. Use the split() string object method instead.
32.22.2 Return Values l
A Table containing the string is returned.
© 2015 by Kony, Inc. All rights reserved 666 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.22.3 Platform Availability
Available on all platforms.
32.23 string.find
This API finds the first occurrence of the search string in the source string.
32.23.1 Signature
JavaScript: Deprecated. Use the indexOf() object method instead.
32.23.2 Return Values
Start Position [Number]
The search string is found and the start position of the search string is returned nil
The search string is not found
32.23.3 Platform Availability
Available on all platforms.
32.24 string.replace
This API finds and replaces the occurrences of a string in the source string with a string you specify.
32.24.1 Signature
JavaScript: Deprecated. Use the replace() string object method instead.
© 2015 by Kony, Inc. All rights reserved 667 of 848
32. String APIs Kony Studio API Developer's Guide
Version 5.0
32.24.2 Return Values modified string [String]
All occurrences of the string specified in the find parameter are replaced with the string specified in the replace parameter
32.24.3 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 668 of 848
33. Sync APIs Kony Studio API Developer's Guide
Version 5.0
33. Sync APIs
Sync Client ORM API Guide lists the set of APIs that you can use to perform various operations on
Kony Sync. You can use the Sync APIs on the application level or on the Object Level.
Refer the Sync APIs documented in Sync Client ORM API Guide: http://docs.kony.com/konylibrary/sync/kmf_sync_orm_api_guide/Default.htm
© 2015 by Kony, Inc. All rights reserved 669 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34. Table APIs
This library provides generic functions for table manipulation. It provides all its functions inside the table.
Most functions in the Table library assume that the table represents an array or a list. For these functions, when we talk about the "length" of a table we mean the result of the length operator.
Note: This library is also available in JavaScript under the namespace kony.table.
Note: If you are developing a new application in JavaScript we recommend using the Array and
JSObject structures.
34.1 table.concat
This API extracts all the elements of a table and concatenates the elements to form a string. A separator can be specified which can be placed between concatenated elements.
34.1.1 Signature
JavaScript: kony.table.concat (
)
34.1.2 Input Parameters inputtable [Table] - Mandatory
Specifies the input table from which the elements will be concatenated.
Note: Elements other than string, number, and Boolean are ignored.
separator [String] - Optional
Specifies the separator character that needs to be inserted between the concatenated elements
© 2015 by Kony, Inc. All rights reserved 670 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
startposition [Number] - Optional
Specifies the start index within the table from which the elements need to be taken for concatenation. If you do not specify the end position the default value is the last index.
Note: 0 <startposition < endposition endposition [Number] - Optional
Specifies the end index within the table till which the elements need to be taken for concatenation.
If you do not specify the startposition the default value is the first index.
Note: 0 < endposition < length of input table
34.1.3 Return Values
ConcatenatedString [Object]
All the elements of a table concatenated to form a string nil nil is returned if there is an error in the input parameters or executing this API
34.1.4 Error Codes l
100 - invalid arguments l
101 - internal error
34.1.5 Platform Availability
Available on all platforms.
© 2015 by Kony, Inc. All rights reserved 671 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.2 table.sort
This API sorts the elements of the input table and returns the modified table. This API sorts only the list part of the table and the hash part of the table is ignored.
34.2.1 Signature
JavaScript: kony.table.sort (
,
,
)
34.2.2 Input Parameters inputtable [Table] - Mandatory
Specifies the input table that needs to be sorted.
sortkey [String] - Optional
Specifies the key based on which the table needs to be sorted comparisonfunction [Function] - Optional
Specifies the comparison function that is called every time the sort algorithm tries to compare two elements in the table
34.2.3 Return Values
Modified table [Table]
A modified table that has been sorted is returned
Important: The input table is modified and is returned.
34.2.4 Error Codes l
100 - invalid arguments l
101 - internal error
© 2015 by Kony, Inc. All rights reserved 672 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.2.5 Platform Availability
Available on all platforms.
34.3 table.insert
This API inserts a specified value into the given table in the list part. If a position is specified, the value is inserted before the element currently at that position. If no position is specified, the value is appended to the end of the table. If the specified position is not within the range of the list part of the table, the new element is added to the hash part of the table.
34.3.1 Signature
JavaScript:
kony.table.insert ( inputtable
,
)
34.3.2 Input Parameters inputtable [Table] - Mandatory
Specifies the input table into which the given value needs to be inserted. The input table is modified.
position [Number] - Optional
Specifies the index of the table before which the given value needs to be inserted.
value [Userdata] - Mandatory
Specifies the value that needs to be inserted into the given input table
34.3.3 Return Values
None
© 2015 by Kony, Inc. All rights reserved 673 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.3.4 Error Codes l
100 - invalid arguments l
101 - internal error
34.3.5 Platform Availability
Available on all platforms.
34.4 table.remove
This API removes an element from the list part of the table. If a position is specified, the element at the position is removed. If no position is specified, the last element in the table is removed. The removed element is returned. This API operates only on the list part of the table.
34.4.1 Signature
JavaScript: kony.table.remove (
)
34.4.2 Input Parameters inputtable [Table]- Mandatory
Specifies the input table from which the element needs to be removed.
position [Number]- Optional
Specifies the index of the input table from where the element needs to be removed. Position must be greater than zero and less than the length of the input table.
Note: If position is greater than the size of the table, the input table is not modified and returns an error with error code 100.
© 2015 by Kony, Inc. All rights reserved 674 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.4.3 Return Values
Removed element
The element that has been removed from the input table is returned
34.4.4 Error Codes l
100 - invalid arguments l
101 - internal error
34.4.5 Platform Availability
Available on all platforms.
34.5 unpack
This API returns the elements from the given table. This function is equivalent to
return list[i], list[i+1], .... list[j]
.
34.5.1 Signature
JavaScript:
kony.table.unpack ( inputtable
)
34.5.2 Input Parameters inputtable [Table] - Mandatory
Specifies the input table that needs to be iterated
34.5.3 Return Values
Returns a list of elements from a given table. If a table has 5 elements, a list of 5 elements will be returned.
© 2015 by Kony, Inc. All rights reserved 675 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.5.4 Error Codes l
100 - invalid arguments l
101 - internal error
34.5.5 Implementation Details
You can achieve the same functionality by writing a custom function that displays all the elements of a table.
34.5.6 Platform Availability
Available on all platforms.
34.6 table.filter
This API filters the given table based on the provided criteria and returns a set of values that match the given criteria.
34.6.1 Signature
JavaScript: kony.table.filter (
inputtable , criteriafunction )
34.6.2 Input Parameters inputtable [Table] - Mandatory
Specifies the table that needs to be filtered criteriafunction [Function] - Mandatory
Specifies the function that defines the criteria for filtering
© 2015 by Kony, Inc. All rights reserved 676 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.6.3 Return Values
Modified table [Table]
A modified table is returned if the API is successfully executed for every element in the table nil nil is returned if there is an error in the input parameters or executing this API
34.6.4 Error Codes l
100 - invalid arguments l
101 - internal error
34.6.5 Platform Availability
Available on all platforms.
34.7 table.map
This API performs the given action on the input table and returns the modified table.
34.7.1 Signature
JavaScript: : kony.table.map (
inputtable , criteriafunction )
34.7.2 Input Parameters inputtable [Table] - Mandatory
Specifies the table on which the action needs to be performed.
criteriafunction [Function] - Mandatory
Specifies the function that defines the criteria for performing action on the table.
© 2015 by Kony, Inc. All rights reserved 677 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.7.3 Return Values
Modified table [Table]
A modified table is returned if the API is successfully executed for every element in the table nil nil is returned if there is an error in the input parameters or executing this API
34.7.4 Error Codes l
100 - invalid arguments l
101 - internal error
34.7.5 Platform Availability
Available on all platforms.
34.8 table.mapnew
This API performs the given action on the input table and returns a new table.
34.8.1 Signature
JavaScript:
kony.table.mapnew ( inputtable
,
)
34.8.2 Input Parameters inputtable [Table] - Mandatory
Specifies the table on which the action needs to be performed criteriafunction [Function] - Mandatory
Specifies the function that defines the criteria for performing action on the table.
© 2015 by Kony, Inc. All rights reserved 678 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.8.3 Return Values
New table [Table]
A new table is returned if the API is successfully executed for every element in the table nil nil is returned if there is an error in the input parameters or executing this API
34.8.4 Error Codes
The following error codes are returned: l
100 - invalid arguments l
101 - internal error
34.8.5 Platform Availability
Available on all platforms.
34.9 table.get
This API searches the given input table and returns the value at the specified key; if the key is a number, this API returns the value at the index.
34.9.1 Signature
JavaScript: kony.table.get (
34.9.2 Input Parameters inputtable [Table] - Mandatory
Specifies the table on which the search should be performed
© 2015 by Kony, Inc. All rights reserved 679 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
index [Number]- Mandatory
Specifies the key based on which the search will be done
Note: index can be a string or a number.
34.9.3 Return Values
Value [String]
If the key is a string, value corresponding to the specified key is returned
If the key is a number, value at the specified index is returned nil nil is returned if there is an error in the input parameters or executing this API
34.9.4 Error Codes l
100 - invalid arguments l
101 - internal error l
0 - invalid key
34.9.5 Platform Availability
Available on all platforms
34.10 table.contains
Tests if the specified key is part of the table.
34.10.1 Signature
JavaScript:
kony.table.contains ( inputtable
,
)
© 2015 by Kony, Inc. All rights reserved 680 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.10.2 Input Parameters inputtable [Table] - Mandatory
Specifies the table within which the search is to be made key - Mandatory
Specifies the key that needs to be searched in the given table
Note: key can be a string or a number.
34.10.3 Return Values status [Boolean] true - if the specified key is found in the input table false - if there is an error in the input parameters or the input table does not contain the specified key
34.10.4 Error Codes l
100 - invalid arguments l
101 - internal error
34.10.5 Platform Availability
Available on all platforms.
34.11 table.append
This API appends the content of the source table to the target table and returns the modified target table.
© 2015 by Kony, Inc. All rights reserved 681 of 848
34. Table APIs Kony Studio API Developer's Guide
Version 5.0
34.11.1 Signature
JavaScript:
kony.table.append ( targettable , sourcetable )
34.11.2 Input Parameters targettable [Table] - Mandatory
Specifies the target table to which the source table will be appended sourcetable [Table] - Mandatory
Specifies the source table that needs to be appended to the target table
34.11.3 Return Values
Modified table [Table]
A modified table is returned, if the input data was appended to the given table.
nil nil is returned if there is an error in the input parameters or executing this API
34.11.4 Error Codes l
100 - invalid arguments l
101 - internal error
34.11.5 Platform Availability
Available on all platforms.
34.12 table.removeall
This API removes data from the table represented by the table id.
© 2015 by Kony, Inc. All rights reserved 682 of 848
34. Table APIs
34.12.1 Signature
JavaScript: kony.table.removeAll (
)
34.12.2 Input Parameters tableid [String] - Mandatory
Specifies the table id whose data needs to be deleted
34.12.3 Return Values
None.
34.12.4 Error Codes
There are no error codes associated with this API.
34.12.5 Platform Availability
Available on all platforms.
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 683 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35. Theme APIs
Theme is a set of skins available at the application level. Themes let you specify common skins for widgets in different states (normal, focus, and so on).
You can define your own themes in Kony Studio or download themes from the network (a specific
URL) and use them in the application.
A theme, which consists of a set of skins, is represented as a file containing a JSON string. The JSON string has the key-value pairs in which the key is skinid and the value is JSON string that represents the skin.
Note: Every application should have a "default" theme (stored in the in the default.theme
file).Deleting or overriding the contents of this file will lead to undesired behavior. Kony Studio does not allow the developer to delete this theme. All other user defined themes can be deleted.
The following APIs are explained in the sections: l
l
l
kony.theme.createThemeFromJSONString
l
l
l
kony.theme.getCurrentThemeData
l
l
© 2015 by Kony, Inc. All rights reserved 684 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.1 Use Cases
l
Themes allow you to package the skins in a way that resemble a particular user interface or branding for a particular set of users. For example, all the Gold customers will see all the buttons in Golden Yellow color.
l
Themes allow you to personalize the look and feel of the application for the end users. For example, the users can choose between a green theme or a blue theme.
l
Themes, when downloaded over the network, allow to remotely control the branding of the native application. For example, during the Christmas season, the marketing or the branding team can push a Christmas Theme to the native application.
35.2 Prerequisites
The themes or the skins must be pre-defined in the IDE or should have been downloaded over the network.
35.2.1 Capabilities
The theme APIs provided by Kony Platform have the following capabilities: l
Defining new themes.
l
Applying the theme to the application or only for the current session.
l
Switching the application from one theme to another theme dynamically.
l
Deleting and loading the skins for memory efficiency.
l
Provision for custom meta data.
© 2015 by Kony, Inc. All rights reserved 685 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.2.2 Important Considerations l
The default theme is the base-point for new theme.
l
If the referred skin does not exist both in the current theme and default theme, a runtime error occurs.
l
When a skin is referred, the IDE searches for the skin in the order of precedence) o
Current theme o
Default theme.
35.2.3 Important Considerations for SPA, Desktop Web, and Mobile Web l
For the SPA, Desktop Web and Mobile Web platforms, the theme files should be CSS files. It cannot accept the theme files as JSON files. If the project is developed using IDE, the platform automatically generates CSS files for the above platforms based on the skins/themes defined by the developer in the IDE. The css files will be generated under "<ThemeID>" folder.
Note: The names of the css files in the theme are same as the css files in the normal build.
l
For those customers/developers, interested in developing applications without IDE, the platform will provide an offline tool to convert a given .theme JSON file into corresponding CSS file. This will be provided post 5.0.
l
For the createTheme API, ensure that the URL mentioned in the createTheme API should point only to a CSS file. The platforms do not support a URL with a .Theme file and convert it into a
CSS file at run time.
l getCurrentThemeData will always return null. As theme files are converted into CSS, the platforms cannot have custom structures/variables in CSS files as browsers fail to parse them.
© 2015 by Kony, Inc. All rights reserved 686 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
l
Do the above platforms support skin level fallback?
The platforms expect each theme file i.e
. CSS file to have all the skins. In the case of projects developed in IDE the platform takes care of skin conversion of this during generation. For customers, hand coding the application, the above mentioned tool should take care of that. But essentially at run time the platforms cannot look up into multiple CSS's and check for a class.
Technically it is possible to do so but it requires the platform to load multiple CSS files and in a specific order. Adding new downloads is an always avoidable and we intend to handle this during the generation of the CSS file itself.
35.2.4 Limitations
You cannot dynamically modify the skin attributes.
35.3 kony.theme.setCurrentTheme
This API allows you to apply a specified theme to the application at runtime.
35.3.1 Signature
JavaScript : kony.theme.setCurrentTheme (
,
,
)
35.3.2 Input Parameters themeidentifier [String] - Mandatory
Specifies a string that denotes the theme ID. The specified theme is applied to the application.
onsuccesscallback [Function] - Mandatory
Specifies the callback function that needs to be executed in case of success. This callback function is executed after applying the specified theme.
onerrorcallback [Function] - Mandatory
Specifies the callback function that needs to be executed in case of error. This callback function has the following parameters:
© 2015 by Kony, Inc. All rights reserved 687 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
l errorcode - the error code thrown if there was a problem while applying the specified theme l errormessage - the error message that corresponds to the error code.
This callback function is executed if there is an error while applying the specified theme.
35.3.3 Exceptions o
1900- SkinError. This error occurs when there is an error related to skin.
o
Error - This error is thrown when there is a generic error.
35.3.4 Platform Availability
Available on all platforms.
35.3.5 JavaScript Example function onsuccesscallback()
{ alert("successfully set the theme to app")
} function onerrorcallback(1900, "Skin Error")
{ alert("Skin does not exist")
} kony.theme.setCurrentTheme("red",onsuccesscallback,onerrorcallback);
35.4 kony.theme.createTheme
This API enables you to create a theme.
© 2015 by Kony, Inc. All rights reserved 688 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.4.1 Signature
JavaScript : kony.theme.createTheme(
,
,
,
)
35.4.2 Input Parameters url [String] - Mandatory
Specifies a string (URL) from which the theme is to be downloaded. The theme is represented as a JSON object.
Note: If the JSON object contains invalid skin attributes, the platforms use the default attributes (platform specific and may vary from platform to platform).
themeIdentifier [String] - Mandatory
Specifies a flag that indicates if the current theme must be replaced with the same identifier or use the theme only in the current session.
onsuccesscallback [Function]-Mandatory
Specifies the callback function that needs to be executed in case of success. This callback function is executed after the theme is created.
onerrorcallback [Function] - Mandatory
Specifies the callback function that needs to be executed in case of error. This callback function has the following signature: onerrorcallback (errorcode,errormessage) l errorcode - the error code thrown if there was a problem while creating the theme l errormessage - the error message that corresponds to the error code.
© 2015 by Kony, Inc. All rights reserved 689 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.4.3 Exceptions o
1900- SkinError. This error occurs when there is an error related to skin.
o
Error - This error is thrown when there is a generic error.
35.4.4 Platform Availability
Available on all platforms except BlackBerry 10.
For SPA, Desktop Web, and Mobile Web ensure that the URL mentioned in the createTheme API should point only to a CSS file. The platforms do not support a URL with a .Theme file and convert it into a CSS file at run time.
35.4.5 JavaScript Example function onsuccesscallback()
{ alert("successfully set the theme to app")
} function onerrorcallback()
{ alert("Theme is not set to the app")
} kony.theme.createTheme("", "Mytheme", onsuccesscreatecallback,onerrorcreatecallback);
35.5 kony.theme.createThemeFromJSONString
This API enables you to create or replace a JSON string theme in the current session.
© 2015 by Kony, Inc. All rights reserved 690 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.5.1 Signature
JavaScript
: kony.theme.createThemeFromJSONString( jsonString , themeIdentifier , onsuccesscallback
,
)
35.5.2 Input Parameters jsonString [String] - Mandatory
A well defined theme JSON string with which theme is created. The theme is represented as a
JSON object.
Note: If the JSON object contains invalid skin attributes, the platforms use the default attributes (platform specific and may vary from platform to platform).
themeIdentifier [String] - Mandatory
Specifies an identifier with which current theme must be created or replace if the theme is already exists and this theme will be available only in the current session.
Note: The theme will not be created and an error callback is called, if null or undefined or non-string themeIdentifier is provided.
onsuccesscallback [Function]- Optional
Specifies the callback function that needs to be executed in case of success. This callback function is executed after the theme is created.
Note: The theme will be created but the successcallback is not called, if null or undefined successcallback is provided.
onerrorcallback [Function] - Optional
Specifies the callback function that needs to be executed in case of error. This callback function has the following signature:
© 2015 by Kony, Inc. All rights reserved 691 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
onerrorcallback (errorcode,errormessage) l errorcode - the error code thrown if there was a problem while creating the theme l errormessage - the error message that corresponds to the error code.
35.5.3 Exceptions o
1900- SkinError. This error occurs when there is an error related to skin.
o
Error - This error is thrown when there is a generic error.
35.5.4 Platform Availability
Available on iOS, Android, and Windows platforms.
35.5.5 JavaScript Example function testCreateThemeFormJSONString() { function onsuccesscallback() { alert("successfully created theme.")
} function onerrorcallback(errorcode, errormessage) { alert("Unable to create theme.")
} var jsonString = '{"btnNormal": { "wtype":"Button","bg_type" :
"one","background_color" : "ff000000","font_weight" : "bold","font_ size" : 120,"font_color" : "314e8900","font_name" : "Arial-
BoldMT","border_color" : "9f9f9f00","border_width" : 1,"border_ style" : "rc","shadow" :
{"x":0,"y":0,"br":0,"color":"00000000","inner":false},"text_shadow"
© 2015 by Kony, Inc. All rights reserved 692 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
:{"x":0,"y":0,"br":0,"color":"00000000"}}}'; kony.theme.createThemeFromJSONString(jsonString, "MyTheme1", onsuccesscallback, onerrorcallback);
}
35.6 kony.theme.isThemePresent
This API allows you to check the existence of specific theme in the application.
35.6.1 Signature
JavaScript: kony.theme.isThemePresent(
35.6.2 Input Parameters themeidentifier [String] - Mandatory
Specifies a string that represents a theme.
35.6.3 Return Values status [Boolean]
Returns the status of the execution of this API.
l true - if the specified theme is present in the application.
l false - if the specified theme does not exist in the application.
35.6.4 Exceptions o 1900- SkinError. This error occurs when there is an error related to skin.
o
Error - This error is thrown when there is a generic error.
© 2015 by Kony, Inc. All rights reserved 693 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.6.5 Platform Availability
Available on all platforms
35.6.6 JavaScript Example var isThemePresent=kony.theme.isThemePresent("green"); alert("IS theme present ? True/False: "+isThemePresent);
35.7 kony.theme.getAllThemes
This API returns all the themes available in the application.
35.7.1 Signature
JavaScript : kony.theme.getAllThemes()
35.7.2 Input Parameters
None
35.7.3 Return Values
JavaScript: Array
Returns an array with a list of all theme Identifiers available in the application.
35.7.4 Exceptions o 1900- SkinError. This error occurs when there is an error related to skin.
o
Error - This error is thrown when there is a generic error.
© 2015 by Kony, Inc. All rights reserved 694 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.7.5 Platform Availability
Available on all platforms.
35.7.6 JavaScript Example var themes=kony.theme.getAllThemes(); alert("No Of themes are "+themes.length);
35.8 kony.theme.getCurrentThemeData
This API returns the meta data of the current theme in the application.
35.8.1 Signature
JavaScript: kony.theme.getCurrentThemeData()
35.8.2 Input Parameters
None
35.8.3 Return Values metadata [Object]
Returns an object that contains the metadata of the current theme in the application
35.8.4 Exceptions o 1900- SkinError. This error occurs when there is an error related to skin.
o
Error - This error is thrown when there is a generic error.
© 2015 by Kony, Inc. All rights reserved 695 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.8.5 Platform Availability
Available on all platforms except SPA, and Mobile Web.
For SPA, Desktop Web, Windows 7 Kiosk, and Mobile Web, this API will always return null. As theme files are converted into CSS, the platforms cannot have custom structures/variables in CSS files as browsers will fail to parse them.
35.8.6 JavaScript Example var crntThemeData=kony.theme.getCurrentThemeData(); alert("Current Theme Data is :"+crntThemeData);
35.9 kony.theme.getCurrentTheme
This API returns the current theme that is applied to the application.
35.9.1 Signature
JavaScript: kony.theme.getCurrentTheme()
35.9.2 Input Parameters
None
35.9.3 Return Values themeID[String]
Returns the identifier of the current theme that is applied to the application
© 2015 by Kony, Inc. All rights reserved 696 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.9.4 Exceptions o
1900- SkinError. This error occurs when there is an error related to skin.
o
Error - This error is thrown when there is a generic error.
35.9.5 Platform Availability
Available on all platforms.
35.9.6 JavaScript Example var crntTheme=kony.theme.getCurrentTheme(); alert("current theme is:"+crntTheme+" And the type is "+typeof
(crntTheme));
35.10 kony.theme.deleteTheme
This API allows you to delete a specified theme in the application programmatically.
Important: l
On all Platforms, pre-bundled themes in the application cannot be deleted, but only the themes created through createTheme API, which are in memory, can be deleted.
l
On Windows Platforms, only the themes created using the createTheme API can be deleted.
Pre-bundled themes and currently used theme cannot be deleted.
35.10.1 Signature
JavaScript : kony.theme.deleteTheme(
,
,
© 2015 by Kony, Inc. All rights reserved 697 of 848
35. Theme APIs Kony Studio API Developer's Guide
Version 5.0
35.10.2 Input Parameters themeidentifier [String] - Mandatory
Specifies a string that denotes the theme ID. The specified theme will be deleted from the application.
onsuccesscallback [Function] - Mandatory
Specifies the callback function that needs to be executed in case of success. This callback function is executed after the theme is deleted.
onerrorcallback [Function] - Mandatory
Specifies the callback function that needs to be executed in case of error. This callback function has the following signature: onerrorcallback (errorcode,errormessage) l errorcode - the error code thrown if there was a problem while creating the theme l errormessage - the error message that corresponds to the error code.
35.10.3 Exceptions o
1900- SkinError. This error occurs when there is an error related to skin.
o
Error - This error is thrown when there is a generic error.
35.10.4 Platform Availability
Available on all platforms except Server side Mobile Web.
35.10.5 JavaScript Example kony.theme.deleteTheme ("green");
© 2015 by Kony, Inc. All rights reserved 698 of 848
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 699 of 848
36. Threading APIs Kony Studio API Developer's Guide
Version 5.0
36. Threading APIs
A subset of native APIs runs only on the main or UI thread. In a Kony application, the bulk of
JavaScript code runs on a VM thread (also called a closure thread). Threading APIs help JavaScript bindings work on main thread. When the code completes its run on the main thread, you need a mechanism to resume JavaScript execution on the VM thread.
The Threading APIs are: l
l
36.1 kony.runOnMainThread
This API helps you run the JavaScript code on the main thread. It is an asynchronous API. It posts a message to the main thread to invoke a function f with parameters arguments.
Note: If runonMainThread is invoked in a JavaScript function that is already running on the main thread, then the function is executed in synchronous mode.
36.1.1 Signature
JavaScript: kony.runOnMainThread (f, args)
36.1.2 Input Parameters f [Function] - Mandatory
Specifies the callback function that must be executed.
args [Array] - Mandatory
Specifies the JavaScript array that holds the parameters to be passed to function f.
© 2015 by Kony, Inc. All rights reserved 700 of 848
36. Threading APIs Kony Studio API Developer's Guide
Version 5.0
36.1.3 Return Values
None
36.1.4 Platform Availability
Available on iOS platform
36.1.5 JavaScript Example
//Example to be added
36.2 kony.runOnWorkerThread
This API helps you run the JavaScript code on the worker thread. It is an asynchronous API. It posts a message to the worker thread that owns the current JavaScript context to invoke a function f with parameters arguments.
Note: The assumption here is that main thread does not own any JavaScript context. The
VM/closure thread and worker threads own the JavaScript context. When the kony.runOnWorkerThread
is invoked from the main thread, a message is posted to the thread that originally invoked the kony.runOnMainThread. If the runonWorkerThread is invoked in a JavaScript function that is already running on the worker thread, then the function would be executed in synchronous mode.
36.2.1 Signature
JavaScript: kony.runOnWorkerThread (f, args)
© 2015 by Kony, Inc. All rights reserved 701 of 848
36. Threading APIs Kony Studio API Developer's Guide
Version 5.0
36.2.2 Input Parameters f [Function] - Mandatory
Specifies the callback function that must be executed.
args [Array] - Mandatory
Specifies the JavaScript array that holds the parameters to be passed to f.
36.2.3 Return Values
None
36.2.4 Platform Availability
Available on iOS platform
36.2.5 JavaScript Example
//Example to be added
© 2015 by Kony, Inc. All rights reserved 702 of 848
37. Guidelines for using Threading APIs Kony Studio API Developer's Guide
Version 5.0
37. Guidelines for using Threading APIs
To use Threading APIs in Kony Studio, follow the guidelines: l
Threading APIs natively support multi-threading environment.
l
An application can be composed of multiple concurrent threads.
l
The UI or main thread is responsible for dispatching events to the user interface widgets and drawing the elements of the UI.
l
Do not block the UI thread. Performing long operations, like network access or database queries on the UI thread, will block the user interface.
l
Do not access the UI components from outside the UI thread. l
JavaScript Thread: l
Application logic written in JavaScript that does not require UI update executes in a different thread than the Main or UI thread.
l
Operations that update the UI are posted on to the Main or UI thread.
l
Use the API kony.runOnMainThread(function, args) to execute JavaScript bindings and JavaScript logic on UI Thread.
© 2015 by Kony, Inc. All rights reserved 703 of 848
38. Timer APIs Kony Studio API Developer's Guide
Version 5.0
38. Timer APIs
The APIs in this library provide you the ability to schedule the execution of a function block at regular intervals. The namespace for TimerAPI is kony.timer.
The timer APIs are as follows: l
l
l
38.1 kony.timer.schedule
This API executes the given function after a specified interval of time.
38.1.1 Use Cases
You can use this API when you want to execute a function after a specified interval of time. i.e, for example to run a specific function for every 15 seconds.
38.1.2 Signature
JavaScript: kony.timer.schedule(
,
,
)
38.1.3 Input Parameters timerid [String] - Mandatory
Specifies the unique ID that identifies the timer.
functionObj [Function] - Mandatory
Specifies the function that needs to be executed.
© 2015 by Kony, Inc. All rights reserved 704 of 848
38. Timer APIs Kony Studio API Developer's Guide
Version 5.0
interval [Number] - Mandatory
Specifies the time in seconds after which the function needs to be executed.
repeat [Boolean] - Mandatory
Specifies a flag that indicates if the function needs to executed once or repeated.
l true - indicates that the execution of the function needs to repeated at regular intervals l false - indicates that the function needs to be executed just once
38.1.4 Return Values
None
38.1.5 Exceptions
Error
38.1.6 Platform Availability
Available on all platforms*. *Dummy Implementation on Mobile Web.
38.1.7 JavaScript Example function timerFunc() //nested function
{ i=i+5; lbl1.text = i+" secs ";
} kony.timer.schedule("mytimer12",timerFunc, 5, true);
//The function timerFunc will be executed after every 5 seconds.
© 2015 by Kony, Inc. All rights reserved 705 of 848
38. Timer APIs Kony Studio API Developer's Guide
Version 5.0
38.2 kony.timer.cancel
This API cancels the timer that has already been scheduled for execution.
38.2.1 Signature
JavaScript: kony.timer.cancel(
)
38.2.2 Input Parameters timerid [String] - Mandatory
Specifies the unique ID that identifies the timer that needs to be canceled.
38.2.3 Return Values
None
38.2.4 Exceptions
Error
38.2.5 Error Codes l
100 - invalid arguments l
101 - internal error
38.2.6 Implementation Details
If the timer is waiting to be run, it will not be run the next time. If the timer is in the middle of execution, it will be allowed to complete and then canceled.
38.2.7 Platform Availability
Available on all platforms*. *Dummy Implementation on Mobile Web.
© 2015 by Kony, Inc. All rights reserved 706 of 848
38. Timer APIs Kony Studio API Developer's Guide
Version 5.0
38.2.8 JavaScript Example function buttoncallback2()
{ try
{ kony.timer.cancel("mytimer");
} catch(err)
{ alert("error in second button onclick and err is:: "+err);
}
}
38.3 kony.timer.setCallBack
This API specifies the callback function that needs to be executed for a scheduled timer. The callback function handles the logic that needs to be executed after a scheduled timer was run successfully or the scheduled timer failed to execute. The setCallBack timer API is provided to override the existing time call back function which is defined in the "schedule" timer API.
38.3.1 Signature
JavaScript: kony.timer.setCallBack(
)
38.3.2 Input Parameters timerid [String] - Mandatory
Specifies the unique ID that identifies the timer.
© 2015 by Kony, Inc. All rights reserved 707 of 848
38. Timer APIs Kony Studio API Developer's Guide
Version 5.0
callbackfunction [Function] - Mandatory
Specifies the callback function that needs to be executed.
38.3.3 Return Values
None
38.3.4 Exceptions
Error
38.3.5 Platform Availability
Available on all platforms*. *Dummy Implementation on Mobile Web.
38.3.6 JavaScript Example
//nested function function timerFunc1()
{ alert("Timer invoked");
} kony.timer.setCallBack("mytimer",timerFunc1);
© 2015 by Kony, Inc. All rights reserved 708 of 848
39. Wearables Kony Studio API Developer's Guide
Version 5.0
39. Wearables
Wearables are body-borne miniature electronic devices such as an Apple Watch and Android Wear.
Using an Apple Watch and Android Wear, you can access information quickly without glancing at your phone. When you pair a watch with your phone, you can keep track of calendar appointments, notifications and more from your watch. Based on the action associated with the notification, you can interact with your phone. The benefits of wearables include the ability of employees to access information on the go, increasing productivity with payment processing and so on. Notifications alert a user to an event that might interest the user. For example, you receive a notification of an existing messaging app with action buttons as "reply," "delete," and "ignore." When you click "delete," the delete message is deleted. If you click "reply," the app opens on your watch, and you can reply to the message. The watch acts as an extension of your phone.
© 2015 by Kony, Inc. All rights reserved 709 of 848
Kony Studio API Developer's Guide
Version 5.0
39.1 Supported Platforms and Devices
The following are the supported platforms for wearable using Kony Studio:
Platform iOS
Android
Version l
8.2 and above l
Xcode 6.3 and above
4.4W (API 20) and above
39.1.1 Prerequisites
In the next few sections, you will learn more about Apple Watch and Android Wear. Detains include understanding application architecture, working with Xcode, creating a watch user interface (UI) for
Apple Watch and Android Wear, and designing a sample app.
To create a watch app for iOS and Android: l
You need to be familiar with Xcode and Objective-C to create an Apple Watch app.
l
You must install Kony Studio 6.5 to build a watch app using Kony Studio.
l
You need to access Kony MobileFabric Messaging to test notifications.
The following are the supported functionality and limitations of the wearable in Kony Studio:
Note: Creating a full-fledged watch application is not supported in this release.
l
The addition of custom actions to notifications is supported.
l
Callbacks for custom actions can be configured.
© 2015 by Kony, Inc. All rights reserved 710 of 848
Kony Studio API Developer's Guide
Version 5.0
l
are supported.
l
Packaging of a default application is supported in iOS platform.
l
Only the iOS platform supports background and foreground modes.
l
As per the Android documentation, the format methods in Android - DateFormat class implements a subset of Unicode UTS #35 patterns. The subset currently supported by
DateFormat class with the format characters:acdEHhLKkLMmsyz. Upto API level 17, only adEhkMmszy are supported.
Note: Android - DateFormat class incorrectly implements k as if it were H for backward compatibility. For more information refer to http://developer.android.com/reference/android/text/format/DateFormat.html
and http://developer.android.com/reference/java/text/SimpleDateFormat.html
l
Internationalization is not supported.
l
Customization of the notification view is not supported in Android. For iOS, you can customize in
Xcode.
l
Kony Studio does not support creating the UI for Apple Watch app. You can create the UI through the Xcode interface builder.
l
The business logic of actions associated to the Apple Watch app UI should be written as part of the watch app extension. You can write the logic in Xcode.
l
In iOS platform, invoking the APIs kony.notificationsettings.createAction and kony.notificationsettings.createCategory
multiple times will not overwrite the existing actions and categories.
l
In iOS platform, invoking the API kony.notificationsettings.registerCategory
will remove the earlier registered categories.
© 2015 by Kony, Inc. All rights reserved 711 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2 Apple Watch
Apple Watch is a wearable timepiece, a communication device, and a wellness and fitness tracker.
Apple Watch is designed for the wrist, and a user can access and interact with information at a glance.
An Apple Watch helps you make calls receive messages when paired with the iPhone.
39.2.1 iOS Application Architecture
WatchKit App and WatchKit Extension work together to start your app’s interface. When you interact with your app on an Apple Watch, your WatchKit App chooses the appropriate scene from your storyboards to handle that interaction.
For example, if you view your app’s glance, it chooses your glance scene. After choosing the scene,
WatchKit tells the paired iPhone to launch your WatchKit Extension and create the objects needed to manage that scene. When the scene is fully configured, it is displayed on an Apple Watch. This transfer of information between the WatchKit App and WatchKit Extension happens transparently behind the scenes.
© 2015 by Kony, Inc. All rights reserved 712 of 848
Kony Studio API Developer's Guide
Version 5.0
The Interface Controller
The interface controller object manages your app scenes. An interface controller in WatchKit presents and manages the content on the screen and responds to user interactions. For more information on managing scenes and interface controller, click here .
WatchKit App Life Cycle
You can launch your app, interact with notifications and view your app glances using custom UI. Some interactions launch your WatchKit app and the corresponding WatchKit extension. Your WatchKit app and WatchKit pass information back and forth until you stop interacting with your app. The iOS suspends the extension until the next user interaction.
For more information on WatchKit App architecture, click here .
© 2015 by Kony, Inc. All rights reserved 713 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2.1.1 Communication Between iPhone App and WatchKit Extension
Watch apps that work closely with their containing iOS app can use the openParentApplication:reply: method to send requests to the iOS app and receive a response. When openParentApplication:reply: method is invoked from the WatchKit
Extension, iOS launches the containing iOS app in the background and calls the application:handleWatchKitExtensionRequest:reply: method of its app delegate.
Then, executes the watch callback registered in the setApplicationCallbacks method.
When the app on an Apple Watch needs to perform longer-running background tasks, such as networking calls, rely on you iPhone to do the work. Use the openParentApplication:reply: method in WKInterfaceController to wake up your iPhone app in the background and return the data that your WatchKit extension needs.
The watch callback method that handles the WatchKit request must return immediately.
39.2.1.2 Guidelines for Creating Wearable App
For creating a wearable app, you have to follow certain guidelines while developing a wearable app.
For example, you have to avoid using network calls that take a long time to respond.
39.2.1.3 User Interactions With a Watch App and Associated Workflow l
Interacting with Glance: Glances can only be tapped. On tapping the glance, the associated watch app will open.
l
Interacting with Notifications: You can interact with notifications by tapping on actions. Actions can be configured to execute the business logic in the foreground or background. The foreground mode opens the watch application, and the background mode executes the business logic in the phone app.
l
Interacting with widgets in watch app: Business logic is executed in the WatchKit Extension.
39.2.1.4 Guidelines for Executing Business Logic in Phone Background
When you do not use an app, the system moves the app to the background state. You need to follow certain guidelines to make your app responsive when it is in the background.
© 2015 by Kony, Inc. All rights reserved 714 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2.2 Notifications
Local notifications and remote notifications are the two types of user notifications. Remote notifications are also known as push notifications. For more information on notifications, refer to the following links: l
Notifications l
Testing your notifications l
Notification guidelines l
Dynamic notifications
39.2.3 Glance
A glance quickly convey information. Unlike notifications, glances do not have any buttons and noninteractive. The glance may not be needed for all applications. For more information on glance, click here .
Glance interface controllers are initialized early so that the glance is displayed quickly to the user. You have to follow certain guidelines while creating glance interface. For more information on glance interface guidelines, click here .
© 2015 by Kony, Inc. All rights reserved 715 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2.4 Guidelines for Creating a Wearable UI
You have to follow certain guidelines when you create a user interface (UI) for a Wearable.
The following are a few key elements for designing an Apple Watch:
Designing a Watch: An Apple Watch comes in two sizes — 38mm and 42mm. The smaller screen is
340 pixels by 272 pixels, and the larger one is 390 pixels by 312 pixels. The watch features a retina display, and you must provide images at double the resolution. You need not provide different sized images (although you can), or design two different layouts because Apple uses relative sizing and spacing options so images and objects resize to fill the available space.
App Anatomy: A WatchKit App supports hierarchical and paginated navigation methods.
Glances: Glance is an interface used to display timely and contextual information from the iOS app.
Glances are accessed by swiping upward and then swiping through horizontally. A glance is read-only and will not allow you to work in your app directly. When you tap a glance, the corresponding watch app is launched.
Notifications: The watch app supports local and remote notifications. The two stages of notifications are short look and long look. When you receive a notification, the short-look notification appears. You can add user actions, graphics, and content to notifications.
For more information, refer to the respective links:
Design Elements
Designing for the Watch
App Anatomy
Glances
Notifications iOS
Click here
Click here
Click here
Click here
© 2015 by Kony, Inc. All rights reserved 716 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2.5 How to Create a Sample Watch App on iOS - Example
Let us download and run the sample watch app, test push notifications, and local notifications.
Note: To test notifications, you must have access to the Kony MobileFabric Messaging.
Working with the sample app:
This app is configured to run on your Apple Watch when built using your Xcode. Download the resources anywhere onto your machine.
l
VMAppWithKonylib.zip
: Sample Xcode project, including the code of WearablesTest App.
l
KAR file : Use the KAR file to extract the sample app in Xcode.
To extracting the KAR file, follow these steps:
1. Extract VMAppWithKonylib.zip to a location on your machine.
2. Open the terminal and navigate to the VMAppWithKonylib/gen folder and extract the downloaded WearablesTest App using the Perl extract command.
© 2015 by Kony, Inc. All rights reserved 717 of 848
3. Open the VMAppWithKonylib.xcode project.
Kony Studio API Developer's Guide
Version 5.0
4. In the Xcode, select File > New > Target, and navigate to the Apple Watch section.
© 2015 by Kony, Inc. All rights reserved 718 of 848
5. Select WatchKit App and click Next.
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 719 of 848
Kony Studio API Developer's Guide
Version 5.0
6. To include notifications in your app, select the Include Notification Scene check box.
7. Click Finish. The Xcode configures your project and creates two new targets as
WearablesTest WatchKitApp and WearablesTest WatchKit Extension.
8. To run the watch app, from the scheme menu, select the WearablesTest WatchKit App.
Connect your iPhone to your Mac. Once connected, your iPhone will be displayed in your
Xcode. Select your iPhone from the list of devices and run the project.
© 2015 by Kony, Inc. All rights reserved 720 of 848
Kony Studio API Developer's Guide
Version 5.0
9. The following screen will be displayed on the Apple Watch device.
The above screen shot is taken using the Apple Watch emulator. The same screen should appear in the Apple Watch device.
Note: You can invoke a service call to show emails. In this example, we invoked a service call using kony.store API where the data are stored in the form of key-value pairs.
10. Change the schema and select Notification- WearablesTest WatchKit App. Select your iPhone from the list of devices and run the project. The following screen will be displayed on the
Apple Watch device.
© 2015 by Kony, Inc. All rights reserved 721 of 848
Kony Studio API Developer's Guide
Version 5.0
11. Click on Read Email button. The following screen will be displayed.
The above screen ensures that the Apple Watch Request API is working as expected.
To create actions/categories to send push and local notifications, follow these steps:
1. To test the
and
notification APIs, set the active scheme to KRelease, select your iPhone from the list of devices, and run the project. The WearablesTest app should be deployed onto the iPhone.
2. Open the deployed application. Alerts will be displayed such as "callbacks added," "setCallBack
Done!!!," "application setCallBack for watchkit Extension Done!!!." Click on the OK buttons to dismiss the alerts.
© 2015 by Kony, Inc. All rights reserved 722 of 848
Kony Studio API Developer's Guide
Version 5.0
3. Click on Create Action button. Scroll the form, and notice the following screen.
4. Configure the following properties from the drop-down list and click on Create custom action button.
l authenticationRequired=true l
ActivationMode=backwards l destructive=true
5. An alert will be displayed as “action1 is created.” Click on OK button.
6. Click on Create Category. An alert will be displayed as "Category category1 Created with actions [object CallbackObject]." Click OK.
© 2015 by Kony, Inc. All rights reserved 723 of 848
Kony Studio API Developer's Guide
Version 5.0
7. Now, enable the check boxes NotificationType=Badge,
NotificationType=Sound, and NotificationType=Alert, and click on Register
Category. The category will be registered.
To test the Push Notifications on Apple Watch, follow these steps:
1. From your Xcode, run the WearablesTest WatchKit App. The app will be installed on your iPhone and Apple Watch.
Note: If the app is not installed on your Apple Watch, open the Apple Watch application on your iPhone. When the app launches on your iPhone, look for the app "WearablesTest."
Click on "WearablesTest" app and select the check box "Show App on Apple Watch." Your app will be displayed in Apple Watch.
2. To send the push notifications from your iPhone, open the WearablesTest App. On the home page, click on Push.
3. Click on Register Push. If the registration is successful, a message with the subscription token alerts will be displayed. Now the device is successfully registered to Kony MobileFabric
Messaging.
4. From your browser, go to Kony MobileFabric Messaging. For more information on Kony
MobileFabric Messaging, refer to the installation and user guides. If you are a cloud user, refer to the cloud user guide guide.
5. Log in to Kony MobileFabric Messaging. Click on the Applications tab. The following screen is displayed.
© 2015 by Kony, Inc. All rights reserved 724 of 848
Kony Studio API Developer's Guide
Version 5.0
6. Click on the Adhoc in the Distribution tab. Select the application to be deployed in the Published
Applications drop-down. Select the check box with the subscription token for which the device was registered.
© 2015 by Kony, Inc. All rights reserved 725 of 848
Kony Studio API Developer's Guide
Version 5.0
7. In the Platform Specific Properties under the Apple tab, enter the following details: l
Category: category1 l
Sound Name: default
8. In the Message section enter Title and Message for the notification and click on Send.
A notification will be displayed on the Apple Watch with the message we sent. See the following note as mentioned in the iOS documentation.
Note: Apple Watch takes full advantage of the existing interactive notification support on iOS. If your iOS app supports notifications, Apple Watch displays those notifications at appropriate times.
When one of your app’s local or remote notifications arrives on the user’s iPhone, iOS decides whether to display that notification on the iPhone or on the Apple Watch. For notifications sent to
Apple Watch, the system lets the user know subtly that a notification is available. If the user chooses to view the notification, the system displays an abbreviated version of the notification first, followed by a more detailed version. The user can dismiss the detailed notification, launch your
WatchKit app, or act on the notification by tapping an available action button.
To test the Local Notifications on Apple Watch, follow these steps:
You can send local notifications using
and
© 2015 by Kony, Inc. All rights reserved 726 of 848
Kony Studio API Developer's Guide
Version 5.0
1. From your app home page, click “Set Callbacks” button.
2. Click on “Create Local Notification” button on the home page of the WearablesTest app on the iPhone.
3. Enter the following details and click on Create Local Notification.
a. Select After from the drop-down list.
b. Enter Time(seconds). The notification is sent after the time specified.
c. Enter Enter Category ID as "category1."
4. Close the app by clicking on the device home button and lock the device. After the set time, the local notification is sent to the phone.
5. Click on the action, enter the passcode for the device, and unlock the device.
6. Open the WearablesTest app and click on Go to offline callback. The following screen is displayed.
© 2015 by Kony, Inc. All rights reserved 727 of 848
Kony Studio API Developer's Guide
Version 5.0
© 2015 by Kony, Inc. All rights reserved 728 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2.6 WatchKit Library Util
KonyWatchKitUtil is a library available for Apple Watch application development support from Kony
Studio. This library packages a set of classes that can be used for enabling communication between watch and phone apps, auto-updating the watch app UI, and maintaining the data cache.
The classes of KonyWatchKitUtil library are: l
l
l
KonyWatchKitRequestUtil
KonyWatchKitRequestUtil is a class that helps communication between the WatchKit App and its parent (iPhone) application. The APIs of this class facilitate the communication through the iOS IPC channel between Apple Watch and iPhone. A request, a set of key value pairs, from the Watch App is sent to its parent application. The parent application handles the request and sends the response, a set of key value pairs back to the watch app. The response data obtained from these APIs can be cached using one of the cache policies so that the further fetch data requests can leverage the readily available cache. These APIs can also help map the response data to the watch app UI using other classes of KonyWatchKitUtil library. All the requests that are sent to the phone using these APIs will be executed in the background.
KonyDataMapper
A KonyDataMapper class help update UI widgets on an Apple Watch application. This class accepts a dictionary of information and automatically maps the dictionary contents on to the widget properties when the dictionary follows a pre-defined format. Typically, this dictionary is the response data received from a phone application using KonyWatchKitUtil APIs. The class has the following APIs:
© 2015 by Kony, Inc. All rights reserved 729 of 848
Kony Studio API Developer's Guide
Version 5.0
l initWithObject : This API initializes KonyDataMapper object. This API accepts an object that manages UI widgets (an object of the WKInterfaceController class) as a parameter to map the widget properties with the dictionary contents.
Note: If you initialize KonyDataMapper object using the init function, an exception will result.
l updateWidgetPropertiesFromDictionary: This API updates the widget properties with the input dictionary contents. This API relies on outlets (properties) defined in the controller object to map the dictionary contents. The keys in the dictionary are the names of the outlets in the object passed as a parameter in KonyDataMapper object creation. The values must be the dictionary with keys as properties of outlets and their corresponding values.
Note: Some widgets can accept string also as a value.
The details about the dictionary format are available under
class.
Example
//Sample code for KonyDataMapper class
KonyDataMapper *dataMapper = [[KonyDataMapper alloc] initWithObject:self]; //here self is InterfaceController
[dataMapper updateWidgetPropertiesFromDictionary:aDictioanry];
KonyDataCache
© 2015 by Kony, Inc. All rights reserved 730 of 848
Kony Studio API Developer's Guide
Version 5.0
KonyDataCache is a class that stores key-value pairs, similar to a dictionary. The cache stores data temporarily in a watch that is obtained from an iPhone using WatchKit requests. Reusing the cached data improves performance. The cache reduces the processing requests to iPhone and helps to improve responsiveness for the users. However, if the data is not critical to the application and memory is running low, cached data can be discarded. If discarded, the data must be recomputed.
© 2015 by Kony, Inc. All rights reserved 731 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2.6.1 WatchKitRequestUtil
KonyWatchKitRequestUtil is a class that helps communication between the WatchKit App and its parent (iPhone) application. The APIs of this class facilitate the communication through the iOS IPC channel between Apple Watch and iPhone. A request, a set of key value pairs, from the Watch App is sent to its parent application. The parent application handles the request and sends the response, a set of key value pairs back to the watch app. The response data obtained from these APIs can be cached using one of the cache policies so that the further fetch data requests can leverage the readily available cache. These APIs can also help map the response data to the watch app UI using other classes of KonyWatchKitUtil library. All the requests that are sent to the phone using these APIs will be executed in the background.
Instance Creation APIs
These APIs help create an instance of KonyWatchkitRequestUtil object. The APIs are: l
l
(instancetype) sharedInstance
This API returns a shared instance of KonyWatchkitRequestUtil object.
Example
KonyWatchkitRequestUtil *util = [KonyWatchkitRequestUtil sharedInstance];
(id) init
This API helps initialize KonyWatchkitRequestUtil object.
Example
© 2015 by Kony, Inc. All rights reserved 732 of 848
Kony Studio API Developer's Guide
Version 5.0
KonyWatchkitRequestUtil *util = [[KonyWatchkitRequestUtil alloc] init];
Data Fetch APIs
The Data Fetch APIs help fetch the data from the cache based on the cache policy specified. You cannot update the data using these APIs. The APIs are: l
fetchDataWithRequestID:onCompletion:cachePolicy
l
fetchDataWithRequestID:userInfo:onCompletion:cachePolicy
fetchDataWithRequestID:onCompletion:cachePolicy
This API fetches data with a given requestID based on the cache policy specified. The parameters are: l requestID: This parameter identifies a specific request among multiple requests made by a watch app from its parent application.
l onCompletion: This parameter accepts an Objective-C block as an input. The block is invoked after receiving the response from a parent application. The callback assumes two parameters: n NSError : This parameter accepts an object that contains the error sent by the iPhone application.
n data : This parameter is an object that contains data sent by the iPhone.
Note: You can pass nil if you do not want to do anything with the fetched data.
l cachePolicy : Specifies the cache policy. For more information on supported cache policies, click
Example
© 2015 by Kony, Inc. All rights reserved 733 of 848
Kony Studio API Developer's Guide
Version 5.0
void( ^ callback)(NSError * err, id data) = ^ (NSError * err, id data) { if (err) {
NSLog(@"%@", err); //(To check what caused the error)
} else {
//do something
}
};
- (void) fetchDataWithRequestID: @"DeleteMail" onCompletion: callback cachePolicy: KonyDataCachePolicyOnlyFromLocal fetchDataWithRequestID:userInfo:onCompletion:cachePolicy
This API fetches data with a given requestID and userInfo based on the cache policy specified.
The parameters are: l requestID: This parameter identifies a specific request among multiple requests made by a watch app from its parent application.
l userInfo: This parameter specifies the dictionary that you must send to iPhone.
l onCompletion: This parameter accepts an Objective-C block as an input. The block is invoked after receiving the response from parent application. The callback assumes two parameters: n NSError : This parameter accepts an object that contains the error sent by the iPhone application.
n data : This parameter is an object that contains data sent by the iPhone.
Note: You can pass nil if you do not want to do anything with the fetched data.
l cachePolicy: Specifies the cache policy. For more information on supported cache policies, click
.
© 2015 by Kony, Inc. All rights reserved 734 of 848
Kony Studio API Developer's Guide
Version 5.0
Example
NSDictionary * userInfo = [
[NSDictionary alloc] init
];
[userInfo initWithObjects: @[@"text"] forKeys: @[@"Mail is
Edited”]];
- (void) fetchDataWithRequestID: @“EditMail” userInfo: userInfo onCompletion: nil cachePolicy: KonyDataCachePolicyOnlyFromRemote
Fetch Data and Update Controller APIs
The fetch data and update controller APIs are similar to the other fetch APIs in this class. But they add convenience functionality of updating the application UI with the data obtained from fetch response. Updating the controllers using the response data is done by using
KonyDataMapper class. The response data can still be cached using any of the supported cache policies.
The APIs are: l
fetchAndUpdateControllerWithRequestID:controller:onCompletion:cachePolicy
l
fetchAndUpdateControllerWithRequestID:controller:userInfo:onCompletion:cachePolicy
fetchAndUpdateControllerWithRequestID:controller:onCompletion:cachePolicy
This API fetches data with given requestID and controller based on the cache policy specified.
The parameters are: l requestID: This parameter identifies a specific request among multiple requests made by a watch app from its parent application.
© 2015 by Kony, Inc. All rights reserved 735 of 848
Kony Studio API Developer's Guide
Version 5.0
l controller: This is the object that manages a scene or a section of the scene. Typically, these objects are instances of WKInterfaceController class (manages scenes) or NSObject class
(manages table rows).
l onCompletion: This parameter accepts an Objective-C block as an input. The block is invoked after receiving the response from the parent application. The callback assumes two parameters: n NSError : This parameter accepts an object that contains the error sent by the iPhone application.
n data : This parameter is an object that contains data sent by the iPhone.
Note: You can pass nil if you do not want to do anything with the fetched data.
l cachePolicy: Specifies the cache policy. For more information on supported cache policies, click
.
Example void( ^ createLocalCache)(NSError * err, id data) = ^ (NSError * err, id data) { if (err) {
NSLog(@"%@", err); //(just to check what caused the error)
} else {
// since we are calling API with KonyDataCachePolicyNoCache data fetched will not be cached, so in callback you can cache the fetched data using KonyDataCache APIs the iPhone
}
};
KonyDataCache * cache = [KonyDataCache sharedInstance];
[cache setCacheWithDictionary: data]; //data is reply from
- (void) fetchAndUpdateControllerWithRequestID: @“MarkRead” controller: nil
© 2015 by Kony, Inc. All rights reserved 736 of 848
Kony Studio API Developer's Guide
Version 5.0
onCompletion: createLocalCache cachePolicy: KonyDataCachePolicyNoCache fetchAndUpdateControllerWithRequestID:controller:userInfo:onCompletion:cachePolicy
This API is used to fetch data with given requestID, controller, and userInfo based on the cache policy specified. The parameters are: l requestID: This parameter is used to identify a specific request among multiple request made by a watch app from its parent application.
l controller: It is the object that manages a scene or a section of the scene. Typically, these objects are instances of WKInterfaceController class (manages scenes) or NSObject class
(manages table rows).
l userInfo: This parameter specifies the dictionary that you must to send to the parent (iPhone).
l onCompletion: This parameter accepts an Objective-C block as an input. The block is invoked after receiving the response from parent application. The callback assumes two parameters: n NSError : This parameter accepts an object that contains the error sent by the iPhone application.
n data : This parameter is an object that contains data sent by the iPhone.
Note: You can pass nil if you do not want to do anything with the fetched data.
l cachePolicy: Specifies the cache policy. For more information on supported cache policies, click
.
Example
//Let us say we have an ExampleInterfaceController class which extends WKInterfaceController,
© 2015 by Kony, Inc. All rights reserved 737 of 848
Kony Studio API Developer's Guide
Version 5.0
ExampleInterfaceController * myController = [
[ExampleInterfaceController alloc] init
];
NSDictionary * userInfo = [
[NSDictionary alloc] init
];
[userInfo initWithObjects: @[@"text"] forKeys: @[@"Mail is
Deleted"]]; void( ^ callback)(NSError * err, id data) = ^ (NSError * err, id data) { if (err) {
NSLog(@"%@", err); //(To check what caused the error)
} else {
//do something
}
};
[util fetchAndUpdateControllerWithRequestID: @"DeleteMail" controller: myController userInfo: userInfo onCompletion: callback
CachePolicy: KonyDataCachePolicyFetchLatest
];
Cache Policies
A cache is an area of local memory in Apple Watch that holds a copy of frequently accessed data. If the caching is not there, then Apple Watch sends the request to iPhone to display the information. Such frequent requests will reduce the performance of your app. The KonyWatchKitUtil library has the following cache policies: l
KonyDataCachePolicyOnlyFromLocal: Use this policy to fetch the data from the local cache. If the cache is not available, then the APIs with this cache policy execute a callback block with
© 2015 by Kony, Inc. All rights reserved 738 of 848
Kony Studio API Developer's Guide
Version 5.0
"noCache" error.
l
KonyDataCachePolicyFetchLatest: Use this policy to fetch the latest data from the cache or its parent (iPhone) application. The data received is cached.
Note: Fetching the latest information occurs by validating the cacheId that is supplied as part of the request information. It is the responsibility of the parent app to validate the version of the data (cacheId), with the current version of the data available in the parent app. If the validation results in a decision to send the latest information back to the watch app, then the parent app should send the response dictionary in the following format {
"hasUpdate":true, "cacheId":<updated
CacheId>,"data":<responsedata>} . If the validation results in a decision where there are no updates in the data, then the parent app should send the response dictionary in the following format {"hasUpdate":false}.
l
KonyDataCachePolicyOnlyFromRemote: Use this policy to fetch the data from its parent
(iPhone) application. The data received is cached.
l
KonyDataCachePolicyNoCache: Use this policy to fetch the data from its parent (iPhone) application, and the data is not cached.
Note: If there is a connection failure between the watch and its parent, then a callback is executed with a connectionFailed error
Note: Data is cached based on the requestId passed as a first parameter to these four cache policies. Passing same requestId will overwrite data in the cache.
The following is an example where the cache policy KonyDataCachePolicyFetchLatest is used as a parameter. The parent application should validate the cacheId, and the appropriate response is sent back.
© 2015 by Kony, Inc. All rights reserved 739 of 848
Kony Studio API Developer's Guide
Version 5.0
function onwatchRequestCallBack1(userInfo, replyObj) { var date = new Date(); var testData; if (userInfo["datasetId"] === "DeleteMail”) { if (userInfo["cacheId"] == currentCacheId) { testData = {
"data": nil, //optional here since cache in local is valid no need to pass data again
"cacheId": userInfo["cacheId”],
"hasUpdate”:”false”
};
} else { testData = {
"data": {
"label": {
"text": "BasicWorks"
}
},
"cacheId": date,
"hasUpdate": “true”
};
}
} replyObj.executeWithReply(testData);
}
© 2015 by Kony, Inc. All rights reserved 740 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2.6.2 KonyDataMapper
A KonyDataMapper class helps update UI widgets on an Apple Watch application. This class accepts a dictionary of information and automatically maps the dictionary contents on to the widget properties when the dictionary follows a pre-defined format. Typically, this dictionary is the response data received from a phone application using KonyWatchKitUtil APIs. The class has the following APIs: l initWithObject : This API helps initialize KonyDataMapper object. This API accepts an object that manages UI widgets (an object of WKInterfaceController class) as a parameter to map the widget properties with the dictionary contents.
Note: If you initialize KonyDataMapper object using the init function, an exception will result.
l updateWidgetPropertiesFromDictionary: This API updates the widget properties with the input dictionary contents. This API relies on outlets (properties) defined in the controller object to map the dictionary contents. The keys in the dictionary are the names of the outlets in the object passed as a parameter in KonyDataMapper object creation. The values must be the dictionary with keys as properties of outlets and their corresponding values.
Note: Some widgets can accept string also as a value.
Sample code to create object and updating the properties
//Sample code
KonyDataMapper *dataMapper = [[KonyDataMapper alloc] initWithObject:self];//Here self is the InterfaceController
[dataMapper updateWidgetPropertiesFromDictionary:aDictioanry];
Following are the widgets supported by KonyDataMapper class:
© 2015 by Kony, Inc. All rights reserved 741 of 848
Kony Studio API Developer's Guide
Version 5.0
l
l
l
l
l
l
l
l
l
l
l
Button
This widget (an instance of WKInterfaceButton class) represents a tappable area on the watch screen. A button supports actions that help invoke a method. For example, when you tap on the watch screen, an action associated with the button gets invoked. A button can be enabled or disabled dynamically. You can assign the styles for a title using attributed title.
Following are the updatable properties of the Button Widget: l width [float value as a string or number]: Specifies the width of the button.
l height [float value as a string or number]: Specifies the height of the button.
l alpha [float value as a string or number]: Specifies the transparency of the button.
© 2015 by Kony, Inc. All rights reserved 742 of 848
Kony Studio API Developer's Guide
Version 5.0
l visible [boolean value as a string or number]: Specifies the visibility of the button. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
l title [string]: Specifies the title of the button.
l backgroundColor [color in hexadecimal string]: Specifies the background color of the button.
l backgroundImage [image name as a string]: Specifies the background image for the button.
l enabled [boolean]: It is a toggle option to interact with the button.
Example
//Defining the button properties.
"button": {
"title": "button title",
"backgroundColor": "#654321",
"backgroundImage": "image"
}
// You can also configure the button using the string.
"button": "buttonName"
Note: Images must be placed in the "ImageAssests" folder, and the image name must be specified as values in a dictionary. By default, images have a higher priority than color. If the specified image name is not found, then the color is applied.
Date
This widget (an instance of WKInterfaceDate class) displays the date or time on the watch screen. A date can be configured by time zone and calendar. You can dynamically change the color of the date.
The iOS-supported calendar and time zones must be specified as string.
Following are the supported calendar formats:
© 2015 by Kony, Inc. All rights reserved 743 of 848
Kony Studio API Developer's Guide
Version 5.0
l
GregorianCalendar l
BuddhistCalendar l
ChineseCalendar l
CopticCalendar l
EthiopicAmeteMihretCalendar l
EthiopicAmeteAlemCalendar l
HebrewCalendar l
ISO8601Calendar l
IndianCalendar l
IslamicCalendar l
IslamicCivilCalendar l
IslamicTabularCalendar l
IslamicUmmAlQuraCalendar l
JapaneseCalendar l
PersianCalendar l
RepublicOfChinaCalendar
Following are the updatable properties of Date Widget: l width [float value as string or number] : Specifies the width of the date.
l height [float value as string or number]: Specifies the height of the date.
l alpha [float value as string or number]: Specifies the transparency of the date.
© 2015 by Kony, Inc. All rights reserved 744 of 848
Kony Studio API Developer's Guide
Version 5.0
l visible [boolean value as string or number]: Specifies the visibility of the date. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
l textColor [color in hexadecimal string]: Specifies the color of the date.
l timeZone [string]: Specifies the time zone for the calendar.
l calendar [string]: Specifies the calendar.
Example
//Defining the date properties.
"date": {
"textColor": "#123456",
"timeZone": "Asia/Kolkata",
"calendar": "IndianCalendar"
}
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
Group
This widget (an instance of WKInterfaceGroup class) helps group one or more widgets. The group acts as a container. Configure a group by setting image, color, and cornerRadius.
Following are the updatable properties of the Group Widget: l width [float value as a string or number]: Specifies the width of the group.
l height [float value as a string or number]: Specifies the height of the group.
l alpha [float value as a string or number]: Specifies the transparency of the group.
© 2015 by Kony, Inc. All rights reserved 745 of 848
Kony Studio API Developer's Guide
Version 5.0
l visible [boolean value as a string or number]: Specifies the visibility of the group. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
l backgroundImage [string]: Specifies the image for the background of the group.
l backgroundColor [color in hexadecimal string]: Specifies the background color for the group.
l cornerRadius [float or number]: Specifies the corner radius of the group.
Example
//Defining the group properties.
"group": {
"backgroundColor": "#123456",
"backgroundImage": "image",
"cornerRadius": "2.0"
}
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
Image
This widget (an instance of WKInterfaceImage class) display images on the watch screen.
Note: Images must be present in the ImageAssests folder.
Following are the updatable properties of the Image Widget: l width [float value as a string or number]: Specifies the width of the image.
l height [float value as a string or number]: Specifies the height of the image.
l alpha [float value as a string or number]: Specifies the transparency of the image.
© 2015 by Kony, Inc. All rights reserved 746 of 848
Kony Studio API Developer's Guide
Version 5.0
l visible [boolean value as a string or number]: Specifies the visibility of the image. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
l imageName [string]: Specifies the name of the image.
l tintColor [color in hexadecimal string]: Specifies the tint color for the image.
Example
//Defining the image properties.
"image": {
"imageName": "imageName",
"tintColor": "#654321"
}
// You can also configure the Image using the string.
"image": "imageName"
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
Label
This widget (an instance of WKInterfaceLabel class) displays text on the watch screen. The text is displayed using the system default font, scale, and alignment. To use custom values for text, use attributed text. The default label color is white.
Following are the updatable properties of the Label Widget: l width [float value as a string or number]: Specifies the width of the text.
l height [float value as a string or number]: Specifies the height of the text.
l alpha [float value as a string or number]: Specifies the transparency of the text.
© 2015 by Kony, Inc. All rights reserved 747 of 848
Kony Studio API Developer's Guide
Version 5.0
l visible [boolean value as a string or number]: Specifies the visibility of the text. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
l text [string]: Specifies the text to be displayed on the screen.
l textColor [color in hexadecimal string]: Specifies the color of the text.
Example
//Defining the label properties.
"label": {
"text": "labelName",
"textColor": "#5236ce"
}
// You can configure the text using the string.
"label": "labelName"
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
Map
This widget (an instance of WKInterfaceMap class) displays the map on the watch screen. You must configure the map dynamically. A map can have more than one annotation.
Following are the updatable properties of the Map Widget: l width [float value as a string or number]: Specifies the width of the map.
l height [float value as a string or number]: Specifies the height of the map.
l alpha [float value as a string or number]: Specifies the transparency of the map.
© 2015 by Kony, Inc. All rights reserved 748 of 848
Kony Studio API Developer's Guide
Version 5.0
l visible [boolean value as a string or number]: Specifies the visibility of the map. It accepts a boolean value in case-sensitive string or nonstring formats such as "true"
/ "false" or true/false. You can also specify 0 for true or 1 for false.
l region [array of four double values]: Specifies the values as an array with the following properties. You must provide the values in two-digit numbers.
l latitude: Specifies the latitude value.
l longitude: Specifies the longitude value.
l spanNorth: Specifies the vertical span representing the amount of map to display.
l spanSouth: Specifies the horizontal span representing the amount of map to display.
l mapRect [array of four double values]: Specifies the two-dimensional map projection. Following are the properties: l x: Specifies the location of the point along the x-axis of the map.
l y: Specifies the location of the point along the y-axis of the map.
l width: Specifies the width of the map.
l height: Specifies the height of the map.
l annotation[array of dictionaries]: Specifies the text to be displayed on the screen.
l location [array of two double values]: Specifies the location. This property is mandatory. Following are the properties: l lat: Specifies the latitude value.
l long: Specifies the longitude value.
l imageName [String] : Specifies the image for annotation.
l offset [array of two float values]: Specifies the offset distance for annotation.
© 2015 by Kony, Inc. All rights reserved 749 of 848
Kony Studio API Developer's Guide
Version 5.0
l pinColor: Red, green, and purple can be configured as the pin color. If the pinColor is not specified, by default red is configured. All other colors are not supported.
l remove [boolean value as a string or number ]: This property removes all annotations. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false. You can also specify 0 for true or
1 for false.
Important details about the preceding properties: l
For annotation you can specify either imageName and offset or pinColor. The behavior is undefined if you specify imageName and pinColor.
l
The offset must be configured to display the custom pin. If the pin image name is not specified, then the red pin is used.
l
The offset (with image) takes precedence over pinColor.
l
The remove property accepts a boolean value. If remove is true, then all annotations are deleted.
Example
//Defining the map properties.
"map": {
"mapRect": [10.22, 10.33, 20, 20],
"region": [17.323244, -1.89893, 1, 1], used
"annotation”:[ {
"location": [17.23456, -1.89893],
"imageName": "image", //optional by default red color pin is
"offset": [1.2, 3.4],
},
{
"location": [17.323244, -1.98765],
© 2015 by Kony, Inc. All rights reserved 750 of 848
Kony Studio API Developer's Guide
Version 5.0
]
}
}
"pinColor": "purple"
"remove": "yes" //Removes all annotations
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
Switch
This widget (an instance of WKInterfaceSwitch class) displays a toggle button on the watch screen.
Following are the updatable properties of the Switch Widget: l width [float value as a string or number]: Specifies the width of the switch.
l height [float value as a string or number]: Specifies the height of the switch.
l alpha [float value as a string or number]: Specifies the transparency of the switch.
l visible [boolean value as a string or number]: Specifies the visibility of the switch. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
l title [string]: Specifies the text to be displayed on the switch.
l color [color in hexadecimal string]: Specifies the color of the switch.
l enabled [boolean value as a string or number]: It is a toggle option to interact with the switch. It accepts a boolean value in case sensitive string or non string formats such as "true" / "false" or true/false. You can also specify 0 for true or 1 for false.
© 2015 by Kony, Inc. All rights reserved 751 of 848
Kony Studio API Developer's Guide
Version 5.0
l state [boolean value as a string or number]: Specifies the state of the switch. It accepts a boolean value in case sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
Example
//Defining the switch properties.
"Switch": {
"title": "switchName",
"color": "5236ce",
"state": "no",
"enabled": "yes"
}
// You can configure the switch using the string.
"Switch": "SwitchName"
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
Separator
This widget (an instance of WKInterfaceSeparator class) helps separate the widgets. You can assign a color to a separator.
Following are the updatable properties of the Separator Widget: l width [float value as a string or number]: Specifies the width of the separator.
l height [float value as a string or number]: Specifies the height of the separator.
l alpha [float value as a string or number]: Specifies the transparency of the separator.
© 2015 by Kony, Inc. All rights reserved 752 of 848
Kony Studio API Developer's Guide
Version 5.0
l visible [boolean value as a string or number]: Specifies the visibility of the separator. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
l color [color in hexadecimal string]: Specifies the color of the separator.
Example
//Defining the separator properties.
"Separator": {
"color": "5236ce",
}
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
Slider
This widget (an instance of WKInterfaceSlider class) selects a value from a defined range of values by using the minus and plus signs on the slider. The value is incremented using a float value form 0 to 1.0.
A slider can be enabled or disabled dynamically.
Following are the updatable properties of the Slider Widget: l width [float value as a string or number]: Specifies the width of the slider.
l height [float value as a string or number]: Specifies the height of the slider.
l alpha [float value as a string or number]: Specifies the transparency of the slider.
l visible [boolean value as a string or number]: Specifies the visibility of the slider. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
l color [color in hexadecimal string]: Specifies the color of the slider.
© 2015 by Kony, Inc. All rights reserved 753 of 848
Kony Studio API Developer's Guide
Version 5.0
l value [positive float value as a string or number]: Specifies the value of the slider.
l numberOfSteps [positive integer as a string or number]: Specifies the steps on the slider.
l enabled [boolean value as a string or number]: It is a toggle option to interact with the slider. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false. You can also specify 0 for true or 1 for false.
Note: The behavior is undefined if you assign negative values to the numberOfSteps and value properties.
Example
//Defining the slider properties.
"slider": {
"value": ".25",
"numberOfSteps": "10",
"color": "#5236ce",
"enabled": "yes"
}
// You can configure the slider using the string.
"slider": ".5"
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
Timer
This widget (an instance of WKInterfaceTimer class) acts as a countdown timer. There is no delegate for the timer. To know when the timer reaches zero, you need to run a separate timer next to the timer.
A timer can be stopped or started, and the countdown is automatically calculated from the date. The counting starts when the timer reaches zero.
© 2015 by Kony, Inc. All rights reserved 754 of 848
Kony Studio API Developer's Guide
Version 5.0
Following are the updatable properties of the Timer Widget: l width [float value as a string or number]: Specifies the width of the timer.
l height [float value as a string or number]: Specifies the height of the timer.
l alpha [float value as a string or number]: Specifies the transparency of the timer.
l visible [boolean value as a string or number]: Specifies the visibility of the timer. It accepts a boolean value in case-sensitive string or nonstring formats such as "true" / "false" or true/false.
You can also specify 0 for true or 1 for false.
l textColor [color in hexadecimal string]: Specifies the text color of the timer.
l date [string with format mm/dd/yyyy hh:mm a]: Specifies the date and time for the timer.
l action [start/stop as a string ]: Specifies the action for the timer to start or stop.
Example
//Defining the timer properties.
"time": {
"date": "12/30/2015 10:30 am", //mm/dd/yyyy hh:mm a
"textColor": "#123456",
"action": "start"
}
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
Table
This widget (an instance of WKInterfaceTable class) represents a single-column table. The table represents a dictionary containing a controller for row and data dictionary for each widget. Each row in a table is a class that is a subclass of the NSObject and contains outlets. To initialize a group of rows simultaneously, use the key "rows". To insert rows at a given position or delete a specific row with
© 2015 by Kony, Inc. All rights reserved 755 of 848
Kony Studio API Developer's Guide
Version 5.0
the specified indices, use the key "rowActions."
Following are the updatable properties of the Table Widget: l data [dictionary]: Specifies the data for the table.
l controller [string ]: Specifies the controller name that holds widgets to be inserted in a single row of a table. It is mandatory.
l rows [array of dictionaries]: Specifies the rows as an array. Each dictionary represents a row. For example, [{}, {},...] .
l rowActions [dictionary]: Specifies the dictionary that contains insert and remove keys. It inserts rows at different positions or deletes different rows.
l insert [array of dictionaries]: Specifies an array of dictionaries, each dictionary contains an index and data of a widget. For example:
[{<index>:<index number>,<data>:{} }, .....], l remove [array of indexes]: Specifies an array of indexes to be removed.
[...],
Note: The index value ranges from zero to the number of rows in a table.
Example
//Inserting two rows in a table."table": {
"data": {
"controller": "RowController",
"rows": [{
"button": "buttonName",
"label": "labelName"
}, //row
{
© 2015 by Kony, Inc. All rights reserved 756 of 848
Kony Studio API Developer's Guide
Version 5.0
}
}
]
"button": "buttonName2",
"label": "labelName2"
}, //row
//Insert and remove two rows in a table."table": {
"data": {
"controller": "RowController",
"rowActions": {
"insert": [{
"index": 0,
"data": {
"button": "buttonName3",
"label": "labelName3"
}
}],
"remove": [1]
}
}
Note: The order of the keys is not mandatory. You can use only the required key-value pairs.
© 2015 by Kony, Inc. All rights reserved 757 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2.6.3 KonyDataCache
KonyDataCache is a class that stores key-value pairs, similar to a dictionary. The cache stores data temporarily in a watch that is obtained from an iPhone using WatchKit requests. Reusing the cached data improves performance. The cache reduces the processing requests to iPhone and helps to improve responsiveness for the users. However, if the data is not critical to the application and memory is running low, cached data can be discarded. If discarded, the data must be recomputed.
cacheTimeoutInterval
This property helps cache the data in an Apple Watch for the duration specified. If you do not specify the cacheTimeoutInterval, the data is cached for one day. The duration must be specified in seconds.
Example
KonyDataCache * cache = [
[KonyDataCache alloc] initWithName: @“localCache”
]; cache.cacheTimeoutInterval = 20; // so data is cached for 20 seconds
Following are the APIs available for the KonyDataCache class: l
initWithName:(NSString*)cacheName
l
l
(void)setObject:(id)value forKey:(id)key
l
l
(void)setCacheWithDictionary:(NSDictionary*)dict
l
(NSDictionary)getDictionaryFromCache
l
(void)setString:(NSString*)string forKey:(NSString*)key
© 2015 by Kony, Inc. All rights reserved 758 of 848
Kony Studio API Developer's Guide
Version 5.0
l
(NSString*)getStringforKey:(NSString*)key
l
(void)setImage:(UIImage*)image forKey:(NSString*)key
l
(UIImage*)getImageForKey:(NSString*)key
l
l
l
(void)removeCacheForKey:(NSString*)key
initWithName:(NSString*)cacheName
This API helps you initialize the KonyDataCache object with the specified cache name.
Signature initWithName:(NSString*)cacheName
Input Parameters cacheName [String] - Mandatory
Specifies the name of the cache that must be initialized.
Return Values
This API returns the initialized KonyDataCache object.
Platform Availability
Available on iOS platform.
Example
KonyDataCache * cache = [
[KonyDataCache alloc] initWithName: @"mycache"
];
© 2015 by Kony, Inc. All rights reserved 759 of 848
Kony Studio API Developer's Guide
Version 5.0
(instancetype)sharedInstance
This API helps you create a shared instance of the KonyDataCache object with a default name.
Signature
(instancetype)sharedInstance
Input Parameters
None
Return Values
This API returns the KonyDataCache shared instance.
Platform Availability
Available on iOS platform.
Example
KonyDataCache * cache = [KonyDataCache sharedInstance];
(void)setObject:(id)value forKey:(id)key
This API helps you set cache with a given key value pair.
Signature
(void)setObject:(id)value forKey:(id)key
Input Parameters value [object] - Mandatory
Specifies the value to be cached.
key [String] - Mandatory
Specifies the key for the value object.
© 2015 by Kony, Inc. All rights reserved 760 of 848
Kony Studio API Developer's Guide
Version 5.0
Return Values
None
Platform Availability
Available on iOS platform.
Example
KonyDataCache * cache = [
[KonyDataCache alloc] initWithName: @"mycache"
];
NSArray * arr = @ [@"one", @"two"];
[cache setObject: arr forKey: @"key"]
(id)getObjectForKey:(id)key
This API helps you get the value of the NSObject for the given key object.
Signature
(id)getObjectForKey:(id)key
Input Parameters key [String] - Mandatory
Specifies the key object for which the associated value is retrieved.
Return Values
None
Platform Availability
Available on iOS platform.
© 2015 by Kony, Inc. All rights reserved 761 of 848
Kony Studio API Developer's Guide
Version 5.0
Example
NSArray * arr = [cache getObjectForKey: @"key"];
(void)setCacheWithDictionary:(NSDictionary*)dict
This API helps you set cache with a given dictionary.
Signature
(void)setCacheWithDictionary:(NSDictionary*)dict
Input Parameters dict [Object] - Mandatory
Specifies the dictionary object with which the cache is set.
Return Values
None
Platform Availability
Available on iOS platform.
Example
NSDictionary * dict = @ {@
"key1": @ "val1",
@"key2": "val2"
};
[cache setCacheWithDictionary: dict];
(NSDictionary)getDictionaryFromCache
This API helps you get the dictionary from cache.
© 2015 by Kony, Inc. All rights reserved 762 of 848
Kony Studio API Developer's Guide
Version 5.0
Signature
(NSDictionary)getDictionaryFromCache
Input Parameters
None
Return Values
This API returns the dictionary.
Platform Availability
Available on iOS platform.
Example
NSDictionary * dict = [cache getDictionaryFromCache];
(void)setString:(NSString*)string forKey:(NSString*)key
This API helps you set the cache with given key-value string objects.
Signature
(void)setString:(NSString*)string forKey:(NSString*)key
Input Parameters
String [String] - Mandatory
Specifies the string object set as a value to the given key.
key [String] - Mandatory
Specifies the key for the object.
Return Values
This API returns the dictionary.
Platform Availability
Available on iOS platform.
© 2015 by Kony, Inc. All rights reserved 763 of 848
Kony Studio API Developer's Guide
Version 5.0
Example
[cache setString: @"stringValue" forKey: @"stringkey"
];
(NSString*)getStringforKey:(NSString*)key
This API helps you get the string object associated with the given key.
Signature
(NSString*)getStringforKey:(NSString*)key
Input Parameters key [String] - Mandatory
Specifies the key for the object to which the associated value is retrieved.
Return Values
This API returns NSString object.
Platform Availability
Available on iOS platform.
Example
[cache setString: @"stringValue" forKey: @"stringkey"
];
(void)setImage:(UIImage*)image forKey:(NSString*)key
This API helps you set the image object to a given key in cache.
Signature
(void)setImage:(UIImage*)image forKey:(NSString*)key
© 2015 by Kony, Inc. All rights reserved 764 of 848
Kony Studio API Developer's Guide
Version 5.0
Input Parameters image [UIImage] - Mandatory
Specifies the image object set as a value to the given key.
key [String] - Mandatory
Specifies the key for the object.
Return Values
This API returns NSString object.
Platform Availability
Available on iOS platform.
Example
UIImage * image = [UIImage imageNamed: @"image.png"];
[cache setImage: image forKey: @"myImage"];
(UIImage*)getImageForKey:(NSString*)key
This API helps you get the image for a given key.
Signature
(UIImage*)getImageForKey:(NSString*)key
Input Parameters key [String] - Mandatory
Specifies the key object to which the associated value is retrieved.
Return Values
This API returns UIImage.
Platform Availability
Available on iOS platform.
© 2015 by Kony, Inc. All rights reserved 765 of 848
Kony Studio API Developer's Guide
Version 5.0
Example
UIImage * img = [cache getImageForKey: @"myImage"];
(NSArray*)getAllkeys
This API helps you get all keys in the cache.
Signature
(NSArray*)getAllkeys
Input Parameters
None
Return Values
This API returns NSArray object.
Platform Availability
Available on iOS platform.
Example
NSArray *arr = [cache getAllKeys];
(void)clearCache
This API helps you clear the cache.
Signature
(void)clearCache
Input Parameters
None
Return Values
None
© 2015 by Kony, Inc. All rights reserved 766 of 848
Kony Studio API Developer's Guide
Version 5.0
Platform Availability
Available on iOS platform.
Example
[cache clearCache];
(void)removeCacheForKey:(NSString*)key
This API helps you remove cache for the given key.
Signature
(void)removeCacheForKey:(NSString*)key
Input Parameters key [String] - Mandatory
Specifies the key object that has to be removed from the cache.
Return Values
None
Platform Availability
Available on iOS platform.
Example
[cache removeCacheForKey:@"myImage"];
© 2015 by Kony, Inc. All rights reserved 767 of 848
Kony Studio API Developer's Guide
Version 5.0
39.2.6.4 Kony Application Integration using WatchKit Util Library
Workflow
The workflow of KonyWatchKitRequestUtil library starts when a user invokes one of the four
KonyWatchKitRequestUtil APIs. The invoked API prepares the userInfo object and sends it to the iPhone application. The iPhone app prepares a response and sends the response object to an Apple
Watch.
Sample code to send the request
This API results in launching a parent application for request handling in the background, so that the parent application must implement a method for handling requests that takes userInfo and replyObj as parameters.
KonyWatchkitRequestUtil * util = [
[KonyWatchkitRequestUtil alloc] init
];
[util fetchAndUpdateControllerWithRequestID: @"DeleteMail" controller: watchInterfaceController userInfo: userInfo onCompletion: callbackblock
CachePolicy: KonyDataCachePolicyFetchLatest
];
Structure of userInfo Object
The API fetchAndUpdateControllerWithRequestID:controller:userInfo:onCompletion
:cachePolicy prepares a request message and sends it to the parent application. Along with the userInfo, “requestId” and “cacheId” keys are added.
© 2015 by Kony, Inc. All rights reserved 768 of 848
Kony Studio API Developer's Guide
Version 5.0
l requestId : The value of the requestId key is the first argument to the API.
l cacheId: This key is added only when there is data from the previous request with the same requestId in the local cache.
{
"requestId " : "DeleteMail"
"cacheId": "11-06-2015" //If there is no data in local, then this key will not be present
"userInfo": {
"somekey1": "somevalue1"
"somekey2": "somevalue2"
}//whenever userinfo dictionary you pass while calling
}
You must define the following method in the iPhone application to handle the request from Apple
Watch.
function onwatchRequestCallBack(userInfo, replyObj) { var testData; var date = new Date(); if (userInfo["requestId"] === "DeleteMail")
{ testdata= {
"data": {
"label": {
}
},
"cacheId" : date,
"hasUpdate": "yes"
"text": "BasicWorks"
© 2015 by Kony, Inc. All rights reserved 769 of 848
Kony Studio API Developer's Guide
Version 5.0
};
} replyObj.executeWithReply(testData);
}
//The replyObj.executeWithReply(testData) sends response to watch app
//Watch app caches the data depending on the cache policy specified
Structure of response Object
The request handler function in iPhone application should send the response object that contains
"data," "hasUpdate," and cacheId."
Example
{
"data": {
"label": "userName"
"button": "submit"
"hasUpdate": "true" //This key will take only “true” or “false” string values
}
}
"cacheId": "11-06-2015"
The value for the “data” key should be a dictionary containing outlet names as keys and their associated values as specified in KonyDataMapper Class.
© 2015 by Kony, Inc. All rights reserved 770 of 848
Kony Studio API Developer's Guide
Version 5.0
39.3 Android Wear
Google's Android Wear helps you run your app on your wrist. As with your phone, you can use
Android Wear to play music, check the weather, track fitness, track flights, get reminders, answer calls, and more. Android Wear is paired (connected) with your handheld device through Bluetooth.
The message that you receive on your phone is also displayed on Android Wear. Using Android Wear, you can also block notifications being received from your phone.
You can only display notifications on Android Wear. Creating a complete app for Android wearable using Kony Studio is not available in this release.
39.3.1 Application Architecture for Android
Android Phone and Android Wear apps consist of the following components: l
Message Data Receiver: This component is responsible for listening to the data and message changes that happen between the wearable and mobile application.
l
Message Data/Send: This component is responsible for sending data between the wearable and mobile application using Data APIs and Message APIs.
© 2015 by Kony, Inc. All rights reserved 771 of 848
Kony Studio API Developer's Guide
Version 5.0
l
Wearable Listener: The wearable listener service receives events from other nodes such as data changes, messages, or connectivity events. The lifecycle of this service is managed by
Android Wear.
l
Data Layer: This component stores the data.
l
Broadcast Receiver: The broadcast receiver component helps you receive intents that are broadcast by the system or by other applications, even when other components of the application are not running.
For example, applications can register for the ACTION_BOOT_COMPLETED system event that is executed once the Android system has completed the boot process.
39.3.2 Notification Lifecycle for Android
The Android notification lifecycle involves three stages: l
Stage one: A push message is sent from a push messaging server.
l
Stage two: The message is then received by the Android Phone.
l
Stage three: The device displays the notification on both the Android phone and Android Wear.
When you interact with the notification action on the Android Wear or Android Phone, the necessary callbacks are executed. The notifications are dismissed on both the devices.
The following illustration depicts a typical notification lifecycle for Android:
© 2015 by Kony, Inc. All rights reserved 772 of 848
Kony Studio API Developer's Guide
Version 5.0
You have to follow certain guidelines for creating notifications such as title, number of lines of text you want to display, image size, and so on.
© 2015 by Kony, Inc. All rights reserved 773 of 848
Kony Studio API Developer's Guide
Version 5.0
39.3.3 Configuring Android Wear Project
This section explains the procedure to configure an Android Wear project and covers the following topics: l
l
Download the SDK and Install the Software l
Set Up the Android Wear Emulator or Device l
How to Create and Test a Sample App on Android Wear
l
39.3.3.1 Installing the Software
Refer to the following links to install Android SDK, Android Wear Device, and Emulator: l
Download the SDK and Install the Software l
Set up the Android Wear Emulator or Device
39.3.4 How to Create and Test a Sample App on Android Wear
In this release Kony Studio supports only notifications to be displayed on your Android Wear. Creating a complete app would be available in future releases.
To create a sample app and test it on your Android Wear, follow these steps:
1. From your Kony Studio, open an existing project or create a new project.
2. Go to Application Properties > Native> Android, and select Enable Local Notifications check box to receive Local Notifications and GCM check box to receive Push Notifications.
© 2015 by Kony, Inc. All rights reserved 774 of 848
Kony Studio API Developer's Guide
Version 5.0
3. To see actions in notifications, your app should have actions, categories associated with the actions. You app should also register the category. For example, below is the code for the sample email app.
//Sample code to create actions. Make sure this code is executed before notification gets fired.
var ReadMailObj = kony.notificationsettings.createAction
({"id":"ReadMail", "label":"ReadMail", "pspConfig":
{"activationMode":kony.notificationsettings.ACTIVATION_MODE_
FORWARDS, "authenticationRequired": true, "destructive": true}}); var DeleteMailObj = kony.notificationsettings.createAction
({"id":"DeleteMail", "label":"DeleteMail", "pspConfig":
{"activationMode":kony.notificationsettings.ACTIVATION_MODE_
© 2015 by Kony, Inc. All rights reserved 775 of 848
Kony Studio API Developer's Guide
Version 5.0
FORWARDS, "authenticationRequired": true, "destructive": true}});
//Sample code to create category var actionArr = [ReadMailObj, DeleteMailObj]; var minActionArr = [ReadMailObj, DeleteMailObj]; var categoryObj = kony.notificationsettings.createCategory
({"categoryId":"newmail", "actions":actionArr, "pspConfig":
{"minimalActions": minActionArr}});
//Registering Category var categoryArr = [categoryObj]; kony.notificationsettings.registerCategory( {"categories": categoryArr,"pspConfig":{ "types":[0,1,2]}} );
4. Build the project for the Android platform and install the app on your Android Phone.
5. Pair your Android Wear with your Android Phone.
Your Android Wear is ready to receive notifications. The flow of the notifications is:
1. Using Kony MobileFabric Messaging , send a notification to your app. For more information on installing and configuring Kony MobileFabric Messaging, refer the installation guide .
© 2015 by Kony, Inc. All rights reserved 776 of 848
Kony Studio API Developer's Guide
Version 5.0
Note: The message you send must have a category in the key value form. For example:
Key should be category (constant) value is the categoryid that is created (in the above sample code newmail is the categoryid).
If there are no actions associated with the category, only the label is displayed on Android
Wear.
A screen used to send messages in Kony MobileFabric Messaging is shown below: l
Key: Specifies the key that is defined in notification setting APIs.
l
Value: Specifies the value associated with the Key.
l
Title: Specifies the title of the notification. This is optional. You can leave it blank.
l
Message: Specifies the notification message.
© 2015 by Kony, Inc. All rights reserved 777 of 848
Kony Studio API Developer's Guide
Version 5.0
2. The message is received by your Android phone.
3. Your Android phone then delivers it to the Android Wear.
4. If you respond to the message on Android Wear, Wear will communicate with the Android
Phone, which will respond with the application.
© 2015 by Kony, Inc. All rights reserved 778 of 848
Kony Studio API Developer's Guide
Version 5.0
39.3.4.1 Troubleshooting
If you encounter any problems or issues while creating the application, check the following settings/configurations before logging any defect.
l
The Android Wear application works on the OS version 4.4W (API 20) and above.
l
When you build an app to receive local notifications, select the Enable Local Notifications check box in Application Properties > Native> Android.
l
Android Wear must be paired with your Android Phone.
l
If you are sending push messages using Kony MobileFabric Messaging, configure the notify_push_msg_clear value to false in the pushconfig.xml that is in the resources folder. If the value is not configured, the notification message will not be sent to Android Wear.
l
If you are sending local notification messages, configure the notify_local_msg_clear value to false in the localnotificationconfig.xml that is in resources folder. If the value is not configured, the notification message will not be sent to Android Wear.
l
To customize notifications, refer to the following links: l pushconfig.xml
l
© 2015 by Kony, Inc. All rights reserved 779 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
40. Worker Thread APIs
Worker threads are a means to execute different tasks in multiple parallel contexts of execution in a concurrent manner, which can take advantage of multiprocessor and multithreaded environments as well as to keep UI Thread in Application responsive by delegating or offloading work which need not be handled in UI Main thread, to a different secondary thread.
Worker thread is a continuous parallel thread that runs and accepts messages until the time it is explicitly closed or terminated. Messages to a worker thread can be sent from the parent thread or its child worker threads. Through out this document, parent thread is referred as thread where a worker thread is spawned.
Worker can have logic that gets executed parallel for each of the messages that it receives. If worker thread is busy handling messages, incoming messages that it receives will be queued for processing.
Sharing data between parent thread and worker threads is done through message passing and by default variables, functions, or state is not shared.
The current specification is inspired from and based on HTML5 Web Worker threads standard, that use Message Passing model or mechanism for communication between threads.
The scenarios of using WorkerThread() constructor are as follows: l
The WorkerThread() constructor creates a new worker thread and returns a handle to the new worker thread, which can be used by the parent thread for any further communication with the worker thread.
Creating a worker thread requires a JavaScript file name or a functional module name. The
WorkerThread() constructor is invoked with the JavaScript file or a functional module name as its only argument and a worker thread instance is then created and returned: var worker = new kony.worker.WorkerThread('helper.js'); var worker = new kony.worker.WorkerThread
('functionModuleName'); l
A message event handler can be registered with the worker by parent thread to receive
© 2015 by Kony, Inc. All rights reserved 780 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
messages from the worker thread.
worker.addEventListener("message", function (event) {
... }); l
To send data from parent to a worker, postMessage() method can be used from parent.
‘buffer’, threshold: 0.6 } ); l
To send messages back from worker thread to parent thread scope, postMessage() can be used.
postMessage({‘msg’:’Data’}); l
To receive a messages inside the worker thread from parent thread, the message event handler can be registered using addEventListener() inside worker thread.
self.addEventListener( "message", function (event) { ...
});
40.1 Scope
1. Kony Platform version >= 5.6.2.
2. Support for JavaScript.
3. Supported mobile Platforms: a. iOS b. Android c. SPA: Supported List of browsers starting from versions.
4. Supported List of Browsers
SPA
© 2015 by Kony, Inc. All rights reserved 781 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
iOS
5.0-
5.1
Blackberry
OS
10.0
4.4
Android
Native
DesktopWeb
IE
10.0
Firefox Chrome Safari
4.0
20 5.0
33.0
Android
Chrome
8
Windows phone
OS
5. Windows: a. Windows Phone 8 b. Windows Phone 8.1
c. Windows Kiosk d. Windows 8.1
40.2 Worker Thread APIs
l
l
l
l
l
l
© 2015 by Kony, Inc. All rights reserved 782 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
l
l
l
l
40.3 Introduction to Constructor - WorkerThread()
l
The WorkerThread() constructor creates and returns the handle to the newly created worker thread. The new worker thread can be used by the Parent thread for any further communication with the worker thread.
l
To create a worker thread, it requires a JavaScript file name or a functional module name. The
WorkerThread() constructor is invoked with the JavaScript file or a functional module name as its only argument and a worker thread instance is then created and returned.
l
Worker threads may in turn initiate new worker threads.
l
If a Javascript file name with “.js” extension is passed as WorkerThread() constructor argument, it looks up only in the
workerthreads
directory in
modules/js
path and loads if the file is found. This holds good for functional modules based projects as well as non-functional modules based projects.
l
If a function module name is provided as an argument for WorkerThread() constructor, in case of functional modules based project then the module will be loaded if found in the modules listing.
40.3.1 Worker Thread Life Cycle
The following steps provide the work flow to use worker thread:
1. Call to Worker constructor will create a new Worker instance and a new parallel execution environment context is created, and immediately starts execution in the new parallel thread of
© 2015 by Kony, Inc. All rights reserved 783 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
control in an asynchronous manner. In this new thread, first the Worker will try to load the
‘workerjs’ script.
2. As a result of the asynchronous parallel nature of execution in worker thread context, invocation of Worker constructor call in Parent thread will return a new Worker instance handle and Parent proceeds with execution of next instructions.
3. Every Worker thread will have its own event loop which takes care of the execution of all the received message tasks which are queued for this worker in that order until ‘self.close()’ in worker scope or ‘worker.terminate()’ in parent worker scope are invoked.
4. From the moment of successful creation of worker thread and until ‘self.close()’ in worker scope or ‘worker.terminate()’ in parent worker scope are invoked, the worker thread will be alive and can receive and process messages which are sent to this worker form its parent or from its child workers if created, as well as it can send messages using postMessage() to its parent thread and its child worker threads if created.
40.3.2 Example of Worker Thread
Here is an example for creating a WorkerThread: new kony.worker.WorkerThread(workerjs);
40.3.3 Input Parameters l workerjs [String] - Mandatory workerjs can be the name of javascript file name or functional module name which contains worker thread code.
© 2015 by Kony, Inc. All rights reserved 784 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
40.3.4 Return Values
Object - kony.worker.WorkerThread
40.3.5 Exceptions
When an error is encountered, the KonyError JS object is thrown with the following information:
Error
Code
3001
Name
WorkerThreadError
Message
WorkerThread:
MissingMandatoryParameter.
Failed to construct
WorkerThread
3002 WorkerThreadError WorkerThread:
InvalidParameter. Invalid script name
Reason
If no argument is given to the constructor API, this exception is thrown and workerThread object is not created.
If workerjs argument is not a string, then this exception is thrown and workerThread object is not created.
l
If the script or module mentioned by workerjs argument is not found, and if an “error” event handler is registered for this worker object in Parent scope then it is invoked with an error
“event” object and its “message” attribute set to following.
message:“WorkerThread: InvalidParameter. WorkerThread script not found” o
In this error scenario no ‘KonyError’ exception will be raised.
o
Also the filename, lineno properties in the error event object for this error scenario have undefined values.
© 2015 by Kony, Inc. All rights reserved 785 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
l
If multiple arguments are provided separated by a comma, the first argument is considered as the “workerjs” filename or module name and rest all are ignored.
40.3.6 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
40.3.7 JavaScript Example try { var worker = new kony.worker.WorkerThread("worker1.js");
} catch (e) { var err = kony.getError(e);
}
} if (err instanceof KonyError) { kony.print("KonyError Catch : " + JSON.stringify(err));
40.4 hasWorkerThreadSupport
This API is used during runtime only in parent scope to determine whether the current platform environment has worker thread support.
This API is most useful in case of SPA and Desktop Web platforms where runtime query can be made to determine whether a browser environment supports Worker Threads or not.
© 2015 by Kony, Inc. All rights reserved 786 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
40.4.1 Signature
JavaScript : kony.worker.hasWorkerThreadSupport()
Input Parameters
None
40.4.2 Return Values
Boolean true: When worker thread support is present.
false: When worker thread support is not present.
40.4.3 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
40.4.4 JavaScript Example var hasWorkerSupport = kony.worker.hasWorkerThreadSupport(); if (hasWorkerSupport) { var worker = new kony.worker.WorkerThread("worker1.js");
//do something
} else {
//workers not supported
}
© 2015 by Kony, Inc. All rights reserved 787 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
40.5 postMessage
postMessage() sends a JSON object or String message to the Parent/worker's scope by invoking respective registered “message” event handlers.
l
In Parent thread scope, call to worker.postMessage() invokes “message” event handler which is registered using addEventListener() in Workers inner Scope.
l
In Worker thread scope, call to postMessage() invokes “message” event handler which is registered using addEventListener() in Parents scope.
The JSON or string object passed to postMessage() is delivered to the registered “message” event handler. The “event” object “data” attribute will have the message passed: “event.data”.
Adhering to the JSON standard, the JSON object passed to postMessage() API should be serializeble
JSON without opaque object handles or function object handles etc.
40.5.1 Signature
JavaScript : postMessage(<String> or <JSON>);
//Parent scope:
//JSON Object
worker.postMessage({‘msg’ : ‘hello’});
//String
worker.postMessage("messsage hello");
//Worker scope:
//JSON Object
postMessage({‘msg’ : ‘hello’});
© 2015 by Kony, Inc. All rights reserved 788 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
//String
postMessage("messsage hello");
40.5.2 Input Parameters l
String
For parent scope, here is an example: worker.
postMessage("messsage hello");
For worker scope, here is an example:
postMessage("messsage hello");
l
JSON Object
For parent scope, here is an example: worker.
postMessage({‘msg’ : ‘hello’});
For worker scope, here is an example:
postMessage({‘msg’ : ‘hello’});
40.5.3 Return Values
None
40.5.4 Exceptions
1. If no argument is given it raises an exception and throws a “KonyError” JS Object with the following attributes: errorCode: 3001.
name: "WorkerThreadError".
message: "postMessage: MissingMandatoryParameter. Message undefined"
2. If the message argument passed is not String or JSON object, it raises an exception and throws a “KonyError” JS Object with the following attributes: errorCode: 3002.
name: "WorkerThreadError".
message: "postMessage: InvalidParameter. Invalid Message"
© 2015 by Kony, Inc. All rights reserved 789 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
3. In Worker scope if these exceptions are not handled and if an “error” event handler is registered in worker’s inner scope or/and in Parent scope for this worker object then it is invoked with an error event object and its message attribute set to following.
In case of exception 1: message: "postMessage: MissingMandatoryParameter. Message undefined"
In case of exception 2: message: "postMessage: InvalidParameter. Invalid Message"
4. In Parent (not a worker to some other parent) scope if these exceptions are not handled registered “error” event handler will not be invoked.
40.5.5 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
40.5.6 JavaScript Example var worker = new kony.worker.WorkerThread("worker1.js");
// Parent scope:
//JSON Object worker.postMessage({‘msg’ : ‘hello’});
//String worker.postMessage(‘message hello’);
// Worker scope:
//JSON Object postMessage({‘msg’ : ‘hello’});
© 2015 by Kony, Inc. All rights reserved 790 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
//or
//or this.postMessage({‘msg’ : ‘hello’}); self.postMessage({‘msg’ : ‘hello’});
//String
//or postMessage(‘message hello’); this.postMessage(‘message hello’);
//or self.postMessage(‘message hello’);
40.6 addEventListener
Event Handlers can be registered using addEventListener() method on the worker Objects and once registered messages and errors from a worker thread can be received in parent thread.
Due to the asynchronous parallel execution nature of the newly created worker thread, which starts executing the worker JS script upon creation. It is always advisable to immediately register the
‘message’ event handler as well as ‘error’ event handler on the worker handle in parent thread context after creation of the worker. This ensures that posted messages or errors in worker scope are handed over to the respective ‘message’ or ‘error’ event listeners in parent scope.
message event handler:
Registered “message” event handler will be invoked in Parent or Worker thread whenever postMessage() is called from inner scope of Worker or Parent thread.
1. In parent scope, call to worker.
postmessage() invokes message event handler registered using addEventListener() in Workers inner Scope.
© 2015 by Kony, Inc. All rights reserved 791 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
2. In worker scope, call to postmessage() invokes message event handler registered using addEventListener() in Parents scope.
Multiple message event handlers can also be registered in parent scope and workers inner scope and all the registered event handlers will be invoked in the registered order whenever a postMessage() is called.
error event listener:
The error handler can also be registered using addEventListener () in parent thread scope on worker object and as well as in worker thread’s inner scope, which will be invoked whenever an unhandled exception occurs in workers inner scope.
The error event object has the following three fields: message, filename, lineno.
If an error event handler is registered in worker inner scope and in parent scope on the worker object, then both the event handlers are invoked in case of an unhandled exception in worker’s inner scope.
Multiple error event handlers can be registered on the worker handle in parent scope and also in worker threads inner scope. Registered error event handlers will be invoked in the order of registration in case of unhandled exception in worker thread.
If an error event handler is not registered for a worker in parent scope or in worker inner scope and if an unhandled exception arises in worker’s inner scope then worker halts execution and no error info is propagated.
The error event handlers work for unhandled exceptions occurring only in worker scope but not in main parent scope.
40.6.1 Signature
JavaScript:
Parent scope: worker.addEventListener(key, listener);
Worker scope:
© 2015 by Kony, Inc. All rights reserved 792 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
addEventListener(key, listener); self.addEventListener(key, listener); this.addEventListener(key, listener);
40.6.2 Input Parameters key listener message: When message event handler is being registered.
error: When error event handler is being registered.
The listener parameter indicates the event listener function to be added.
40.6.3 Return Values
None
40.6.4 Exceptions
1. If no argument is given or if the number of arguments are less than two, it raises an exception and throws a “KonyError” JS Object with the following attributes: errorCode: 3001.
name: "WorkerThreadError".
message: "addEventListener: MissingMandatoryParameter. Mandatory arguments missing"
2. If the first argument is not equal to “message” or “error” and if second argument is not a function object, it raises an exception and throws a “KonyError” JS Object with the following attributes: errorCode: 3002.
name: "WorkerThreadError".
message: "addEventListener: InvalidParameter. Invalid arguments"
© 2015 by Kony, Inc. All rights reserved 793 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
3. In Worker scope if these exceptions are not handled and if an “error” event handler is registered in worker’s inner scope or/and in Parent scope for this worker object then it is invoked with an error event object and its message attribute set to following.
In case of exception 1) message: "addEventListener: MissingMandatoryParameter . Mandatory arguments missing"
In case of exception 2) message: "addEventListener: InvalidParameter. Invalid arguments"
4. In Parent(not a worker to some other parent) scope if these exceptions are not handled registered “error” event handler will not be invoked.
40.6.5 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
40.6.6 JavaScript Example
//Parent Scope var worker = new kony.worker.WorkerThread("worker1.js"); var evtMessageHandler_1 = function (event) { kony.print ("Parent Scope : In message handler 1");
}; var evtErrorHandler_1 = function (event) { kony.print("Parent Scope: In error handler 1"); kony.print('ERROR: Line ' + event.lineno + ' in ' + event.filename +
': ' + event.message);
};
© 2015 by Kony, Inc. All rights reserved 794 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
"message" event handler :
//Parent Scope var worker = new kony.worker.WorkerThread("worker1.js"); var evtMessageHandler_1 = function (event) { kony.print ("Parent Scope : In message handler 1");
}; var evtMessageHandler_2 = function (event) { kony.print ("Parent Scope : In message handler 2");
}; worker.addEventListener("message", evtMessageHandler_1); worker.addEventListener("message", evtMessageHandler_2);
//Worker Scope var evtMessageHandler_1 = function (event) { kony.print ("Worker Scope : In message handler 1");
}; self.addEventListener("message", evtMessageHandler_1);
//or this.addEventListener("message", evtMessageHandler_1);
//or addEventListener("message", evtMessageHandler_1);
"error" event listener :
© 2015 by Kony, Inc. All rights reserved 795 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
//Parent Scope var worker = new kony.worker.WorkerThread("worker1.js"); var evtErrorHandler_1 = function (event) { kony.print("Parent Scope: In error handler 1"); kony.print('ERROR: Line ' + event.lineno + ' in ' + event.filename +
': ' + event.message);
}; var evtErrorHandler_2 = function (event) { kony.print("Parent Scope: In error handler 2");
};
// worker.addEventListener("error", evtErrorHandler_1); worker.addEventListener("error", evtErrorHandler_2);
//Worker Scope var evtErrorHandler_1 = function (event) { kony.print("Worker Scope: In error handler 1");
}; self.addEventListener("error", evtErrorHandler_1);
//or this.addEventListener("error", evtErrorHandler_1);
© 2015 by Kony, Inc. All rights reserved 796 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
//or addEventListener("error", evtErrorHandler_1);
40.7 message event handler
“message” event handler receives an “event” object which contains the JSON or string message that is passed to postMessage() during invocation and the same message can be accessed from its
“event.data” field. The data passed to postMessage() should be a String or JSON object.
Adhering to the JSON standard, the JSON object passed to postMessage() API should be serializable
JSON without opaque object handles or function object handles etc. The data which is passed between the parent thread and worker thread using postMessage() API are copied, not shared, so the end result is that a duplicate is created on each end.
Multiple “message” event handlers can also be registered in Parent scope and in workers inner scope and all the registered event handlers will be invoked in the registered order whenever a postMessage
() is called.
40.7.1 Signature
JavaScript : function(event) { });
40.7.2 Input Parameters
String / JSON Object l
“message” event handler receives an “event” object which contains the JSON or string message that is passed to postMessage() during invocation and the same message can be accessed from its “event.data” field.
l
The data passed to postMessage() should be a String or JSON object.
© 2015 by Kony, Inc. All rights reserved 797 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
l
Adhering to the JSON standard, the JSON object passed to postMessage() API should be serializable JSON without opaque object handles or function object handles etc.
l
The data which is passed between the parent thread and worker thread using postMessage()
API are copied, not shared, so the end result is that a duplicate is created on each end.
l
Multiple “message” event handlers can also be registered in Parent scope and in workers inner scope and all the registered event handlers will be invoked in the registered order whenever a postMessage() is called.
40.7.3 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
40.7.4 JavaScript Example var evtMessageHandler_1 = function(event) {
//In case of JSONkony.print ("Received message :" + event.data
["msg"]);"
//In case of string kony.print ("Received message :" + event.data);
};
40.8 error event handler
“error” event handler receives an “event” object which has the has the following three fields: message, filename, lineno. Registered ‘error’ event handler is invoked whenever an unhandled exception arises in worker’s scope. “error” event handler can be registered in parent thread scope on worker object and as well as in worker thread’s inner scope, where both event handlers will be invoked if present whenever an unhandled exception occurs in workers inner scope.
© 2015 by Kony, Inc. All rights reserved 798 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
Multiple “error” event handlers can also be registered in Parent scope and in workers inner scope and all registered event handlers will be invoked in the registered order whenever an unhandled exception arises in worker’s scope.
40.8.1 Signature
JavaScript : function(event) { });
40.8.2 Input Parameters error event object (message, filename, lineno)
40.8.3 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
40.8.4 JavaScript Example function(event) { kony.print ('ERROR: Line '+ event.lineno + ' in ' + event.filename
+ ': ' + event.message);
}
40.9 removeEventListener
This API is used to remove the previously registered message or error event listener that was registered using addEventListener().
This API can be used in both parent and worker scope
40.9.1 Signature
JavaScript :
© 2015 by Kony, Inc. All rights reserved 799 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
Parent scope: worker.removeEventListener(key, listener);
Worker scope: removeEventListener(key, listener); self.removeEventListener(key, listener); this.removeEventListener(key, listener);
40.9.2 Input Parameters key message: In case of message event handler.
error: In case of error event handler.
listener: The listener parameter indicates the event listener function to be removed.
40.9.3 Exceptions
1. If no argument is given or if the number of arguments are less than two, it raises an exception and throws a “KonyError” JS Object with the following attributes: errorCode: 3001.
name: "WorkerThreadError".
message: "removeEventListener: MissingMandatoryParameter.
Mandatory arguments missing"
2. If the first argument is not equal to “message” or “error” and if second argument is not a function object, it raises an exception and throws a “KonyError” JS Object with the following attributes:
© 2015 by Kony, Inc. All rights reserved 800 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
errorCode: 3002.
name: "WorkerThreadError".
message: "removeEventListener: InvalidParameter. Invalid arguments"
3. In Worker scope if these exceptions are not handled and if an “error” event handler is registered in worker’s inner scope or/and in Parent scope for this worker object then it is invoked with an error event object and its message attribute set to following.
In case of exception 1: message: "removeEventListener: MissingMandatoryParameter.
Mandatory arguments missing"
In case of exception 2: message: "removeEventListener: InvalidParameter. Invalid arguments"
4. In Parent(not a worker to some other parent) scope if these exceptions are not handled registered “error” event handler will not be invoked.
40.9.4 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
40.9.5 JavaScript Example
"message" event handler :
//Parent Scope var worker = new kony.worker.WorkerThread("worker1.js"); var evtMessageHandler_1 = function (event) { kony.print ("Parent Scope : In message handler 1");
};
© 2015 by Kony, Inc. All rights reserved 801 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
var evtMessageHandler_2 = function (event) { kony.print ("Parent Scope : In message handler 2");
};
//adding event listeners worker.addEventListener("message", evtMessageHandler_1); worker.addEventListener("message", evtMessageHandler_2);
//removing event listener worker.removeEventListener("message", evtMessageHandler_2);
//Worker Scope var evtMessageHandler_1 = function (event) { kony.print ("Worker Scope : In message handler 1");
}; var evtMessageHandler_2 = function (event) { kony.print ("Worker Scope : In message handler 2");
};
//adding event listeners self.addEventListener("message", evtMessageHandler_1); self.addEventListener("message", evtMessageHandler_2);
//removing event listener self.removeEventListener("message", evtMessageHandler_2);
"error" event listener :
//Parent Scope
© 2015 by Kony, Inc. All rights reserved 802 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
var worker = new kony.worker.WorkerThread("worker1.js"); var evtErrorHandler_1 = function (event) { kony.print("Parent Scope: In error handler 1");
}; var evtErrorHandler_2 = function (event) { kony.print("Parent Scope: In error handler 2");
};
//adding event listeners worker.addEventListener("error", evtErrorHandler_1); worker.addEventListener("error", evtErrorHandler_2);
//removing event listener worker.removeEventListener("error", evtErrorHandler_2);
//Worker Scope var evtErrorHandler_1 = function (event) { kony.print("Worker Scope: In error handler 1");
}; var evtErrorHandler_2 = function (event) { kony.print("Worker Scope: In error handler 2");
};
//adding event listeners self.addEventListener("error", evtErrorHandler_1); self.addEventListener("error", evtErrorHandler_2);
//removing event listener self.removeEventListener("error", evtErrorHandler_2);
© 2015 by Kony, Inc. All rights reserved 803 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
40.10 terminate
When called from parent scope immediately terminates the worker. This does not offer the worker an opportunity to finish its operations. It is simply stopped at once.
The tasks pending in the message queue and callbacks registered for network, timer APIs are discarded without wait until completion.
40.10.1 Signature
JavaScript : worker.terminate();
40.10.2 Input Parameters
None
40.10.3 Return Values
None
40.10.4 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
40.10.5 JavaScript Example var worker = new kony.worker.WorkerThread("worker1.js");
//post a message to the worker worker.postMessage("Hello from Parent");
© 2015 by Kony, Inc. All rights reserved 804 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
//terminate the worker worker.terminate();
40.10.6 Limitations
As the worker threading model is mapped to underlying native threading models in native platforms, there can be some deviations from what specification says, this is due to technical limitations in the underlying platforms which include: l
When terminate() is invoked in Parent thread on worker, and if worker is currently executing a large task, it might not immediately terminate, it will continue to execute the task to completion and terminate.
l
When terminate() is invoked in Parent thread on worker, and if there are pending tasks waiting in the message queues for this worker to perform, some platforms might discard all the pending tasks without accepting them for execution and terminate, and on some platform all the pending tasks are executed to completion and then the worker terminates.
l
Hence it is to be noted that to achieve cross platform consistency, it is always advised that terminate() be invoked on the worker once all the tasks in message queues are completed.
40.11 close
Worker thread can be terminated from inner scope of the worker by invoking close(). The worker thread is killed immediately without an opportunity to complete its operations or clean up.
The tasks pending in the message queue and callbacks registered for network, timer APIs etc are discarded without wait until completion.
40.11.1 Signature
JavaScript :
© 2015 by Kony, Inc. All rights reserved 805 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
Worker scope: close(); self.close(); this.close();
40.11.2 Input Parameters
None
40.11.3 Return Values
None
40.11.4 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
40.11.5 JavaScript Example
//worker init
//post a message to parent self.postMessage("Hello from Worker");
//do some work
//terminate this worker from inner scope self.close();
© 2015 by Kony, Inc. All rights reserved 806 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
40.11.6 Limitations
As the worker threading model is mapped to underlying native threading models in native platforms, there can be some deviations from what specification says, this is due to technical limitations in the underlying platforms which include: l
When close() is invoked in worker scope, and if worker is currently executing a large task, it might not immediately terminate, it will continue to execute the task to completion and then terminate.
l
When close () is invoked in worker scope, and if there are pending tasks waiting in the message queues for this worker to perform, some platforms might discard all the pending tasks without accepting them for execution and terminate, and on some platform all the pending tasks are executed to completion and then the worker terminates.
l
Hence it is to be noted that to achieve cross platform consistency, it is always advised that close
() be invoked in worker scope once all the tasks in message queues are completed.
40.12 Importing scripts
Worker threads can use importScripts() function to import external scripts their scope by providing the
JS file name to import. This method takes one or more JavaScript file names to import.
This API is only available in worker thread scope and not in main parent thread scope.
In case of Functional modules based project ” kony.modules.loadFunctionalModule()” API can be used to import a functional module into workers scope. Refer
specification document for usage help on loadFunctionalModule() API.
importScripts() if invoked with .js file, looks up only in the “workerthreads" directory under “modules/js/” in Kony IDE Project structure to import scripts into workers scope. This holds good for both functional modules based projects and non-functional modules based projects.
In case of loading multiple files using importScripts(), if an error occurs while loading one of the script, then the remaining scripts are not loaded into context scope.
© 2015 by Kony, Inc. All rights reserved 807 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
For more information on Functional Module APIs, refer
.
40.12.1 Signature
JavaScript : importScripts(".js_file_name"); or
JavaScript : importScripts("functional_module_name");
40.12.2 Input Parameters
JSFileNames [Object] or
Functional_Module_Name [Object] l
One or more comma separated list of JavaScript file names.
40.12.3 Return Values
None
40.12.4 Exceptions
Note: If no argument is given, no exception is raised and it does nothing.
When an error is encountered, the KonyError JS object is thrown with the following information:
Error
Code
3002
Name
WorkerThreadError
Message importScripts:
InvalidParameter. Invalid script name
Reason
This exception occurs when the argument passed is not a string.
© 2015 by Kony, Inc. All rights reserved 808 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
Error
Code
3002
Name
WorkerThreadError
Message importScripts:
InvalidParameter. Unable to import script. <scriptname>
Reason
This exception occurs when it is unable to find and load the JS script.
l
In worker scope, if these exceptions are not handled and if an error event handler is registered in worker’s inner scope or/and in parent scope for this worker object, then it is invoked with an error event object and its message attribute is set as follows:
Exception 1 - message: "importScripts: InvalidParameter. Invalid script name"
Exception 2 - message: "importScripts: InvalidParameter. Invalid script name"
Differences in behavior of importScripts() and
kony.modules.loadFunctionalModule()
API with respect to Functional Modules:
Without Functional Modules
From inside Worker context if importScripts() is used to import external JS scripts the search criteria would be : only “workerthreads” directory.
With Functional Modules
From inside Worker context if importScripts() is used to import external JS scripts the search criteria would be : only “workerthreads” directory.
kony.modules.loadFunctionalModule() function cannot be used in workers scope to load any
FunctionalModule.
kony.modules.loadFunctionalModule()
function can be used in workers scope to load any
JavaScript script which is part of some
Functional Module.
40.12.5 Platform Availability
Available for iOS, Android, Windows, SPA, and Desktop Web. For more information, see
.
© 2015 by Kony, Inc. All rights reserved 809 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
40.12.6 JavaScript Example importScripts("Utility.js"); // loads Util.js
importScripts("Utility1.js", "Utility2.js", "Utility3.js");
40.13 Using Worker Threads Feature
The following topics helps you to use the worker thread feature: l
Communicating and Data Processing Between Threads
l
Nesting of Threads and Performing Parallel Tasks
l
Scope Rules and Supported APIs
l
l
l
40.13.1 Communicating and Data Processing Between Threads
Main.js
//create new worker var worker = new kony.worker.WorkerThread('1_worker.js');
//invoked when worker calls postmessage() from its inner scope worker.addEventListener("message", function (event) { kony.print('Parent Scope : onmessage : event.data : ' + event.data["message"]);
© 2015 by Kony, Inc. All rights reserved 810 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
}); kony.print('Parent Scope : Invoking worker.postmessage()');
//will invoke worker's inner scope onmessage() worker.postMessage({
'message': 'Hello World From Parent'
});
1_worker.js
//workers inner scope
//invoked when Parent calls worker.postmessage() self.addEventListener("message", function (event) { kony.print('Worker Scope : onmessage : event.data : ' + event.data["message"]);
//call func do_something_in_worker();
}); function do_something_in_worker() { kony.print('Worker Scope : invoking postMessage()');
//will invoke Parent worker.onmessage() postMessage({
'message': "Hello World From Worker "
});
};
Expected Output
"Parent Scope: Invoking worker.postmessage()"
"Worker Scope: onmessage : event.data : " "Hello World From Parent"
"Worker Scope: invoking postMessage()"
"Parent Scope: onmessage : event.data : " "Hello World From Worker "
© 2015 by Kony, Inc. All rights reserved 811 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
Explanation
1. In Parent Scope: Creates new worker using new kony.worker.WorkerThread ()
2. In Parent Scope: Call to worker.postMessage() invokes message event handler registered using addEventListener() in worker threads inner scope.
3. In Worker Scope: Call to postMessage() invokes message event handler registered using addEventListener() in the parent thread scope.
40.13.2 Nesting of Threads and Performing Parallel Tasks
Main.js
try { kony.print("Parent Scope: Init test_case_parent_thread()"); kony.print("Parent Scope: In try block");
//create new kony.worker.WorkerThread
var worker = new kony.worker.WorkerThread('WorkerThread.js');
//invoked when worker calls postmessage() from its inner scope worker.addEventListener("message", function (event) { kony.print('Parent Scope : onmessage : event.data : ' + event.data);
}); worker.postMessage("Hello from Parent");
} catch (err) { kony.print("Parent Scope: In Catch block");
}
© 2015 by Kony, Inc. All rights reserved 812 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
//invoke a function invoke_timer_task();
// function invoke_timer_task() { kony.print("Parent Scope :- kony.timer.schedule - "); var timerId = "mytimer12111"; var i = 0; function timerFunc() { i++; kony.print("Parent Scope :- kony.timer.schedule - In timerFunc() : " + i); if (i > 20) { kony.print("Parent Scope :- kony.timer.schedule -
Stopping timer : "); kony.timer.cancel(timerId);
}
};
// kony.timer.schedule(timerId, timerFunc, 1, true); kony.print("Parent Scope :- kony.timer.schedule - Done");
}; kony.print("Parent Scope: Exit test_case_parent_thread()");
WorkerThread.js
//worker
//workers inner scope
© 2015 by Kony, Inc. All rights reserved 813 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
kony.print("Worker Scope: Init"); var worker = new kony.worker.WorkerThread('WorkerThread2.js');
//invoked when Parent calls worker.postmessage() this.addEventListener("message", function(event) { kony.print('Worker Scope : onmessage : event.data : ' + event.data);
}); self.postMessage("Hello from Worker");
// invoke_timer_task();
// function invoke_timer_task() { kony.print("Worker Scope :- kony.timer.schedule - "); var timerId = "mytimer121"; var i = 0; function timerFunc() { i++; kony.print("Worker Scope :- kony.timer.schedule - In timerFunc() : " + i); if(i > 20) { kony.print("Worker Scope :- kony.timer.schedule -
Stopping timer : "); kony.timer.cancel(timerId);
}
© 2015 by Kony, Inc. All rights reserved 814 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
};
// kony.timer.schedule(timerId,timerFunc, 1, true); kony.print("Worker Scope :- kony.timer.schedule - Done");
}; kony.print("Worker Scope: Loading done");
WorkerThread2.js
//Grand child worker2 – nested worker
//workers inner scope kony.print("Grand child: Worker2 Scope: Init");
//invoked when Parent calls worker.postmessage() this.addEventListener("message", function(event) { kony.print('Grand child: Worker2 Scope : onmessage : event.data : '
+ event.data);
}); self.postMessage("Hello from Worker2");
// invoke_timer_task();
// function invoke_timer_task () { kony.print("Grand child: Worker2 Scope :- kony.timer.schedule -
"); var timerId = "mytimer1211"; var i = 0; function timerFunc()
© 2015 by Kony, Inc. All rights reserved 815 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
{ i++; kony.print("Worker2 Scope :- kony.timer.schedule - In timerFunc() : " + i + " : Grand child "); if(i > 20) { kony.print("Grand child: Worker2 Scope :kony.timer.schedule - Stopping timer : "); kony.timer.cancel(timerId);
}
};
// kony.timer.schedule(timerId,timerFunc, 1, true); kony.print("Grand child: Worker2 Scope :- kony.timer.schedule -
Done");
}; kony.print("Grand child: Worker2 Scope : Loading done");
40.13.3 Scope Rules and Supported APIs
Global resources in the App context will not be available in the worker thread context as it can lead to
Race conditions since no locking mechanisms are provided.
Every worker has its own context of execution, which is not shared between the parent and its worker.
As a result the global variables in parent scope are not available in worker scope and vice versa.
Not
Supp orted
APIs l
Kony UI APIs and UI object handles l
App Global variables
© 2015 by Kony, Inc. All rights reserved 816 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
Supp orted
APIs and
Platfo rm
String
API
Math
API
Table
API
Standar d Kony
API
Networ k API
Cryptog raphy
API iO
S iO
S iO
S iO
S iO
S
© 2015 by Kony, Inc. All rights reserved
Offline
Data
Access
API
Lo cal
Sto rag e
Operati ng
System
API
We b
SQ
L iO
S iO
S iO
S
An dro id iO
S
An dro id
An dro id
An dro id
An dro id
An dro id
Win dow s
Win dow s
Win dow s
Win dow s
SPA
SPA
SPA
Desktop
Web
Desktop
Web
Desktop
Web
Win dow s
Andr oid
Limited Availability
* For SPA and Desktop Web, the following APIs are supported: l kony.convertToBase64
l kony.convertToRawByte
s l kony.type
l kony.props.getProperty
l kony.print() is not supported in Safari.
l
Kony.print() is supported in Mozilla from version
29.0.
For SPA and DesktopWeb:
Limited Availability n
The following API will not be available in SPA &
Desktop Web.
kony.net.setNetworkCall
backs
817 of 848
Windows
Andr oid
Windows
Win dow s
An dro id
Win dow s
SPA and
DesktopWeb
* For SPA and Desktop Web, the following APIs are NOT supported: l kony.os.addHiddenField
l kony.os.readHiddenField
l kony.os.startSecureTran
saction l kony.os.endSecureTrans
action l kony.os.getAppContext
l kony.os.hasAcceleromet
erSupport l kony.os.deviceInfo
l kony.os.deviceInfo
().httpheaders
l kony.os.addMetaTag
l kony.os.removeMetaTag
l kony.os.removeAllMetaT
ags l kony.os.hasGPSSupport
l kony.os.hasCameraSupp
ort l kony.os.hasTouchSuppor
t l kony.os.hasOrientationS
upport l kony.os.getDeviceCurren
tOrientation l kony.os.print
* For SPA and Desktop Web, the following APIs are NOT supported: l kony.crypto.saveKey
l kony.crypto.deleteKey
l kony.crypto.readKey
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
40.13.4 FFI and Custom Widgets
With and without Functional Module in Worker context:
FFI
Custom Widgets iOS Android
Platform will load modules by default
Windows
No need to load Custom Widgets in worker scope.
SPA
40.13.5 Guidelines and Limitations
The following guidelines are recommended before using worker thread:
1. The objects “this” and “self” are available in worker thread inner scope that is referred as worker thread itself.
2. Event propagation cannot be stopped by using event.stopPropagation() as in HTML specification. Where event.stopPropagation() stops the DOM event to be propagated further by breaking the event chain.
3. Data passed between the main thread and workers are copied, but not shared. Objects are serialized as they are handed to the worker, and subsequently, de-serialized on the other end.
The main thread and worker do not share the same instance. So the end result is that a duplicate is created on each end. HTML5 worker threads support transferable objects that allow transferring the objects from one thread to other without making a copy.
4. As explicit thread synchronization mechanisms like locking or mutexes are not available in JS environment, you must take required care in scenarios where multiple threads concurrently or simultaneously are trying to access and write/insert data into local database or local datastore using WebSQL or Local datastore APIs, as these are shared resources across the Application context.
© 2015 by Kony, Inc. All rights reserved 818 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
l
The outcome of these simultaneous or concurrent accesses to database/datastore might push the database/datastore to inconsistent state and is dependent on the individual platforms WebSQL or DataStore implementations. It is always suggested to avoid such scenarios of multiple threads accessing the database/datastore simultaneously/concurrently.
Limitations in SPA and DesktopWeb:
1. Nested Workers support will be available only if they are supported by the underlying browser platforms.
2. Error event messages in error event handler sometimes might be appended with extra prefix or suffix string messages from underlying browsers (like Uncaught, Uncaught error etc).
3. Even though error event handler is invoked in case of unhandled exceptions, the same event messages might also be logged on browser console.
4. Line number, file name populated in error event object passed to error event handler might be different from user defined files.
Note: For SPA and Desktop Web, nested workers are not supported in Google Chrome.
terminate API
As the worker threading model is mapped to underlying native threading models in native platforms, there can be some deviations from what specification says, this is due to technical limitations in the underlying platforms which include:
1. If terminate() is invoked in Parent thread on worker, and if worker is currently executing a large task, it might not immediately terminate, it will continue to execute the task to completion and terminate.
2. If terminate() is invoked in Parent thread on worker, and if there are pending tasks waiting in the message queues for this worker to perform, some platforms might discard all the pending tasks
© 2015 by Kony, Inc. All rights reserved 819 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
without accepting them for execution and terminate, and on some platform all the pending tasks are executed to completion and then the worker terminates.
3. It is to be noted that to achieve cross platform consistency, it is always advised that terminate() be invoked on the worker once all the tasks in message queues are completed.
close API
1. As the worker threading model is mapped to underlying native threading models in native platforms, there can be some deviations from what specification says, this is due to technical limitations in the underlying platforms which include:
2. When close() is invoked in worker scope, and if worker is currently executing a large task, it might not immediately terminate, it will continue to execute the task to completion and then terminate.
3. When close () is invoked in worker scope, and if there are pending tasks waiting in the message queues for this worker to perform, some platforms might discard all the pending tasks without accepting them for execution and terminate, and on some platform all the pending tasks are executed to completion and then the worker terminates.
4. Hence it is to be noted that to achieve cross platform consistency, it is always advised that close
() be invoked in worker scope once all the tasks in message queues are completed.
40.13.6 Debugger Support
Debugger support for worker threads is not available in 5.6.2 release.
40.13.7 Worker Life Cycle Notes
Following are some worker life cycle notes: l
Call to Worker constructor will create a new Worker instance and a new parallel execution environment context is created, and immediately starts execution in the new parallel thread of control in an asynchronous manner. In this new thread, first the Worker will try to load the
© 2015 by Kony, Inc. All rights reserved 820 of 848
40. Worker Thread APIs Kony Studio API Developer's Guide
Version 5.0
‘workerjs’ script.
l
As a result of the asynchronous parallel nature of execution in worker thread context, invocation of Worker constructor call in Parent thread will return a new Worker instance handle and Parent proceeds with execution of next instructions.
l
Every Worker thread will have its own event loop which takes care of the execution of all the received message tasks which are queued for this worker in that order until ‘self.close()’ in worker scope or ‘worker.terminate()’ in parent worker scope are invoked.
l
From the moment of successful creation of worker thread and until ‘self.close()’ in worker scope or ‘worker.terminate()’ in parent worker scope are invoked, the worker thread will be alive and can receive and process messages which are sent to this worker form its parent or from its child workers if created, as well as it can send messages using postMessage() to its parent thread and its child worker threads if created.
l
In worker thread scope when there is no “message” event handler registered which indicates that no tasks can be posted or queued by parent for this worker, and if no callbacks are registered in this worker scope for network, timer APIs etc, then after postMessage() call in
Workers inner scope if any, worker can terminate itself without worker.terminate() being called in Parent scope or self.close() called in inner scope.
l
In case of orphaned threads if no tasks are queued in message handler and if the worker is not waiting for any callbacks to be returned from network, timer APIs etc then the orphaned thread can be terminated.
l
If Parent stops either due to unhandled exception raised in it scope, Worker threads still continues to exist and execute.
© 2015 by Kony, Inc. All rights reserved 821 of 848
Kony Studio API Developer's Guide
Version 5.0
40.13.8 Worker Thread
Worker threads are used to execute events simultaneously. Worker thread can take advantage of multiprocessor environments and to keep responsive UI thread in the application (by delegating or offloading work, which need not be handled in the main thread).
Worker thread is a continuous parallel thread that runs and accepts messages until the time it is explicitly closed or terminated. Messages to a worker thread can be sent from the parent thread or its child worker threads. Through out this document, parent thread is referred as thread where a worker thread is spawned.
Worker can have logic that gets executed parallel for each of the messages that it receives. If worker thread is busy handling messages, incoming messages that it receives will be queued for processing.
Sharing data between parent thread and worker threads is done through message passing and by default variables, functions, or state is not shared.
The current specification is inspired from and based on HTML5 Web Worker threads standard, that use Message Passing model or mechanism for communication between threads.
Message Passing model based threads need proper communication constructs and protocol to be defined for data passing and also can consume more CPU cycles and memory because of local copies, and can have an impact on application performance if huge data needs to be transferred. Also, proper scoping rules need to be specified for access control of Shared or Global resources within the application context.
The following topics helps you to use the worker thread feature: l
Communicating and Data Processing Between Threads
l
Nesting of Threads and Performing Parallel Tasks
l
Scope Rules and Supported APIs
l
© 2015 by Kony, Inc. All rights reserved 822 of 848
Kony Studio API Developer's Guide
Version 5.0
l
l
40.13.8.1 Communicating and Data Processing Between Threads
Main.js
//create new worker var worker = new kony.worker.WorkerThread('1_worker.js');
//invoked when worker calls postmessage() from its inner scope worker.addEventListener("message", function (event) { kony.print('Parent Scope : onmessage : event.data : ' + event.data["message"]);
}); kony.print('Parent Scope : Invoking worker.postmessage()');
//will invoke worker's inner scope onmessage() worker.postMessage({
'message': 'Hello World From Parent'
});
1_worker.js
//workers inner scope
//invoked when Parent calls worker.postmessage() self.addEventListener("message", function (event) { kony.print('Worker Scope : onmessage : event.data : ' + event.data["message"]);
//call func do_something_in_worker();
});
© 2015 by Kony, Inc. All rights reserved 823 of 848
Kony Studio API Developer's Guide
Version 5.0
function do_something_in_worker() { kony.print('Worker Scope : invoking postMessage()');
//will invoke Parent worker.onmessage() postMessage({
'message': "Hello World From Worker "
});
};
Expected Output
"Parent Scope: Invoking worker.postmessage()"
"Worker Scope: onmessage : event.data : " "Hello World From Parent"
"Worker Scope: invoking postMessage()"
"Parent Scope: onmessage : event.data : " "Hello World From Worker "
Explanation
1. In Parent Scope: Creates new worker using new kony.worker.WorkerThread ()
2. In Parent Scope: Call to worker.postMessage() invokes message event handler registered using addEventListener() in worker threads inner scope.
3. In Worker Scope: Call to postMessage() invokes message event handler registered using addEventListener() in the parent thread scope.
40.13.8.2 Nesting of Threads and Performing Parallel Tasks
Main.js
try { kony.print("Parent Scope: Init test_case_parent_thread()"); kony.print("Parent Scope: In try block");
//create new kony.worker.WorkerThread
© 2015 by Kony, Inc. All rights reserved 824 of 848
Kony Studio API Developer's Guide
Version 5.0
var worker = new kony.worker.WorkerThread('WorkerThread.js');
//invoked when worker calls postmessage() from its inner scope worker.addEventListener("message", function (event) { kony.print('Parent Scope : onmessage : event.data : ' + event.data);
}); worker.postMessage("Hello from Parent");
} catch (err) { kony.print("Parent Scope: In Catch block");
}
//invoke a function invoke_timer_task();
// function invoke_timer_task() { kony.print("Parent Scope :- kony.timer.schedule - "); var timerId = "mytimer12111"; var i = 0; function timerFunc() { i++; kony.print("Parent Scope :- kony.timer.schedule - In timerFunc() : " + i); if (i > 20) { kony.print("Parent Scope :- kony.timer.schedule -
Stopping timer : ");
© 2015 by Kony, Inc. All rights reserved 825 of 848
Kony Studio API Developer's Guide
Version 5.0
kony.timer.cancel(timerId);
};
}
// kony.timer.schedule(timerId, timerFunc, 1, true); kony.print("Parent Scope :- kony.timer.schedule - Done");
}; kony.print("Parent Scope: Exit test_case_parent_thread()");
WorkerThread.js
//worker
//workers inner scope kony.print("Worker Scope: Init"); var worker = new kony.worker.WorkerThread('WorkerThread2.js');
//invoked when Parent calls worker.postmessage() this.addEventListener("message", function(event) { kony.print('Worker Scope : onmessage : event.data : ' + event.data);
}); self.postMessage("Hello from Worker");
// invoke_timer_task();
// function invoke_timer_task() { kony.print("Worker Scope :- kony.timer.schedule - ");
© 2015 by Kony, Inc. All rights reserved 826 of 848
Kony Studio API Developer's Guide
Version 5.0
var timerId = "mytimer121"; var i = 0; function timerFunc() { i++; kony.print("Worker Scope :- kony.timer.schedule - In timerFunc() : " + i); if(i > 20) { kony.print("Worker Scope :- kony.timer.schedule -
Stopping timer : "); kony.timer.cancel(timerId);
}
};
// kony.timer.schedule(timerId,timerFunc, 1, true); kony.print("Worker Scope :- kony.timer.schedule - Done");
}; kony.print("Worker Scope: Loading done");
WorkerThread2.js
//Grand child worker2 – nested worker
//workers inner scope kony.print("Grand child: Worker2 Scope: Init");
//invoked when Parent calls worker.postmessage() this.addEventListener("message", function(event) { kony.print('Grand child: Worker2 Scope : onmessage : event.data : '
+ event.data);
© 2015 by Kony, Inc. All rights reserved 827 of 848
Kony Studio API Developer's Guide
Version 5.0
}); self.postMessage("Hello from Worker2");
// invoke_timer_task();
// function invoke_timer_task () { kony.print("Grand child: Worker2 Scope :- kony.timer.schedule -
"); var timerId = "mytimer1211"; var i = 0; function timerFunc()
{ i++; kony.print("Worker2 Scope :- kony.timer.schedule - In timerFunc() : " + i + " : Grand child "); if(i > 20) { kony.print("Grand child: Worker2 Scope :kony.timer.schedule - Stopping timer : "); kony.timer.cancel(timerId);
}
};
// kony.timer.schedule(timerId,timerFunc, 1, true); kony.print("Grand child: Worker2 Scope :- kony.timer.schedule -
Done");
}; kony.print("Grand child: Worker2 Scope : Loading done");
© 2015 by Kony, Inc. All rights reserved 828 of 848
Kony Studio API Developer's Guide
Version 5.0
40.13.8.3 Scope Rules and Supported APIs
Global resources in the App context will not be available in the worker thread context as it can lead to
Race conditions since no locking mechanisms are provided.
Every worker has its own context of execution, which is not shared between the parent and its worker.
As a result the global variables in parent scope are not available in worker scope and vice versa.
Not
Supp orted
APIs l
Kony UI APIs and UI object handles l
App Global variables
© 2015 by Kony, Inc. All rights reserved 829 of 848
Kony Studio API Developer's Guide
Version 5.0
Supp orted
APIs and
Platfo rm
String
API
Math
API
Table
API
Standar d Kony
API
Networ k API iO
S
© 2015 by Kony, Inc. All rights reserved
Offline
Data
Access
API
Lo cal
Sto rag e
Operati ng
System
API
We b
SQ
L iO
S iO
S iO
S
An dro id
Cryptog raphy
API iO
S iO
S iO
S iO
S iO
S
An dro id
An dro id
An dro id
An dro id
An dro id
Win dow s
Win dow s
Win dow s
Win dow s
SPA
SPA
SPA
Desktop
Web
Desktop
Web
Desktop
Web
Win dow s
Andr oid
Limited Availability
* For SPA and Desktop Web, the following APIs are supported: l kony.convertToBase64
l kony.convertToRawByte
s l kony.type
l kony.props.getProperty
l kony.print() is not supported in Safari.
l
Kony.print() is supported in Mozilla from version
29.0.
For SPA and DesktopWeb:
Limited Availability n
The following API will not be available in SPA &
Desktop Web.
kony.net.setNetworkCall
backs
830 of 848
Windows
An dro id
Andr oid
Win dow s
Win dow s
Windows SPA and
Desktop
Web not supported
* For SPA and Desktop Web, the following APIs are NOT supported: l kony.os.addHiddenField
l kony.os.readHiddenField
l kony.os.startSecureTran
saction l kony.os.endSecureTrans
action l kony.os.getAppContext
l kony.os.hasAcceleromet
erSupport l kony.os.deviceInfo
l kony.os.deviceInfo
().httpheaders
l kony.os.addMetaTag
l kony.os.removeMetaTag
l kony.os.removeAllMetaT
ags l kony.os.hasGPSSupport
l kony.os.hasCameraSupp
ort l kony.os.hasTouchSuppor
t l kony.os.hasOrientationS
upport l kony.os.getDeviceCurren
tOrientation l kony.os.print
* For SPA and Desktop Web, the following APIs are NOT supported: l kony.crypto.saveKey
l kony.crypto.deleteKey
l kony.crypto.readKey
Kony Studio API Developer's Guide
Version 5.0
Supported List of Browsers
SPA iOS
5.0-
5.1
Blackberry
OS
7.0
4.4
Android
Native
33.0
Android
Chrome
DesktopWeb
IE
10.0
Firefox Chrome Safari
4.0
20 5.0
40.13.8.4 FFI and Custom Widgets
With and without Functional Module in Worker context:
FFI
Custom Widgets iOS Android
Platform will load modules by default
Windows
No need to load Custom Widgets in worker scope.
8
Windows phone
OS
SPA
40.13.8.5 Guidelines and Limitations
The following guidelines are recommended before using worker thread:
1. The objects “this” and “self” are available in worker thread inner scope that is referred as worker thread itself.
© 2015 by Kony, Inc. All rights reserved 831 of 848
Kony Studio API Developer's Guide
Version 5.0
2. Event propagation cannot be stopped by using event.stopPropagation() as in HTML specification. Where event.stopPropagation() stops the DOM event to be propagated further by breaking the event chain.
3. Data passed between the main thread and workers are copied, but not shared. Objects are serialized as they are handed to the worker, and subsequently, de-serialized on the other end.
The main thread and worker do not share the same instance. So the end result is that a duplicate is created on each end. HTML5 worker threads support transferable objects that allow transferring the objects from one thread to other without making a copy.
Guidelines for SPA and DesktopWeb:
1. Nested Workers support will be available only if they are supported by the underlying browser platforms.
2. Error event messages in error event handler sometimes might be appended with extra prefix or suffix string messages from underlying browsers (like Uncaught, Uncaught error etc).
3. Even though error event handler is invoked in case of unhandled exceptions, the same event messages might also be logged on browser console.
4. Line number, file name populated in error event object passed to error event handler might be different from user defined files.
Note: For SPA and Desktop Web, nested workers are not supported in Google Chrome.
40.13.8.6 Worker Thread Life Cycle
The following steps provide the work flow to use worker thread:
1. Create a new worker instance (by calling the worker thread constructor). The new instance starts executing in a separate thread of control in an asynchronous manner. In this new thread, first the worker will try to load the ‘workerjs’ script.
© 2015 by Kony, Inc. All rights reserved 832 of 848
Kony Studio API Developer's Guide
Version 5.0
2. As a result of the asynchronous nature of execution of worker thread, invocation of worker constructor call in parent thread will immediately return a new worker instance handle and parent proceeds execution of next instructions.
3. In worker thread scope when there is no message event handler registered that indicates no tasks can be posted or queued by parent for this worker, and if no callbacks are registered in this worker scope for network, timer APIs etc, then after postMessage() call in workers inner scope, worker can terminate itself without worker.terminate() being called in parent scope or self.close
() called in inner scope.
4. In case of orphaned threads, if no tasks are queued in message handler and if the worker is not waiting for any callbacks to be returned from network, timer APIs etc then the orphaned thread can be terminated.
5. If parent stops either due to unhandled exception raised in its scope, worker threads still continue to exist and execute.
© 2015 by Kony, Inc. All rights reserved 833 of 848
41. Appendix: General FAQ Kony Studio API Developer's Guide
Version 5.0
41. Appendix: General FAQ
This appendix explains a few frequently asked questions (FAQs).
41.1 Network Calls
Can I cancel synchronous network calls?
Canceling synchronous network calls in not a cross platform feature. Platforms like iPhone and
BlackBerry provide a means of canceling synchronous network calls, which is very specific to those platforms.
For example, on iPhone, the developer can choose to show the Cancellation popup. If this option is available, the cancel option pops up from the bottom of the screen allowing the developer to cancel the synchronous service call.
Can I handle the logic that needs to be executed when a synchronous network call is canceled?
Yes. When a network call is canceled, an error is thrown with opstatus 1021. Because cancellation of synchronous calls is not cross platform, ensure that any logic that is written to handle 1021 opstatus does not have any business logic but displays a proper message to the user.
Is blocking the UI still an option that I can choose while making a synchronous network call?
The isBlocking parameter is not considered by platforms (except for iPhone). Only way to block the user interface is by explicitly using
showLoadingScreen
API supported by Kony Platform.
What is the advantage of asynchronous network calls compared to the synchronous network calls?
Any network call goes through the following phases:
1. Phase 1: preparing network request
2. Phase 2: making a network connection and wait for response
© 2015 by Kony, Inc. All rights reserved 834 of 848
41. Appendix: General FAQ Kony Studio API Developer's Guide
Version 5.0
3. Phase 3: handle the returned response.
In case of synchronous calls, user clicks and touches on any widget of the form are ignored until network call finishes all the three phases. In case of asynchronous network calls, users can execute any logic while the network is busy waiting for the response.
Phase 1 and Phase 2 are handled by Kony Platform and Phase 3 a callback function is executed (the function that is passed to the asynchronous network call).
What are the important considerations for using Asynchronous network calls?
Kony Platform runs all the functions attached to the widgets and the callback for asynchronous network call in a single thread except for some of the system events.
The callback function is queued if any of the functions are in execution. This may lead to the order of execution issues.
Because the user can execute any other functions while waiting for the response of the network call, this may lead to the order of execution issues.
For example, user is performing account deletion logic by invoking a network call asynchronously.
During the same time, user may end up updating the same account by executing another network call or a function. This could lead to erroneous data.
For example, user is performing the retrieval of accounts through asynchronous network call and if the user moves to the functionality that depends on the availability of the accounts, then application should display the appropriate message or block the UI till account retrieval is completed.
When to use asynchronous network calls?
In general, asynchronous calls should be preferred over synchronous calls in all situations. However, user should be aware that order of execution issues may creep in and handle such situations.
When you want to make network calls as part of the following events, use asynchronous network calls: l pre-appinit
© 2015 by Kony, Inc. All rights reserved 835 of 848
41. Appendix: General FAQ Kony Studio API Developer's Guide
Version 5.0
l post-appinit l transactionalDataLoad l onIdleTimeout l onBackground l onForeground l appmenuevents.
How to handle error codes thrown by the network calls?
Define handlers for all the error codes including the generic error code. If a particular platform cannot distinguish an error case specifically, the platform throws a generic error.
Can I click/touch the widgets on a form and trigger an action when a function is getting executed?
No. As explained earlier, because executing the logic corresponding to touches/gestures on the form is run in a single thread.
Are the asynchronous callbacks (associated with asynchronous network call) executed when a function is under execution?
Yes. All Asynchronous callbacks are queued and executed on the main thread. Hence the callbacks are always guaranteed for execution when the current thread completes its current job.
Can I control the timeout of a network call?
No. Kony Platform does not support changing the timeout period. The default timeout period is 3 minutes.
Can I make the network calls outside the Kony Application Server?
No. Kony Platform does not support making network calls outside the Kony Application Server.
© 2015 by Kony, Inc. All rights reserved 836 of 848
41. Appendix: General FAQ Kony Studio API Developer's Guide
Version 5.0
Are the network calls authenticated against the Kony Application Server?
Yes. The basic form based authentication is used between devices and the Kony Application Server.
The relevant authentication headers are added to the application code in a transparent way.
Can the platform support un-trusted certificates when making HTTPS network calls ?
Apple does not allow usage of the private APIs (used to support un-trusted certificates) in the applications as part of application certification process. In platforms like Android, though there are ways to allow un-trusted certificates it is not guaranteed across the family of Android devices. Using un-trusted certificates also leads to security issues. Hence, on Kony Platform use of valid and trusted certificates is mandatory for secure (HTTPS) communication.
What are the certificates that are treated as trusted and work cross-platform?
iPhone http://support.apple.com/kb/HT3580 http://support.apple.com/kb/HT4415 .
Android
Only the certificates issued by CA that are bundled with the application.
BlackBerry
All the certificates installed on the device. Navigate to Options -> Security -> Advanced
Security Settings -> Certificates to see the installed certificates.
Windows Phone l
America Online Root Certification Authority 2 l
America Online Root Certification Authority 1 l
COMODO RSA Certification Authority
© 2015 by Kony, Inc. All rights reserved 837 of 848
41. Appendix: General FAQ Kony Studio API Developer's Guide
Version 5.0
l
USERTrust RSA Certification Authority l
COMODO ECC Certification Authority l
USERTrust ECC Certification Authority l
UTN-USERFirst-Hardware l
UTN - DATACorp SGC l
AddTrust External CA Root l
DigiCert Assured ID Root CA l
DigiCert High Assurance EV Root CA l
DigiCert Global Root CA.
For more certificates, see http://www.microsoft.com
.
For uniform cross-platform behavior, select a trusted root certificate which works across the devices.
How do I disable the widgets (such as text box, text area) or the complete form while a network call is in progress ?
You have the following options: l
Use the window.showloadingscreen API to block the UI while the network call is in progress.
l
Use widget.setenabled method to disable the widgets one after the other. But in this approach, you must remember to enable the widgets after the completion of the network call.
© 2015 by Kony, Inc. All rights reserved 838 of 848
41. Appendix: General FAQ Kony Studio API Developer's Guide
Version 5.0
41.2 form.destroy API
When I invoke form.destroy API, will I lose the widgets and data associated with the widgets also?
Yes. When
form.destroy
is invoked, complete form along with its widgets and data associated with the widgets will be lost. It is the developer's responsibility to save any critical, easily nonreproducible data using
ds.save
before invoking
form.destroy
API.
Can I access the form that was destroyed?
Yes. If you access the form that was destroyed, either by calling form.show or by accessing the widgets on the form or by accessing the properties of the form, the form will undergo through the entire form lifecycle.
© 2015 by Kony, Inc. All rights reserved 839 of 848
42. Appendix: JavaScript FAQ Kony Studio API Developer's Guide
Version 5.0
42. Appendix: JavaScript FAQ
Can I use the standard JavaScript features like prototypes, "this", function semantics, or do I have to use a "restricted JavaScript"?
Yes, the JavaScript runtime environment embedded by the Kony platform is ECMA 262 compliant. So all the standard JavaScript features are available out of the box. All the custom Functions and Objects defined by the developer have access to standard JavaScript features. Though the JavaScript
Objects/Functions created/defined by the Kony APIs adhere to this specification there are some known limitations that one must be aware of. These limitations mostly arise from the limitations posed by the JavaScript runtime environment when invoking native SDK APIs (defined in a different
language). These limitations have been captured under the sections " JavaScript Function Semantics "
and " JavaScript Object Semantics
".
What are the different JavaScript runtime environments that Kony platform bundles for each of the Mobile platforms?
iOS
Platform
Android
BlackBerry
MobileWeb
SPA
Windows Phone
Windows
Desktop
Supported Version
4.0 and above
2.1 and above
5.0 and above
All iOS,Android,BlackBerry,Windows
7.5
7.5 and above
Coming soon
JavaScript Engine
JS Core
Google V8 (via NDK)
Native BrowserField
---
JS engine embedded in the browser
Jurassic
Coming soon
© 2015 by Kony, Inc. All rights reserved 840 of 848
42. Appendix: JavaScript FAQ Kony Studio API Developer's Guide
Version 5.0
Are there any JavaScript constraints or cross platform nuances that I should be aware of when developing on Kony platform ?
Yes, even though Kony platform bundles or uses widely used JavaScript runtime environment, there are some JavaScript APIs that don't work consistently across the JavaScript runtime environments.
Below are some of the JavaScript operators and semantics that can result in inconsistent experience across runtimes and should be avoided: l typeof operator for the Objects created and returned by the Kony APIs l instanceof operator for the Objects created and returned by the Kony APIs
I like that Kony now supports JavaScript. Can I pick a JavaScript based 3rd party library and include it in my project codebase ?
Yes, you can integrate any Javascript library which is purely written in Javascript language without any native, browser dependencies. In case the JavaScript library depends upon a browser DOM then it would only work on the SPA channel.
I see some of the widgets like Form and Image have got a "2" as suffix when creating the widget.
For instance, when creating the form we have to say com.kony.ui.Form2. Why do we need to have "2" as suffix for these widgets ?
When drafting the specifications for the JavaScript APIs there was a conscious effort to ensure common cross platform behavior of some of the widgets. We realized that unless we break some backward compatibility the widget behavior cannot be made consistent across platforms. Hence Kony came with new API definitions for these widgets with the intention to consolidate the cross platform behavior. A version "2" of these widgets was introduced.
So in general is it recommended to use kony.ui.Image2 or kony.ui.Image, should I use the version "2" of the widgets or their original version ?
For better cross platform behavior we recommend you to use the kony.ui.Image2 widget wherever possible. The original version of the widgets have been retained only for backward compatibility.
© 2015 by Kony, Inc. All rights reserved 841 of 848
42. Appendix: JavaScript FAQ Kony Studio API Developer's Guide
Version 5.0
Can I use Octal literals in my JavaScript Code?
Octal literals should be avoided in JavaScript Code. Numbers prefixed with 0 will be treated as octal numbers by most of the Javascript Engines but some throw an exception. If you want to parse the octal number from a string variable, use parseInt with radix parameter.
© 2015 by Kony, Inc. All rights reserved 842 of 848
43. Appendix: SQLite Kony Studio API Developer's Guide
Version 5.0
43. Appendix: SQLite
SQLite is a database engine packaged along with the native sdk. This section comprises the following: l
l
l
l
Determination of Column Affinity
l
Affinity Name JavaScript Example
l
Column Affinity Behavior JavaScript Example
43.1 SQLite Characteristics
SQLite has the following characteristics: l
It is embedded with the native sdk.
l
It is ACID-compliant (atomicity, consistency, isolation, durability).
l
It is weakly-typed i.e, any object can be stored in any column, regardless of how that column was declared. For example you can insert a string into a database column of type integer l
It does not officially support foreign key constraints, although triggers can be used as a workaround.
l
It does not support RIGHT OUTER JOINs.
43.2 SQLite Column Types
Most databases use strong, static column typing which means that the elements of a column can only hold values compatible with the defined type of a column. SQLite utilizes a dynamic typing technique known as manifest typing. For each row value, manifest typing records the value's type along with the
© 2015 by Kony, Inc. All rights reserved 843 of 848
43. Appendix: SQLite Kony Studio API Developer's Guide
Version 5.0
value data. This allows nearly any element of any row to hold almost any type of value. In the strictest sense, SQLite supports only five concrete datatypes. These are known as storage classes, and represent the different ways SQLite stores data on disk.
Every value has one of these five native storage classes: l
NULL: NULL is considered its own distinct type. A NULL type does not hold a value. Literal
NULLs are represented by the keyword NULL.
l
Integer: A signed integer number. Integer values are variable length, being 1, 2, 3, 4, 6, or 8 bytes in length, depending on the minimum size required to hold the specific value. Integer have a range of 9,223,372,036,854,775,808 to +9,223,372, 036,854,775,807, or roughly 19 digits.
Literal integers are represented by any bare series of numeric digits (without commas) that does not include a decimal point or exponent.
l
REAL: The value is a floating-point number, stored as an 8-byte value in the processor's native format. For most modern processors, this is an IEEE 754 double-precision number. Literal floating-point numbers are represented by any bare series of numeric digits that include a decimal point or exponent.
l
Text: A variable-length string, stored using the database encoding (UTF-8, UTF-16BE, or UTF-
16LE). Literal text values are represented using character strings in single quotes.
l
BLOB: A length of raw bytes, copied exactly as provided. Literal BLOBs are represented as hexadecimal text strings preceded by an x. For example, the notation x'1234ABCD' represents a 4-byte BLOB. BLOB stands for Binary Large OBject. SQLite text and BLOB values are always variable length. The maximum size of a text or BLOB value is limited by a compile-time directive.
The default limit is exactly one billion bytes, or slightly less than a full gigabyte. The maximum value for this directive is two gigabytes.
© 2015 by Kony, Inc. All rights reserved 844 of 848
43. Appendix: SQLite Kony Studio API Developer's Guide
Version 5.0
43.3 Type Affinity
The elements of most columns can hold any value type, the "type" of a column could be misleading.
Rather than being an absolute type,like most databases, an SQLite column type (as defined in
CREATE TABLE) becomes more of a suggestion than a hard and fast rule. This is known as type affinity, and essentially represents a desired category of type. Each type affinity has specific rules about what types of values it can store, and how different values will be converted when stored in that column. Generally, type affinity will cause conversion or migration of types only if it can be done without losing data or precision.
Each table column must have one of five type affinities: l
Text: A column with a text affinity will only store values of type NULL, text, or BLOB. If you attempt to store a value with a numeric type (float or integer) it will be converted into a text representation before being stored as a text value type.
l
Numeric: A column with a numeric affinity will store any of the five types. Values with integer and float types, along with NULL and BLOB types, are stored without conversion. Any time a value with a text type is stored, an attempt is made to convert the value to a numeric type
(integer or float). Assuming the conversion works, the value is stored in an appropriate numeric type. If the conversion fails, the text value is stored without any type of conversion.
l
Integer: A column with an integer affinity works essentially the same as a numeric affinity. The only difference is that any value with a float type that lacks a fractional component will be converted into an integer type.
l
Real: A column with REAL affinity behaves like a column with NUMERIC affinity except that it forces integer values into floating point representation.
l
None: A column with a none affinity has no preference over storage class. Each value is stored as the type provided, with no attempt to convert anything.
© 2015 by Kony, Inc. All rights reserved 845 of 848
43. Appendix: SQLite Kony Studio API Developer's Guide
Version 5.0
43.4 Determination Of Column Affinity
Since type affinities are not part of the SQL standard, SQLite has a series of rules that attempt to map traditional column types to the most logical type affinity. The type affinity of a column is determined by the declared type of the column, according to the following rules (substring matches are caseinsensitive):
1. If no column type was given, then the column is given the none affinity.
2. If the column type contains the substring "INT," then the column is given the integer affinity.
3. If the column type contains any of the substrings "CHAR," "CLOB," or "TEXT," then the column is given the text affinity.
4. If the column type contains the substring "BLOB," then the column is given the none affinity.
5. If the column type contains any of the substrings "REAL," "FLOA," or "DOUB," then it is given the float real affinity.
6. If no match is found, the column is assigned the numeric affinity.
As implied by the first rule, the column type is completely Optional. SQLite will allow you to create a table by simply naming the columns, such as CREATE TABLE t ( i, j,k);. You'll also notice that there isn't any specific list of column types that are recognized. You can use any column type you want, even making up your own names. This might sound a bit fast and loose for a typing system, but it works out quite well. By keying off specific substrings, rather than trying to define specific types, SQLite is able to handle SQL statements (and their database-specific types) from just about any database, all while doing a pretty good job of mapping the types to an appropriate affinity. Note that a declared type of
"FLOATING POINT" would give INTEGER affinity, not REAL affinity, due to the "INT" at the end of
"POINT". And the declared type of "STRING" has an affinity of NUMERIC, not TEXT.
43.5 Affinity Name Example
The following table shows how many common datatype names from more traditional SQL implementations are converted into affinities by the six rules of the previous section.
© 2015 by Kony, Inc. All rights reserved 846 of 848
43. Appendix: SQLite Kony Studio API Developer's Guide
Version 5.0
JavaScript Example Typenames From The CREATE
TABLE Statement or CAST Expression
Resulting
Affinity
INT, INTEGER, TINYINT, SMALLINT, MEDIUMINT, BIGINT,
UNSIGNED BIG INT, INT2, INT8
INTEGER 2
Rule Used
To
Determine
Affinity
TEXT 3 CHARACTER(20), VARCHAR(255), VARYING CHARACTER
(255), NCHAR(55), NATIVE CHARACTER(70), NVARCHAR
(100), TEXT, CLOB
BLOB no datatype specified NONE 1,4
REAL, DOUBLE, DOUBLE PRECISION, FLOAT
NUMERIC, DECIMAL(10,5) , BOOLEAN, DATE, DATETIME
REAL
NUMERIC
5
6
43.6 Column Affinity Behavior Example
CREATE TABLE t1( t TEXT, -- text affinity by rule 3 nu NUMERIC, -- numeric affinity by rule 6 i INTEGER, -- integer affinity by rule 2 r REAL, -- real affinity by rule 5 no BLOB -- no affinity by rule 1,4
);
-- Values stored as TEXT, INTEGER, INTEGER, REAL, TEXT.
INSERT INTO t1 VALUES('500.0', '500.0', '500.0', '500.0', '500.0');
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
4 text|integer|integer|real|text
© 2015 by Kony, Inc. All rights reserved 847 of 848
43. Appendix: SQLite Kony Studio API Developer's Guide
Version 5.0
-- Values stored as TEXT, INTEGER, INTEGER, REAL, REAL.
DELETE FROM t1;
INSERT INTO t1 VALUES(500.0, 500.0, 500.0, 500.0, 500.0);
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1; text|integer|integer|real|real
-- Values stored as TEXT, INTEGER, INTEGER, REAL, INTEGER.
DELETE FROM t1;
INSERT INTO t1 VALUES(500, 500, 500, 500, 500);
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1; text|integer|integer|real|integer
-- BLOBs are always stored as BLOBs regardless of column affinity.
DELETE FROM t1;
INSERT INTO t1 VALUES(x'0500', x'0500', x'0500', x'0500', x'0500');
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1; blob|blob|blob|blob|blob
-- NULLs are also unaffected by affinity
DELETE FROM t1;
INSERT INTO t1 VALUES(NULL,NULL,NULL,NULL,NULL);
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1; null|null|null|null|null
Note: Columns of type INTEGER PRIMARY KEY may only hold a 64-bit signed integer. An error will result if you try to put anything other than an integer into an INTEGER PRIMARY KEY column.
© 2015 by Kony, Inc. All rights reserved 848 of 848
Download
Advertisement
Key features
Visual development environment
Device independent wire-frame format design
Rapid development and deployment
Supports multiple platforms and browsers
Provides APIs for various operations
Offers a comprehensive set of features for mobile app development
Frequently asked questions
Kony Studio is an integrated development environment (IDE) for rapid development and deployment of mobile applications.
Kony Studio provides a visual development environment, device independent wire-frame format design, rapid development and deployment, support for multiple platforms and browsers, comprehensive set of APIs for various operations, and a comprehensive set of features for mobile app development.
This document explains the Application Program Interface (API) used in Kony Studio and provides procedural information to use them to achieve functionality.
This document is targeted at developers who use Kony Studio to develop applications.