Skip to content
This repository was archived by the owner on Nov 17, 2022. It is now read-only.

Commit f81d615

Browse files
authored
Merge pull request #1422 from NativeScript/niliev/native-apis
add ts examples and overall improvments
2 parents 80f18b1 + 85cc8fd commit f81d615

File tree

1 file changed

+109
-36
lines changed

1 file changed

+109
-36
lines changed

docs/core-concepts/accessing-native-apis-with-javascript.md

Lines changed: 109 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,24 @@ In this article, you will learn how to call native APIs from JavaScript with var
1717

1818
All native numeric types (e.g., char, short, int, double, float on iOS and byte, short, int, long, double, float on Android) are implicitly converted to JavaScript number and vice versa. For example, when you run the following code on iOS:
1919

20+
- iOS
21+
2022
```JavaScript
21-
// iOS
22-
console.log('pow(2.5, 3) = ', pow(2.5, 3));
23+
console.log(`pow(2.5, 3) = ${pow(2.5, 3)}`);
24+
```
25+
```TypeScript
26+
console.log(`pow(2.5, 3) = ${pow(2.5, 3)}`);
2327
```
2428

2529
the iOS Runtime converts the JavaScript number literals to native doubles and passes them to the native `pow(double x, double y)` function. The returned native integer is automatically converted to a JavaScript number and passed to `console.log()`. The same is valid for Android:
2630

31+
- Android
32+
2733
```JavaScript
28-
// Android
29-
console.log('min(3, 4) = ', java.lang.Math.min(3, 4));
34+
console.log(`min(3, 4) = ${java.lang.Math.min(3, 4)}`);
35+
```
36+
```TypeScript
37+
console.log(`min(3, 4) = ${java.lang.Math.min(3, 4)}`);
3038
```
3139

3240
The native `java.lang.Math.min()` method expects two integers. The Android Runtime knows the signature of the function `java.lang.Math.min()` and translates the literals `3` and `4` to their representation in a Java integer data type. The returned integer is also automatically translated to a JavaScript number and passed to `console.log()`.
@@ -35,16 +43,26 @@ The native `java.lang.Math.min()` method expects two integers. The Android Runti
3543

3644
JavaScript strings are implicitly marshalled to `java.lang.String` on Android and `NSString` on iOS and vice versa.
3745

46+
- iOS
47+
3848
```JavaScript
39-
// iOS
40-
var button = new UIButton();
49+
let button = new UIButton();
50+
button.setTitleForState('Button title', UIControlStateNormal); // 'Button title' is converted to NSString
51+
console.log(button.titleLabel.text); // The returned NSString is converted to JavaScript string
52+
```
53+
```TypeScript
54+
let button = new UIButton();
4155
button.setTitleForState('Button title', UIControlStateNormal); // 'Button title' is converted to NSString
4256
console.log(button.titleLabel.text); // The returned NSString is converted to JavaScript string
4357
```
4458

59+
- Android
60+
4561
```JavaScript
46-
// Android
47-
var file = new java.io.File('myfile.txt'); // 'myfile.txt' is converted to java.lang.String
62+
const file = new java.io.File('myfile.txt'); // 'myfile.txt' is converted to java.lang.String
63+
```
64+
```TypeScript
65+
const file = new java.io.File('myfile.txt'); // 'myfile.txt' is converted to java.lang.String
4866
```
4967

5068
The exception to this are the methods on `NSString` classes declared as returning `instancetype` - init methods and factory methods. This means that a call to `NSString.stringWithString` whose return type in Objective-C is `instancetype` will return a wrapper around a `NSString` instance rather than a JavaScript string.
@@ -55,38 +73,62 @@ The exception to this are the methods on `NSString` classes declared as returnin
5573

5674
JavaScript boolean values are implicitly marshalled to `boolean` on Android and `BOOL` on iOS and vice versa.
5775

76+
- iOS
77+
5878
```JavaScript
59-
// iOS
60-
var str = NSString.stringWithString('YES');
61-
var isTrue = str.boolValue();
79+
let str = NSString.stringWithString('YES');
80+
let isTrue = str.boolValue();
81+
```
82+
```TypeScript
83+
let str = NSString.stringWithString('YES');
84+
let isTrue = str.boolValue();
6285
```
6386

