Check out this quick tour to find the best demos and examples for you, and to see how the Felgo SDK can help you to develop your next app or game!
The nativeUtils context property allows opening native message boxes, input dialogs and browsers. More...
Import Statement: | import Felgo 3.0 |
This object is available as a context property from all QML components when Felgo is imported via import Felgo 3.0
. It is accessible with the name nativeUtils
. The nativeUtils
context property allows to open platform-specific widgets for displaying message boxes and input dialogs. These elements have the same style as other dialogs of the platform. You can use it as a convenience, when designing custom
dialogs matching your game's UI is not desired.
The nativeUtils
context property also allows to open the browser on the mobile and desktop platforms with openUrl().
The following example shows a message box with 2 buttons to check if the app should be quit when the back key is pressed or when pressed on the quit button. When the Open Felgo Website
button is clicked, the Felgo
website is opened in the default external browser application of the system.
import Felgo 3.0 import QtQuick 2.0 GameWindow { Scene { SimpleButton { text: "Quit app" onClicked: openMessageBoxWithQuitQuestion() } // the "Back" key is used on Android to close the app when in the main scene focus: true // this guarantees the key event is received Keys.onBackButtonPressed: openMessageBoxWithQuitQuestion() SimpleButton { text: "Open Felgo Website" onClicked: nativeUtils.openUrl("https://felgo.com") } } // the result of the messageBox is received with a connection to the signal messageBoxFinished Connections { target: nativeUtils // this signal has the parameter accepted, telling if the Ok button was clicked onMessageBoxFinished: { console.debug("the user confirmed the Ok/Cancel dialog with:", accepted) if(accepted) Qt.quit() } } function openMessageBoxWithQuitQuestion() { // show an Ok and Cancel button, and no additional text nativeUtils.displayMessageBox(qsTr("Really quit the game?"), "", 2); } }
This example shows how to query user input and to save it in a Text element.
import Felgo 3.0 import QtQuick 2.0 GameWindow { Scene { id: scene property string userName: "My Username" SimpleButton { text: "Enter User Name" // the input text will be pre-filled with the current userName // if it is the first time the user is queried the userName, it will be "My Username" onClicked: nativeUtils.displayTextInput("Your user name:", "", "", scene.userName); } } // the result of the input dialog is received with a connection to the signal textInputFinished Connections { target: nativeUtils // this signal has the parameters accepted and enteredText onTextInputFinished: { // if the input was confirmed with Ok, store the userName as the property if(accepted) { scene.userName = enteredText; console.log("Entered userName:", scene.userName); } } } }
Note: If you have multiple sources where you could start MessageBoxes or InputDialogs, you need to store which source started the MessageBox or InputDialog in a property. Otherwise you would not know which source originated the nativeUtils call. In a future SDK version, the MessageBox and InputDialog will be available as own QML items, which makes this workaround obsolete. To accelerate this integration, please contact us so we know you would need this feature urgently.
This example shows how to take a screenshot of the current screen and store it in a temporary folder on the device. See FileUtils for more information.
That image can then be shared with other apps using the share() method. Additionally, the screenshot it displayed using the AppImage component.
import Felgo 3.0 import QtQuick 2.0 App { id: app property url imageUrl: "" NavigationStack { id: stack Page { title: "Share screenshot" Column { anchors.fill: parent AppButton { text: "Take screenshot" onClicked: stack.grabToImage(function(result) { var fileName = "Image" + new Date().getTime() + ".png" var filePath = fileUtils.storageLocation(FileUtils.TempLocation, fileName) result.saveToFile(filePath) app.imageUrl = fileUtils.getUrlByAddingSchemeToFilename(filePath) }) } AppImage { id: resultImage width: app.width - dp(40) x: dp(20) height: dp(200) fillMode: Image.PreserveAspectFit autoTransform: true source: app.imageUrl } AppButton { text: "Share image" onClicked: nativeUtils.share("Image from Felgo", app.imageUrl) } } } } }
In Felgo you code with QML, so going native first means to step into the Qt C++ world. You can find a guide how to mix Felgo QML code with Qt C++ components here: How to Expose a Qt C++ Class with Signals and Slots to QML
The demo is also available with the Felgo SDK: <Path to Felgo>/Examples/Felgo/appdemos/cpp-qml-integration
Working with your native Android code from C++ then requires JNI as the bridge between the two languages. Weaving in native iOS code is a little easier, as Objective-C is directly compatible with C++. But before you dive in too deep: Our developers are experts at building such native integrations, and we're happy to add features or build extensions as part of our support package offering!
Find more examples for frequently asked development questions and important concepts in the following guides:
contacts : var |
Contains a list of all contacts including name and all phone numbers per contact. This property is only supported on Android and iOS.
On iOS, it is required to add an NSContactsUsageDescription
entry to your Project-Info.plist
:
<key>NSContactsUsageDescription</key> <string>App would like to read contacts from the Addressbook.</string>
On Android, it is required to add the READ_CONTACTS
permission to your AndroidManifest.xml
:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
Note: If your targetSdkVersion
in AndroidManifest.xml
is 23 or higher, it asks the user for the permission on first use. At this point, this property contains an empty list of contacts.
Once the user accepted the permission, it contains the actual contacts. You can use property bindings to automatically update your QML logic.
The property contains a JSON array with objects containing the following keys:
name
: The contact's full name as a string. Includes first and last name.company
: The contact's company name as a string.phoneNumbers
: A JSON array with each of the contact's phone numbers as a string.phoneNumbersDetails
: A JSON array with details about each of the contact's phone numbers as a JSON object. Each entry in the list contains the keys label
and value
.emailAddresses
: A JSON array with each of the contact's email addresses as a string.addresses
: A JSON array with each of the contact's addresses as a JSON object. Each entry in the list contains keys for the address details, like Country
, City
,
Street
, and ZIP
.Example for the data contained in contacts
:
[ { name: "Kate Bell", company: "Microsoft", phoneNumbers: [ "(555) 564-8582", "(555) 524-7213" ] phoneNumbersDetails: [ { "label": "Work", "value": "(555) 564-8582" }, { "label": "Home", "value": "(555) 524-7213" } ] addresses: [ { "Country": "USA", "City": "Redmond", "State": "WA", "Street": "One Microsoft Way", "ZIP": "12345-1234" } ], emailAddresses: [ "k.bell@microsoft.at", "k.bell@gmail.com" ] }, { name: "Daniel Higgins", phoneNumbers: ["555-478-7672"] }, ... ]
Use this example code to show all contacts with name and all attached phone numbers:
import Felgo 3.0 App { Page { AppListView { anchors.fill: parent model: nativeUtils.contacts delegate: SimpleRow { text: modelData.name detailText: modelData.phoneNumbers.join(", ") // Join all numbers into a string separated by a comma } } } }
You can also use the property contacts to retrieve just the first phone number stored per contact.
Note: The phone numbers are returned in the format as they are stored in the address book by the user. To normalize phone numbers, you can use the country code of the device's own phone number and replace the starting 0 with the device's country code.
See also contacts, phoneNumber, getPhoneCountryIso(), and storeContacts().
displaySleepEnabled : bool |
Set this property to true
to allow devices to go into a "sleep" state where the screen dims after a specific period of time without any user input. The default value is false
meaning that the
display won't be dimmed, which is desirable for most games.
galleryPhotos : var |
Contains a list of photos that are retrieved from the gallery or camera roll on iOS and Android. To populate (or reload) the list, call NativeUtils::fetchGalleryPhotos() initially.
The returned list consists of objects with an ID and a path to the photo:
// Get the first gallery photo var photo = nativeUtils.galleryPhotos[0] var photoId = photo.id var photoPath = photo.assetPath
The path is a reference to the image and can be used as source property of an AppImage item. To get an absolute file path reference for further actions outside of your code, you can use NativeUtils::getCachedAssetPath():
// Get the first gallery photo var photo = nativeUtils.galleryPhotos[0] // Get the path to the first gallery photo nativeUtils.getCachedAssetPath(photo.id, function(success, filePath) { // Do something with the filePath, e.g. upload to \vpgn })
On iOS, it is required to add an NSPhotoLibraryUsageDescription
entry to your Project-Info.plist
:
<key>NSPhotoLibraryUsageDescription</key> <string>App would like to access the library.</string>
On Android, it is required to add the READ_EXTERNAL_STORAGE
permission to your AndroidManifest.xml
:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Note: If your targetSdkVersion
in AndroidManifest.xml
is 23 or higher, it asks the user for the permission on first use. At this point, this property contains an empty list of photos. Once
the user accepted the permission, it contains the file paths of the photos.
Note: This function is not implemented on desktop systems and WebAssembly.
The ImagePicker component uses the galleryPhotos to show a default view that allows picking multiple images. You can also create your own gallery and use the property as a model for your views:
import VPlayApps 1.0 import QtQuick 2.0 App { Page { // Fetch photos from gallery Component.onCompleted: nativeUtils.fetchGalleryPhotos() AppListView { anchors.fill: parent // Show fetched photos in list model: nativeUtils.galleryPhotos delegate: AppImage { width: parent.width height: width fillMode: Image.PreserveAspectCrop source: modelData.assetPath } } } }
See also fetchGalleryPhotos.
phoneNumber : string |
Contains the mobile device's phone number, if available. It might not be available if the user is not registered to a network or if the network does not provide this information. The property value is a string containing
the number, for example "+11234567"
, or an empty string ""
, if not available.
If your app or game has a functionality that needs the user's phone number and this method can not provide it, you can ask your user to enter his or her phone number using a displayTextInput().
This property is only supported on Android, as it is not possible to access the device phone number on iOS. On Android, it is required to add the READ_PHONE_STATE
or READ_SMS
permission to your
AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Note: If your targetSdkVersion
in AndroidManifest.xml
is 23 or higher, it asks the user for the permission on first use. At this point, this property contains an empty string. Once the user
accepted the permission, it contains the actual phone number. You can use property bindings to automatically update your QML logic.
See also getPhoneCountryIso(), contacts, and storeContacts().
preferredScreenOrientation : int |
Defines the preferred orientation of the screen.
The orientation of the screen on mobile devices can be either portrait or landscape. It can be set to a fixed value or controlled by the device's orientation sensor.
You can define your app's preferred orientation in AndroidManifest.xml
on Android and Project-Info.plist
on iOS. Setting this property allows to override the setting at any time during
runtime.
Following NativeUtils.ScreenOrientation
enumeration values are available:
NativeUtils.ScreenOrientationDefault
: Do not override the orientation and use the one set in AndroidManifest.xml
and Project-Info.plist
.NativeUtils.ScreenOrientationUnspecified
: Specifies that any orientation is allowed, depending on device configuration and sensor orientation.NativeUtils.ScreenOrientationSensor
: Specifies that the orientation should be determined based on device sensors.NativeUtils.ScreenOrientationPortrait
: Specifies that portrait orientation should be used. Based on device configuration and sensors, either regular or upside-down portrait may be used.NativeUtils.ScreenOrientationLandscape
: Specifies that landscape orientation should be used. Based on device configuration and sensors, either left or right landscape may be used.This is useful if different screens within your app or game should use different screen orientation. E.g. to set a preferred orientation during runtime and reset it to the default value, you can use the following code snippet:
Column { AppButton { text: "Lock to portrait" onClicked: nativeUtils.preferredScreenOrientation = NativeUtils.ScreenOrientationPortrait } AppButton { text: "Lock to landscape" onClicked: nativeUtils.preferredScreenOrientation = NativeUtils.ScreenOrientationLandscape } AppButton { text: "Use sensor orientation" // Rotating the device will now switch the screen orientation onClicked: nativeUtils.preferredScreenOrientation = NativeUtils.ScreenOrientationSensor } AppButton { text: "Reset to default orientation" // Resets to the orientation defined in AndroidManifest.xml or Project-Info.plist onClicked: nativeUtils.preferredScreenOrientation = NativeUtils.ScreenOrientationDefault } }
Sometimes it is also useful to use fixed orientation depending on some property of your game state. In this case, nativeUtils.preferredScreenOrientation
can be bound using property bindings with the Binding item:
Binding { target: nativeUtils property: "preferredScreenOrientation" // Use portrait mode as long as usePortraitMode is true, which is defined somewhere else within your app/game value: usePortraitMode ? NativeUtils.ScreenOrientationPortrait : NativeUtils.ScreenOrientationDefault }
To switch back to the original screen orientation, set preferredScreenOrientation
to NativeUtils.ScreenOrientationDefault
.
If you use Felgo Apps components, you can also define a preferred screen orientation for pages inside a NavigationStack: Just assign Page::preferredScreenOrientation for each page you want to push with NavigationStack::push().
Note: This property only has an effect on mobile platforms.
You can use NativeUtils::screenOrientation to find out the current orientation of the screen.
The default value for this property is NativeUtils.ScreenOrientationDefault
.
This property was introduced in Felgo 2.16.0.
See also NativeUtils::screenOrientation and Page::preferredScreenOrientation.
safeAreaInsets : var |
On modern devices like the iPhone X, some parts of the screen are covered by native device overlays and buttons. When creating user interfaces for such devices, it may be necessary to adapt the app layout based on the inset to the border of the screen.
This property holds the pixel inset at the left, top, right and bottom of the screen, which you can access with:
The returned pixel value directly reflects the inset for the safe area of the screen. It is not required to apply App::dp() when used.
This property was introduced in Felgo 2.16.0.
[read-only] screenOrientation : int |
Read-only property returning the current orientation of the screen, which is either NativeUtils.ScreenOrientationPortrait
or NativeUtils.ScreenOrientationLandscape
. The value of this property
depends on preferredScreenOrientation.
This corresponds to the Screen::primaryOrientation property but uses the enum values ScreenOrientation
defined in NativeUtils.
This property was introduced in Felgo 2.16.0.
See also NativeUtils::preferredScreenOrientation.
softInputMode : int |
Defines the app or game's behavior when a soft keyboard is open.
Certain Felgo components open a soft keyboard on mobile devices when in focus. Such components include AppTextInput, AppTextField and AppTextEdit.
When the soft keyboard opens, the app or game adjusts its content accordingly. Felgo supports multiple modes of behavior for this.
Following NativeUtils.SoftInputMode
enumeration values are available:
NativeUtils.SoftInputModeUnspecified
: Specifies no soft input mode and lets the underlying mobile platform decide.NativeUtils.SoftInputModeAdjustResize
: The content view resizes to the remaining screen area.NativeUtils.SoftInputModeAdjustPan
: The content view moves upwards with the height of the soft keyboard.NativeUtils.SoftInputModeAdjustNothing
: The content view does not adjust with the soft keyboard. This means that the soft keyboard might hide the view that opened it.Note: This property is only supported on Android. On other platforms, the soft keyboard's behavior cannot be changed.
Note: On Android, only non-fullscreen apps can use the NativeUtils.SoftInputModeAdjustResize
mode. So to use this mode, set your app to be in windowed mode. The best way to do this is to use setStatusBarStyle() with NativeUtils.StatusBarStyleSystem
. If you use the App components, you can also switch it with ThemeColors::statusBarStyle. The below shows an example usage:
import Felgo 3.0 App { onInitTheme: { // use system status bar style making the app non-fullscreen Theme.colors.statusBarStyle = Theme.colors.statusBarStyleSystem // switch to adjust resize mode nativeUtils.softInputMode = NativeUtils.SoftInputModeAdjustResize } }
Note: On Android, text fields inside a WebView only support the NativeUtils.SoftInputModeAdjustResize
mode. Thus if you use a WebView in your app or game, you can set this mode. You can set it at app start, or temporarily while the WebView is showing.
Note: On Android, this property can also be defined in AndroidManifest.xml
. It corresponds to the android:windowSoftInputMode attribute on the <activity>
tag. Changing this property at runtime overrides the setting defined
in the manifest.
The default value of this property is the NativeUtils.SoftInputModeUnspecified
. On Android, this means the value set in AndroidManifest.xml
is still active.
This property was introduced in Felgo 3.3.0.
This signal gets emitted after the alert dialog initiated with displayAlertDialog() gets dismissed by the user. If accepted is true, the user confirmed the dialog by pressing the OK button. If accepted is false, the user either pressed the Cancel button, or on Android either pressed the back button or touched outside of the dialog.
This signal gets emitted after the alert sheet initiated with displayAlertSheet() is finished by the user. The parameter index holds the selected option
or -1
if canceled.
cameraPickerFinished(accepted, string path) |
This signal gets emitted after the dialog initiated with displayCameraPicker() is finished by the user. If accepted is true, the user selected an image. The parameter path holds the path to the selected image or an empty string if canceled.
datePickerFinished(accepted, date date) |
This signal gets emitted after the dialog initiated with displayDatePicker() is finished by the user. If accepted is true, the user pressed the OK button after selecting a date. The parameter date holds the year, month and day of month of the selected date.
imagePickerFinished(accepted, string path) |
This signal gets emitted after the dialog initiated with displayImagePicker() is finished by the user. If accepted is true, the user selected an image. The parameter path holds the path to the selected image or an empty string if canceled.
This signal gets emitted after the MessageBox dialog initiated with displayMessageBox() gets dismissed by the user. If accepted is true, the user confirmed the MessageBox by pressing the OK button. If accepted is false, the user either pressed the Cancel button, or on Android either pressed the back button or touched outside of the dialog.
Gets emitted on iOS as soon as the height of the statusbar changes, e.g. when a call is accepted or finished.
textInputFinished(accepted, string enteredText) |
This signal gets emitted after the input dialog initiated with displayTextInput() is finished by the user. If accepted is true, the user confirmed the text input by pressing the OK button. The text input is then stored in enteredText. If accepted is false, the user either pressed the Cancel button, or on Android either pressed the back button or touched outside of the dialog.
bool clearKeychainValue(identifier) |
Delete a value based on a given identifier from the native Keychain on the device.
Here is an example how to delete a Keychain item:
nativeUtils.clearKeychainValue("identifier")
Note: The keychain is only implemented on iOS and Android, on all other platforms the function uses unencrypted QSettings as fallback.
See also getKeychainValue() and setKeychainValue().
string deviceManufacturer() |
Returns a string representing the manufacturer name of iOS and Android devices, e.g. Samsung
, LG
or Apple
. Returns unknown
on all other platforms.
See also deviceModel().
string deviceModel() |
Returns the model identifier string of iOS and Android devices. Returns unknown
on other platforms.
Note: The identifier does not necessarily match the device name. For example, the model iPhone8,2
represents the iPhone 6s Plus, whereas SM-G925F
is the identifier for the Galaxy S6 Edge.
You can have a look at websites like https://www.theiphonewiki.com/wiki/Models or http://samsung-updates.com to see which model
identifier belongs to which device.
See also deviceManufacturer().
Displays a native alert dialog with a given title, an optional description that can provide more details, an OK button and an optional Cancel button.
By default, the additional dialog description is an empty string and okButtonTitle is set to "OK", so only an OK button is displayed.
In comparison to displayMessageBox(), displayAlertDialog() allows to localize the button titles. E.g. to show a dialog with localized buttons, call
nativeUtils.displayAlertDialog(qsTr("Title"), qsTr("Description"), qsTr("OK"), qsTr("Cancel"))
and provide your localizations in a language resource file or provide the strings for your specific language hardcoded.
To receive the result of the user input, use the Connections element and the alertDialogFinished signal handler like demonstrated in MessageBox and Opening URL with System Browser.
Note: To show a more advanced native-looking dialog, use the MessageDialog.
See also alertDialogFinished().
void displayAlertSheet(title, stringlist items, bool cancelable) |
Displays a modal alert sheet with the specific options. It uses an AlertDialog on Android and a UIActionSheet on iOS.
The native dialog shows the title and offers the specified items as options. The parameter cancelable decides whether the user can cancel the dialog or is forced to choose an option.
See also alertSheetFinished().
Allows to take a photo by starting the native camera, if available.
It copies the new photo to the app's private storage folder. It uses the FileUtils.AppDataLocation
. For more info see Storage Location. You can access the
file path in cameraPickerFinished().
Note: On iOS, the FileUtils.AppDataLocation
changes when the app gets updated. To persist the images returned from this method, it is recommended to store only the file name using FileUtils::cropPathAndKeepFilename(). To get the actual file name back, use FileUtils::storageLocation()
with FileUtils.AppDataLocation
.
Note: To store files to FileUtils.AppDataLocation
on Android, add the following line to android/res/xml/file_paths.xml
:
<files-path name="files" path="."/>
If you are developing for iOS, please make sure to include descriptions for the camera usage and for storing photos to your ios/Project-Info.plist
configuration, for example:
<key>NSCameraUsageDescription</key> <string>Take photos for the user profile.</string> <key>NSPhotoLibraryAddUsageDescription</key> <string>App would like to save photos in your library.</string>
If you are developing for Android, no special permissions are needed for this function on current Android versions. If you plan to support Android 4.3 (API level 18) and lower however, you need to declare the permission
for external storage in AndroidManifest.xml
:
<manifest ...> ... <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" /> </manifest>
Note: When displaying images taken with the device camera, they might be shown incorrectly rotated. Activate AppImage::autoTransform to also consider the orientation of the shot and show the image correctly.
See also cameraPickerFinished().
Allows to choose a date from a calendar by displaying a native date picker dialog, if available.
The parameters allow detailed control over the selectable dates. The first parameter, initialDate
, specifies the date selected when the date picker is opened. The second parameter, minDate
, and
the third parameter, maxDate
, specify the range of selectable dates. It is also possible to omit all three parameters, or to only specify the initialDate
.
Example calls:
// Display date picker with current date and no min/max date nativeUtils.displayDatePicker() // Display date picker on February 9th 2018 with no min/max date nativeUtils.displayDatePicker("2018-02-09") // Display date picker on February 9th 2018 with and only dates in January and February 2018 selectable nativeUtils.displayDatePicker("2018-02-09", "2018-01-01", "2018-02-28")
See also datePickerFinished().
Allows to choose a photo from the device by displaying the native image picker, if available.
It copies the chosen photo to the app's private storage folder. It uses the FileUtils.AppDataLocation
. For more info see Storage Location. You can access
the file path in imagePickerFinished().
Note: On iOS, the FileUtils.AppDataLocation
changes when the app gets updated. To persist the images returned from this method, it is recommended to store only the file name using FileUtils::cropPathAndKeepFilename(). To get the actual file name back, use FileUtils::storageLocation()
with FileUtils.AppDataLocation
.
Note: To store files to FileUtils.AppDataLocation
on Android, add the following line to android/res/xml/file_paths.xml
:
<files-path name="files" path="."/>
Note: If you want to select multiple images, or display the image picker inline in you app, you can use the ImagePicker QML component.
If you are developing for iOS, please make sure to include an entry about the photo library usage description to your ios/Project-Info.plist
configuration, for example:
<key>NSPhotoLibraryUsageDescription</key> <string>Select pictures for the user profile.</string>
Note: When displaying images taken with the device camera, they might be shown incorrectly rotated. Activate AppImage::autoTransform to also consider the orientation of the shot and show the image correctly.
See also imagePickerFinished().
Displays a native-looking message box dialog with a given title, an optional description that can provide more details, an OK button and an optional Cancel button. By default, the additional dialog
description is an empty string and buttons is set to 1, so only an OK button is displayed. To also add a Cancel button, call the following: nativeUtils.displayMessageBox("Really Quit?", "", 2)
.
To receive the result of the user input, use the Connections element and the messageBoxFinished signal handler like demonstrated in MessageBox and Opening URL with System Browser.
Note: For showing dialogs with localized button titles, use displayAlertDialog().
Note: To show a more advanced native-looking dialog, use the MessageDialog.
See also messageBoxFinished().
Displays a native-looking message input dialog with a given title, a description that can provide more details, a placeholder that is displayed as long as the input field is empty (optional) and a prefilled text. The dialog also provides an OK and a Cancel button, which can optionally be localized with okButtonTitle and cancelButtonTitle.
The signal textInputFinished gets emitted after the user dismisses the dialog. Use the Connections element to receive the result of textInputFinished like explained in User Input With Native Dialog.
Note: For custom text input dialogs, use the TextInput component from the QtQuick module.
See also textInputFinished().
Fetches photos from the device gallery or camera roll and makes them available with NativeUtils::galleryPhotos. This is also used internally to populate the ImagePicker, a component to select multiple Images from the device gallery.
See also galleryPhotos.
void getCachedAssetPath(id, var jsCallback) |
Requests an absolute file path (cached file) to the asset with the given id and returns it within the callback:
// Get the first gallery photo var photo = nativeUtils.galleryPhotos[0] // Get the path to the first gallery photo nativeUtils.getCachedAssetPath(photo.id, function(success, filePath) { // Do something with the filePath, e.g. upload to \vpgn or save to storage with FileUtils })
Using this method is necessary if you want to use an image retrieved from NativeUtils::galleryPhotos because the given path might be a virtual reference to an image from the device's gallery and not an absolute file path already (e.g. if displaying images from iCloud on iOS).
This function is also used internally to populate the ImagePicker, a component to select multiple Images from the device gallery.
Note: This function is not implemented on desktop systems and WebAssembly.
See also galleryPhotos.
string getKeychainValue(identifier) |
Read a value based on a given identifier from the native Keychain on the device.
Here is an example how to read a Keychain value:
nativeUtils.getKeychainValue("identifier", "value")
Note: The keychain is only implemented on iOS and Android, on all other platforms the function uses unencrypted QSettings as fallback.
See also setKeychainValue() and clearKeychainValue().
string getPhoneCountryIso() |
Returns the country code string according to ISO 3166-1 of your mobile device's SIM card, if available. It might not be available if, for example, there is no SIM card inserted into the device. The return value is a string
representing this country, for example "us"
, or an empty string ""
, if not available.
This method is only supported on Android, as it is not possible to access the device phone status on iOS. On Android, it is required to add the READ_PHONE_STATE
or READ_SMS
permission to your
AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
See also phoneNumber, contacts, and storeContacts().
bool openApp(launchParam) |
Tries to launch an app identified by launchParam
on the device. The required parameter value depends on the platform. For Android, the app's package identifier should be passed. On iOS, apps can only be
launched by passing url-schemes.
The method returns true
if the app could be launched, false
otherwise.
The following code snippet launches the Facebook app on iOS or Android if possible:
var launchParam = system.isPlatform(System.IOS) ? "fb://profile" : "com.facebook.katana" if(!nativeUtils.openApp(launchParam)) { // app could not be opened, add code for handling this case here }
bool openUrl(urlString) |
Opens the urlString with the default application associated with the given URL protocol of the current platform. This means your game is suspended and an external application gets opened. Here is an example for opening an URL in the platform's default browser:
nativeUtils.openUrl("https://felgo.com")
Examples of URL protocols and how this method handles them:
http(s)://
- Opens the URL in a default web browser.mailto:
- Opens the default email composer.
Note: To send emails, the method sendEmail() is preferred because of proper URL escaping.
file://
- If the URL points to a directory, opens the directory in the default file browser. If the URL points to a file, opens the file with the default app associated with the file type, if one exists.
Note: Depending on the platform, no file browser to open directories or app to open a specific file type may be installed. In this case, the call does nothing and returns false. Specifically, mobile platforms don't generally have file browsers for opening directories installed.
Note: To be able to open file://
URLs with another app on Android, if your targetSdkVersion
in AndroidManifest.xml
is 24 or higher, you need to enable the paths you wish to
use in android/res/xml/file_paths.xml
.
Note: To open files, the method FileUtils::openFile() is preferred. It can also handle file paths without file://
prefix.
assets:/
and qrc:/
- Qt resources and app assets are not supported as they cannot be opened outside your app.Each platform might support additional URL protocols. On iOS, for example, apps can be opened with custom URL protocols. For opening other apps, openApp() is preferred though.
This method returns true
if the URL was handled by the operating system. It returns false
if the platform cannot handle the URL's protocol or the URL itself. In this case, check the log output for
the actual error.
Opens the native email app prefilled with the given to receiver, subject and message. If users do not have a default email application, they can choose between their installed native applications that support sending emails.
Store a value (like a password) based on a given identifier securely and persistent in the native Keychain on the device.
Here is an example how to use the Keychain storage functionality:
nativeUtils.setKeychainValue("identifier", "value")
Note: The keychain is only implemented on iOS and Android, on all other platforms the function uses unencrypted QSettings as fallback.
See also getKeychainValue() and clearKeychainValue().
Allows to set the status bar style for apps or games.
By default the status bar is visible for apps, and hidden for games. To change the status bar style, you can set one of the following values:
Note: This property determines if the app uses full-screen mode on Android. Only the setting NativeUtils.StatusBarStyleSystem disables the full-screen mode.
Note: The white and black style only apply for iOS devices. On Android devices, the status bar is either hidden or translucent.
void share(text, string url) |
Opens the native share dialog with a given text and url. This method is currently implemented on Android and iOS.
nativeUtils.share("Check out Felgo!","https://felgo.com")
The parameter text can be any text. That text is shared with another app.
The parameter url can either be a http(s)://
web link or a file://
URL.
If it is a web link, it shares it directly with another app.
If it is a file URL, it shares that file's contents. This lets you share images and other files with other apps. For example, you can use the various FileUtils methods to obtain such file URLs.
To share files on Android if your targetSdkVersion
in AndroidManifest.xml
is 24 or higher, you need a file provider tag in AndroidManifest.xml
.
The tag is added in projects created after Felgo 2.16.
If you created your project with an earlier version of Felgo, add this entry in AndroidManifest.xml
, inside the <application>
tag:
<!-- file provider needed for letting external apps (like contacts) read from a file of the app --> <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"/> </provider>
Also, create a file android/res/xml/file_paths.xml
with the following content:
<paths> <!-- Example: to share images from the Pictures/ folder --> <external-files-path name="images" path="Pictures"/> <!-- Example: app internal files, like files saved to FileUtils.AppDataLocation --> <files-path name="files" path="."/> </paths>
On iOS, the sharing an image file allows the user to save it to the iOS Photo Gallery.
Your app required the NSPhotoLibraryAddUsageDescription
in your ios/Project-Info.plist
to use that feature, otherwise the app may crash:
<key>NSPhotoLibraryAddUsageDescription</key> <string>App would like to save photos.</string>
int statusBarHeight() |
Returns the height of the native status bar of the device.
bool storeContacts(vCard) |
Stores one or more contacts to the device address book. The vCard
parameter passes the data for the contacts in VCF format (version 2.1).
On iOS, it is required to add an NSContactsUsageDescription
entry to your Project-Info.plist
:
<key>NSContactsUsageDescription</key> <string>App would like to store contacts to the Addressbook.</string>
The permission for AddressBook access is then asked the first time this method is called for the app. If permission is given, it stores the contacts and returns true
.
On Android, the method first stores the VCF data as contacts.vcf
in the app's cache directory of the internal storage and then opens the file for importing the contacts.
Note: If your targetSdkVersion
in AndroidManifest.xml
is 24 or higher, you need a file provider tag in AndroidManifest.xml
. The tag is added in projects created after Felgo
2.16. If you created your project with an earlier version of Felgo, add this entry in AndroidManifest.xml
, inside the <application>
tag:
<!-- file provider needed for letting external apps (like contacts) read from a file of the app --> <provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"/> </provider>
Also, create a file android/res/xml/file_paths.xml
with the following content:
<paths> <!-- the path for nativeUtils.displayCameraPicker() --> <external-files-path name="images" path="Pictures"/> <!-- app internal cache for nativeUtils.storeContacts() --> <cache-path name="cache" path="."/> </paths>
The call returns false
if the user did not allow AddressBook access on iOS or if the VCF file could not be stored on Android, true
otherwise.
Note: It is currently not possible to determine if the passed vCard
data is valid or not. On Android, the VCF data file is successfully stored but the device can then not open the file to import the
contacts. On iOS, invalid contacts are simply not added to the AddressBook without any hint or exception. Please make sure to pass valid data and do tests on your devices to avoid problems.
The following example shows how to add a contact to the device and handles errors appropriately:
import Felgo 3.0 App { screenWidth: 960 screenHeight: 640 AppButton { text: "Store Contact" anchors.centerIn: parent onClicked: { var vCard = "BEGIN:VCARD VERSION:2.1 N:Felgo;Engine;;; FN:Felgo TEL;WORK:0123456789 EMAIL;WORK:help@felgo.com ADR;WORK:;;Kolonitzgasse;Wien;;1030;Austria ORG:Felgo URL:http://www.felgo.com END:VCARD"; var success = nativeUtils.storeContacts(vCard) if(system.isPlatform(System.IOS)) { // handle success/error on iOS to give feedback to user if(success) NativeDialog.confirm("Contacts stored.", "", function() {}, false) else NativeDialog.confirm("Could not store contacts", "The app does not have permission to access the AddressBook, please allow access in the device settings.", function() {}, false) } else if (system.isPlatform(System.Android)) { // only react to error on Android, if successful the device will open the vcard data file if(!success) { NativeDialog.confirm("Could not store contacts", "Error when trying to store the vCard to the app's cache folder.", function() {}, false) } } else { // platform not supported NativeDialog.confirm("Could not store contacts", "Storing contacts is only possible on iOS and Android.", function() {}, false) } } } }
To allow special characters for a vCard property, use CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE
for the property and encode the data. The encodeQuotedPrintable
function of the following example can
be used to convert a string to quoted-printable representation:
function storeContact(name) { var name = encodeQuotedPrintable(name) var vCard = "BEGIN:VCARD VERSION:2.1 N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:"+name+";;;; FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:"+name+" END:VCARD" nativeUtils.storeContacts(vCard) } function encodeQuotedPrintable(text) { var charsPerLine = 69 // output lines in quoted printable hold 70 chars max var curLineLength = 0 var result = "" // convert string to utf-8 var utf8 = unescape(encodeURIComponent(text)); // convert all chars of line to quoted printable hex representation for(var i = 0; i < utf8.length; i++) { var hexChar = utf8.charCodeAt(i).toString(16).toUpperCase() // hex value of character if(hexChar.length == 1) hexChar = "0"+hexChar if((curLineLength + hexChar.length + 1) > charsPerLine) { curLineLength = 0 result += "=\n" // invisible line break } curLineLength += (hexChar.length + 1) result += ("=" + hexChar) } return result }
See also contacts.
Vibrates a short duration on supported devices. This method is currently implemented on Android and iOS.
Note: Please make sure to add the
<uses-permission android:name="android.permission.VIBRATE"/>
to your AndroidManifest.xml file when using the vibration functionality on Android.