WKWebView. Return a value from native code to JavaScript

WKWebView exposes a comfortable way to call native code from JavaScript. So called Message handlers are defined in native code and can be later used in JavaScript like this:


But what about return values? For as you know, WKWebView runs in its own process and that’s why pushMessage() function cannot return any value. It is not possible to get the return value from native function synchronously. It is also not possible to give a JS callback function to native function. So what to do, if we need a return value from native function?

[adinserter block=”1″]

There are several approaches how to realize and organize asynchronous communication of native code <-> JavaScript with WKWebView. The first thought is to implement another JS function that would be called from native code after operation on native side is finished, i.e.

JavaScript code:

function readStringFromFile(relativeFilePath) {
webkit.messageHandlers.readFileHandlder.pushMessage({filePath: relativeFilePath});

// this function will be later called by native code
function readStringFromFileReturn(returnedValue) {
// do you stuff with returned value here

And the corresponding handler implementation in Objective-C would look like this:

- (void)userContentController:(WKUserContentController*)userContentController
didReceiveScriptMessage:(WKScriptMessage*)message {

if([message.name isEqualToString:@"readFileHandler"]) {
NSDictionary *paramDict = message.body;
NSString *filePath = [paramDict objectForKey:@"filePath"];
NSString *resultString = [self readStringFromFileSynchronously: filePath];
NSString *javaScript = [NSString stringWithFormat:@"readStringFromFileReturn('%@');", resultString];
[self.webView evaluateJavaScript:javaScript completionHandler:nil];

The described approach is not very elegant. If you have several functions in your interface between JavaScript and native code, the chained calls get very quickly confusing.

Much better approach is utilizing relative new concept of promises in JavaScript. I think, it’s also the way, Apple bore in mind when WKWebView has been introduced. More about promises can be read here or here. First, we need to extend our JavaScript:

// object for storing references to our promise-objects
var promises = {}

// generates a unique id, not obligator a UUID
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&amp;amp;amp;amp;amp;amp;0x3|0x8)).toString(16);
return uuid;

// this funciton is called by native methods
// @param promiseId - id of the promise stored in global variable promises
function resolvePromise(promiseId, data, error) {
if (error){

} else{
// remove referenfe to stored promise
delete promises[promiseId];

Our readStringFromFile function looks now like this:

function readStringFromFile(relativeFilePath) {
var promise = new Promise(function(resolve, reject) {
// we generate a unique id to reference the promise later
// from native function
var promiseId = generateUUID();
// save reference to promise in the global variable
this.promises[promiseId] = { resolve, reject};

try {
// call native function
window.webkit.messageHandlers.readFileHandler.postMessage({promiseId: promiseId, fileName: fileName});
catch(exception) {


return promise;


The JavaScript code is self explaining. One important thing to mention is that the reference to the created promise-object is stored globally.

And now the Objective-C code:

- (void)userContentController:(WKUserContentController*)userContentController
didReceiveScriptMessage:(WKScriptMessage*)message {

if([message.name isEqualToString:@"readFileHandler"]) {
NSDictionary *paramDict = message.body;
NSString *promiseId = [paramDict objectForKey:@"promiseId"];
NSString *filePath = [paramDict objectForKey:@"filePath"];
NSString * resultString = [self readStringFromFileSynchronously: filePath];
NSString *javaScript = [NSString stringWithFormat:@"resolvePromise('%@',%@, null);",promiseId, resultString];
[self.webView evaluateJavaScript:javaScript completionHandler:nil];

As you can see the native function calls resolvePromise with return value. The code at JavaScript continues running, after the promise is resolved. What we are still missing, is the usage example for function readStringFromFile, which returns a promise object:

readStringFromFile("someRelativePath").then(function(returnedString) {
var returnValue = returnedString;
// do your stuff here

}, function(returnedString) {

Utilization of promises as described above makes code more readable.It allows a clean definition of the interface between JavaScript and native code.

There are also other projects, aiming to enable easy communication between JavaScript in WKWebView and native code, e.g. XWebView. However, when integrating such components in your project be aware of:

  • you become dependent on third party development. Each newer version of SWIFT would make you to wait for compatible updates
  • they use the same messaging mechanism under the hood

About communication between JavaScript and native code in WKWebView

WKWebView is a replacement of UIWebView that is available since iOS 2.0. Apple encourages using WKWebView instead of UIWebView in its documentation:


In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView.

One of the key advantages of the new component is the more comfortable way to call native functions directly from JavaScript and to execute JavaScript functions at the native side. However, there are some limitations, which one should know:

  • WKWebView runs in its own process. On one hand it is a great performance improvement. On the on the hand it implies some unpleasant limitations in exchanging data between native app and the WKWebView
  • Native <=> JavaScript communication can only be asynchronous.
  • Native functions called from JavaScript cannot return values immediately.
  • The only way to return a value is to call another JavaScript function from native function with return value as parameter.
  • JavaScript functions can be called within native native methods only in global context.

To my opinion, limitations mentioned above are a step back comparing with UIWebView. With UIWebView it is possible to obtain JavaScript context and inject native(!) objects into that context by means of JSExport interface. There is then no difference wether you call a function on an injected object or some other JS function. Native functions can return values synchronously! The only disadvantage of this approach is that Apple has not exposed JavaScript context of the UIWebView officially. It is only possible to obtain the context  via private properties. That’s why this approach should not be used in product apps.

Start using Swift code in your Objective-C project

If you decided to start using Swift in your existing Xcode project, it can become a pain if your project is large and contains multiple targets. Follow steps below to be able to use Swift classes in your Objective-C code:

  1. Create a new *.swift file in your Objective-C project, or drag a .swift file with Finder
  2. Xcode prompts you to create an Objective-C bridging header file. Confirm it or add the bridging header manually
  3. Use @objc attribute for your Swift class:
    import Foundation
    @objc class YourController: UIViewController {    
  4. In Build Settings of your project check parameters below:
    Defines Module : YES
    Install Objective-C Compatibility Header : YES => Once you’ve added *.swift file to the project this property will appear in Build Settings
    Objective-C Generated Interface Header : $(PROJECT_NAME)-Swift.h
  5. Import Swift interface header in your *.m file like this:
    #import "YourProject-Swift.h" // $(PROJECT_NAME)-Swift.h

iOS: Today Extensions / Widgets

A Today extension, also known as a widget, is a way for the app to provide quick access to its main functions and the up-to-date information in the Notification Center. The content for the widgets might be directly fetched from the web, but quite often there is a requirement to share data between the App and its widget.

How to add Today extension / Widget to an existing project?

Just add a new target of type “Today extension” to your project . To debug/start Today extension just select the proper target and run.

Can the same code, e.g. views and controllers, be shared/utilized between Widget and App targets?

Yes. Be sure to select checkboxes for the corresponding files in the “Target Membership” window of the Xcode. There are, however, some limitations, especially using swipe gestures. The swipe gesture triggers swiping between the Today and Notifications sections within Notification Center, so it doesn’t really provide the best or most reliable user experience.

What about CoreData in Widgets?

No problem, almost.. In general, by default, an App and its extension cannot access the same data, since their security domains are different. In order to solve this problem there should be created an App Group. An App Group provides a shared bundle that can be used by the app and its extensions as a shared container in which data can be stored. The App group can be configured in the apple developer portal (s. nice tutorial) or directly in Xcode under target capabilities.

Read More

VMWare Fusion: /dev/vmmon konnte nicht geöffnet werden

On my MacBook Pro I have VMWare Fusion with Windows 10 installed. It worked quite well until I started getting following error message:


/dev/vmmon konnte nicht geöffnet werden: Es existiert keine Datei und kein Ordner dieser Art. Stellen Sie sicher dass das Kernelmodul “vmmon” geladen ist.

It is the same as the the english variant

Could not open /dev/vmmon: No such file or directory.

First, I thought it could be an error after upgrading the MAC OS from Yosemite to Mavericks. However, it turned out to be a conflict with Oracle’s VirtualBox, known as Oracle VM VirtualBox. VirtualBox is a free software for running virtual machines, i.e. same purpose as VMWare. I didn’t realize, that it was installed on my MAC. It might came with some other Apps, that were previously installed. Like Android emulator “Andy” or some other.

So how to fix the issue? Just uninstall VirtualBox. Follow the steps below:

The system restart is not required, your VMWare Fusion should work from now on properly. If you need VirtualBox in the future for other apps, you can install it again from Oracle’s website.

Apple Watch at the second glance

I could make my first impression of the Apple Watch 2 years ago. The very first version of the watchOS could not really persuade with features that one would say “I absolutely need the watch!”. Actually, I agree with multiple reviews and the main statement about Apple Watch: no clear concept for whom it can bee useful and how it can revolutionize my everyday life. Thus, I put the Apple Watch in the cupboard. For fitness data tracking and sleep data tracking I preferred my new Garmin Vivosmart HR. To my opinion it had a number of advantages over Apple Watch:

  • Battery Life! The most important argument. Vivosmart HR needs to be charged only once a week, where Apple Watch should be charged really every day
  • Sleep data tracking
  • Stairs/floor counter
  • Waterproof

Last week I wanted to know more about the features of watchOS 3. For this purpose Apple Watch and Vivosmart HR changed their places in the cupboard. After a week of wearing the Apple Watch I did like the recent changes. Of course, battery life didn’t really change. watchOS 3 did not bring waterproof property to the very first model of the Apple Watch as well 🙂 BUT:

  • Now, apps can run directly on the  Apple Watch
  • More interesting apps for the Apple Watch
  • Pleasant improvements in fitness aspects: better user interface, more features
  • HomeKit makes it possible to integrate it in your smart home environment
  • and much more..

The Apple Watch became more attractive for sportsmen and the intent of Apple is to make more in that direction. If one accepts the fact, that even Generation 2  of the Apple Watch still needs to be charged every 2 days, then one can say, it is one of the best devices on the markt of wearable devices. At least at the current moment.

How do I remove Adware Generic7.CASB?

If your antivirus software like AVP reports a threat through Adware Gerneric7.CASB and is not able to treat it itself, don’t become desperate. Generally, it is possible to remove this nasty Trojan yourself. However, this way is complicated and not safe for your system, if you are not a virus expert. Adware Generic is able to rename itself and also rename other important system files, so that you can accidentally corrupt useful applications.

In order to remove Adware Generic7.CASB just use a free tool AdwCleaner. It is a small program, which is even not required to be installed. It knows almost all kinds of adware and can repair your PC in a few moments.

  • First, start AdwCleaner and run the scan of your computer.
  • After AdwCleaner finds adware, press “Clean” button
  • Adware Generic7.CASB will be automatically removed from your computer. You will be prompted to restart your PC.
  • After system restart you can view the log file and wonder how deep Adware Generic7.CASB set in your operation system. That’s all.


PolterApp Version 1.11

Die neue Version der PolterApp stellt ein Hotfix für die Kartennutzung dar. Der Schlüssel für die Nutzung der Google-Maps war abgelaufen und musste erneuert werden. Es ist nun wieder möglich eigene Position und Positionen der erfassten Polter auf der Karte sehen.

Google Analytics for iOS

Once I reported about my experience with HockeyApp a tracking tool for iOS, Android and Windows Apps. Today I tested the abilities of Google Analytics for iOS. Without going deep in details here is the overview of the evaluation results:

  • There are SDKs only for iOS and Android. Tracking of the Windows Apps is not supported.
  • Tracking of the fatal and non fatal exceptions is possible
  • Screen tracking. If desired, the tracking method can be called for example in viewWillAppear. In the dashboard of Google Analytics there is the overview of the called Views.
  • Support for custom events
  • Real time screen end events tracking
  • Dashboard of the App Analytics looks almost same as the dashboard for tracking websites
  • If tracking private user data, be sure to learn about privacy policy and the proper use of the Google Analytics in your app