87+
- Android
88+
6489
```JavaScript
65-
// Android
66-
var str = new java.lang.String('Hello world!');
67-
var result = str.endsWith('world!');
90+
let str = new java.lang.String('Hello world!');
91+
let result = str.endsWith('world!');
92+
console.log(result); // true
93+
```
94+
```TypeScript
95+
let str = new java.lang.String('Hello world!');
96+
let result = str.endsWith('world!');
6897
console.log(result); // true
6998
```
7099

71100
## Array
72101

73102
JavaScript arrays map to specialized Java arrays on Android and `NSArray` on iOS.
74103

104+
- iOS
105+
75106
```JavaScript
76-
// iOS
77107
// nsArray is not a JavaScript array but a JavaScript wrapper around a native NSArray
78-
var nsArray = NSArray.arrayWithArray(['Four', 'Five', 'Two', 'Seven']);
79-
var jsArray = ['One', 'Two', 'Three']; // pure JavaScript array
80-
var firstCommon = nsArray.firstObjectCommonWithArray(jsArray);
108+
let nsArray = NSArray.arrayWithArray(['Four', 'Five', 'Two', 'Seven']);
109+
let jsArray = ['One', 'Two', 'Three']; // pure JavaScript array
110+
let firstCommon = nsArray.firstObjectCommonWithArray(jsArray);
81111
console.log(firstCommon); // Two
82112
```
113+
```TypeScript
114+
// nsArray is not a JavaScript array but a JavaScript wrapper around a native NSArray
115+
let nsArray = NSArray.arrayWithArray(['Four', 'Five', 'Two', 'Seven']);
116+
let jsArray = ['One', 'Two', 'Three']; // pure JavaScript array
117+
let firstCommon = nsArray.firstObjectCommonWithArray(jsArray);
118+
console.log(firstCommon); // Two
119+
```
120+
121+
- Android
83122

84123
The following code snippet shows how to call a `ns.example.Math.minElement(int[] array)` from JavaScript:
85124

86125
```JavaScript
87-
// Android
88-
var numbers = [3, 6, 19, -2, 7, 6];
89-
var min = ns.example.Math.minElement(numbers); // -2
126+
let numbers = [3, 6, 19, -2, 7, 6];
127+
let min = ns.example.Math.minElement(numbers); // -2
128+
```
129+
```TypeScript
130+
let numbers = [3, 6, 19, -2, 7, 6];
131+
let min = ns.example.Math.minElement(numbers); // -2
90132
```
91133

92134
## Classes and Objects
@@ -98,8 +140,11 @@ All native classes are represented in the JavaScript world by a constructor func
98140
Here is an example of how an instance of the `NSMutableArray` class is made and consumed in JavaScript:
99141

100142
```JavaScript
101-
// iOS
102-
var array = new NSMutableArray();
143+
let array = new NSMutableArray();
144+
array.addObject(new NSObject());
145+
```
146+
```TypeScript
147+
let array = new NSMutableArray();
103148
array.addObject(new NSObject());
104149
```
105150

@@ -109,47 +154,75 @@ This snippet creates an instance of `NSMutableArray` and adds an object to it us
109154

110155
You will most probably encounter methods accepting NSDictionary instances as parameters. There are few ways of creating an NSDictionary instance:
111156

