NativeUtils

The nativeUtils context property allows opening native message boxes, input dialogs and browsers. More...

Import Statement: import

Properties

Signals

Methods

Detailed Description

This object is available as a context property from all QML components when V-Play is imported via import VPlay 2.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().

Example Usages

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 V-Play Website button is clicked, the V-Play website is opened in the default external browser application of the system.

MessageBox and Opening URL with System Browser

 import VPlay 2.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 V-Play Website"
       onClicked: nativeUtils.openUrl("http://v-play.net")
     }

   }

   // 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);
   }

 }

User Input With Native Dialog

This example shows how to query user input and to save it in a Text element.

 import VPlay 2.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.

Property Documentation

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.


Signal Documentation

alertDialogFinished(bool accepted)

This handler is called 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.


alertSheetFinished(int index)

This handler is called after the alert sheet initiated with displayAlertSheet() is finished by the user. The parameter index holds the selected option or -1 if canceled.


cameraPickerFinished(bool accepted, string path)

This handler is called 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.


imagePickerFinished(bool accepted, string path)

This handler is called 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.


messageBoxFinished(bool accepted)

This handler is called 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.


statusBarHeightChanged(real height)

Gets emitted on iOS as soon as the height of the statusbar changes, e.g. when a call is accepted or finished.


textInputFinished(bool accepted, string enteredText)

This handler is called 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.


Method Documentation

string deviceModel()

Returns the model identifier string of iOS and Android devices, 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 lo at websites like https://www.theiphonewiki.com/wiki/Models or http://samsung-updates.com to see which model identifier belongs to which device.


void displayAlertDialog(string title, string description, string okButtonTitle, string cancelButtonTitle)

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: For showing more advanced native-looking dialog, use the MessageDialog component from the QtQuickDialogs module.

See also alertDialogFinished.


void displayAlertSheet(string 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.


void displayCameraPicker(string title)

Allows to take a photo by starting the native camera, if available.

See also cameraPickerFinished.


void displayImagePicker(string title)

Allows to choose a photo from the device by displaying the native image picker, if available.

See also imagePickerFinished.


void displayMessageBox(string title, string description, int buttons)

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: For showing more advanced native-looking dialog, use the MessageDialog component from the QtQuickDialogs module.

See also messageBoxFinished.


void displayTextInput(string title, string description, string placeholder, string text, string okButtonTitle, string cancelButtonTitle)

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 handler textInputFinished is called 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.


bool openApp(string 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 function 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
 }

void openUrl(string 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("http://v-play.net")

Note: You can also use mailto: links, for sending emails the method sendEmail() is however preferred because of proper URL escaping. For advanced usage like opening a file browser, use Qt.openUrlExternally().


void sendEmail(string to, string subject, string message)

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.


void setStatusBarStyle(style)

Allows setting the status bar style for games & apps running on iOS devices.

By default the iOS status bar is hidden for new V-Play projects. If you want to explicitly display the status bar you can set style to one of the following values:

  • NativeUtils.StatusBarStyleHidden: The status bar is hidden (default)
  • NativeUtils.StatusBarStyleWhite: Display a white status bar for dark content
  • NativeUtils.StatusBarStyleBlack: Display a black status bar for light content

Note: This setting only applies for games & apps running on iOS devices.


void share(string 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 that nice Engine!","http://v-play.net")

void statusBarHeight()

Returns the height of the native status bar of the device.


bool storeContacts(string 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, the permission for AddressBook access is required and asked the first time this function is called for the app. If permission is given, it stores the contacts and returns true. On Android, the function first stores the VCF data as contacts.vcf in the documents directory of the external storage and then opens the file for importing the contacts.

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 VPlayApps 1.0
 import VPlay 2.0

 App {
   screenWidth: 960
   screenHeight: 640

   AppButton {
     text: "Store Contact"
     anchors.centerIn: parent
     onClicked: {
       var vCard = "BEGIN:VCARD
 VERSION:2.1
 N:V-Play;Engine;;;
 FN:V-Play Engine
 TEL;WORK:0123456789
 EMAIL;WORK:help@v-play.net
 ADR;WORK:;;Kolonitzgasse;Wien;;1030;Austria
 ORG:V-Play
 URL:http://www.v-play.net
 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 user documents 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
 }

void vibrate()

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.


Voted #1 for:

  • Easiest to learn
  • Most time saving
  • Best support

Develop Cross-Platform Apps and Games 50% Faster!

  • Voted the best supported, most time-saving and easiest to learn cross-platform development tool
  • Based on the Qt framework, with native performance and appearance on all platforms including iOS and Android
  • Offers a variety of plugins to monetize, analyze and engage users
FREE!
create apps
create games
cross platform
native performance
3rd party services
game network
multiplayer
level editor
easiest to learn
biggest time saving
best support