Obsolete Members for NativeUtils

The following members of QML type NativeUtils are obsolete. They are provided to keep old source code working. We strongly advise against using them in new code.

Methods

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: To show a more advanced native-looking dialog, use the MessageDialog.

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.

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().


void displayDatePicker(date initialDate, date minDate, date maxDate)

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().


void displayImagePicker(string title)

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().


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: To show a more advanced native-looking dialog, use the MessageDialog.

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 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().


void fetchGalleryPhotos()

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

See also galleryPhotos.


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(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 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(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("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.


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 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:

  • NativeUtils.StatusBarStyleHidden: Hides the status bar.
  • NativeUtils.StatusBarStyleWhite: Shows the status bar. This setting uses a white status bar for dark content on iOS.
  • NativeUtils.StatusBarStyleBlack: Shows the status bar. This setting uses a black status bar for light content on iOS.
  • NativeUtils.StatusBarStyleSystem: Shows the status bar. This setting uses a white status bar for dark content on iOS. It uses a default system themed status bar on Android.

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(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 Felgo!","https://felgo.com")

int 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, 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.


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