112-
```Javascript
113-
var dict = new NSDictionary([".example.com", "cookieName", "/", "cookieValue"], [NSHTTPCookieDomain, NSHTTPCookieName, NSHTTPCookiePath,NSHTTPCookieValue]);
114-
var cookie = NSHTTPCookie.cookieWithProperties(dict);
157+
- Using `NSDictionary` and passing arrays for keys and values.
158+
159+
```JavaScript
160+
let dict = new NSDictionary([".example.com", "cookieName", "/", "cookieValue"], [NSHTTPCookieDomain, NSHTTPCookieName, NSHTTPCookiePath,NSHTTPCookieValue]);
161+
let cookie = NSHTTPCookie.cookieWithProperties(dict);
115162
```
163+
```TypeScript
164+
let dict = new NSDictionary([".example.com", "cookieName", "/", "cookieValue"], [NSHTTPCookieDomain, NSHTTPCookieName, NSHTTPCookiePath,NSHTTPCookieValue]);
165+
let cookie = NSHTTPCookie.cookieWithProperties(dict);
166+
```
167+
168+
- Using JSON literals
116169

117-
```Javascript
118-
var cookie = NSHTTPCookie.cookieWithProperties({[NSHTTPCookieDomain]:".example.com", [NSHTTPCookieName]:"cookieName", [NSHTTPCookiePath]:"/", [NSHTTPCookieValue]:"cookieValue"});
170+
```JavaScript
171+
let cookie = NSHTTPCookie.cookieWithProperties({[NSHTTPCookieDomain]:".example.com", [NSHTTPCookieName]:"cookieName", [NSHTTPCookiePath]:"/", [NSHTTPCookieValue]:"cookieValue"});
119172
```
173+
```TypeScript
174+
let cookie = NSHTTPCookie.cookieWithProperties({[NSHTTPCookieDomain]:".example.com", [NSHTTPCookieName]:"cookieName", [NSHTTPCookiePath]:"/", [NSHTTPCookieValue]:"cookieValue"});
175+
```
176+
177+
120178
In the second example we are passing a JSON literal to the method.**NSHTTPCookieDomain** is a variable and we need to use a [computed property name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) in order to have its value (otherwise we are getting *"NSHTTPCookieDomain"* as key).
121179

122180
### Working With Classes And Objects on Android
123181

124182
The following code snippet demonstrates how an instance of the `android.widget.Button` is created in JavaScript:
125183

126184
```JavaScript
127-
// Android
128-
var context = ...;
129-
var button = new android.widget.Button(context);
185+
let context = ...;
186+
let button = new android.widget.Button(context);
187+
button.setText("My Button"); // "My Button" is converted to java.lang.String
188+
```
189+
```TypeScript
190+
let context = ...;
191+
let button = new android.widget.Button(context);
130192
button.setText("My Button"); // "My Button" is converted to java.lang.String
131193
```
194+
132195
As you can see, the native Java types are exposed through their corresponding packages. In other words, to access a native Java type, you simply need to know the package it is contained in and explicitly state it. Native Java methods are accessed in the same way as regular JavaScript methods: by using the method identifier and supplying the required arguments. You can read more about Java packages on Android [here](https://docs.nativescript.org/runtimes/android/metadata/accessing-packages).
133196

134197
## Undefined and Null
135198

136199
JavaScript [Undefined](http://www.w3schools.com/jsref/jsref_undefined.asp) & [Null](http://www.w3schools.com/js/js_datatypes.asp) map to Java null pointer and Objective-C nil. Native null values map to JavaScript null.
137200

201+
- iOS
202+
138203
```JavaScript
139-
// iOS
140204
console.log(NSStringFromClass(null)); // null
141205
```
206+
```TypeScript
207+
console.log(NSStringFromClass(null)); // null
208+
```
209+
210+
- Android
142211

143212
```JavaScript
144-
// Android
145-
var context = ...;
146-
var button = new android.widget.Button(context);
213+
let context = ...;
214+
const button = new android.widget.Button(context);
215+
button.setOnClickListener(undefined); // the Java call will be made using the null keyword
216+
```
217+
```TypeScript
218+
let context = ...;
219+
const button = new android.widget.Button(context);
147220
button.setOnClickListener(undefined); // the Java call will be made using the null keyword
148221
```
149222

150223
## IntelliSense and Access to the Native APIs via TypeScript
151224

152-
To have access and Intellisense for the native APIs, you have to add a dev dependency to `tns-platform-declarations`
225+
To have access and Intellisense for the native APIs, you have to add a developer dependency to `tns-platform-declarations`.
153226

154227
Steps to install and enable
155228

0 commit comments

Comments
 (0)