KendoUI mobile app, view event afterShow has no access to cordova plugin. Outside event is fine - cordova-plugins

I have a kendoui applbuilder mobile app. I have installed a custom camerapreview plugin and it works fine. I tried adding an event handler to my view (afterShow) to set something in the camera plugin module:
cordova.plugins.camerapreview.startCamera(
which initializes the camera preview.
the problem seems to be that in this handler cordova.plugins.camerapreview is undefined? Access to this same method in a button handler on the view works fine. I'm assuming this has something to do with dependency? How can i ensure this is loaded? Doesn't make sense to me that it wouldn't be available after the view has loaded and bound the model.
my code looks like:
// Handle "deviceready" event
document.addEventListener('deviceready', onDeviceReady, false);
var mobileApp = new kendo.mobile.Application(document.body, {
skin: 'flat',
initial: 'views/home.html'
});

When using Kendo UI Mobile app with Cordova, make sure to initialize the app in the deviceready event. This will ensure that the Cordova APIs will be available throughout the whole app lifecycle.
// this function is called by Cordova when the application is loaded by the device
document.addEventListener('deviceready', function () {
// hide the splash screen as soon as the app is ready. otherwise
// Cordova will wait 5 very long seconds to do it for you.
navigator.splashscreen.hide();
app = new kendo.mobile.Application(document.body, {
// you can change the default transition (slide, zoom or fade)
transition: 'slide',
// comment out the following line to get a UI which matches the look
// and feel of the operating system
// skin: 'flat',
// the application needs to know which view to load first
initial: 'views/home.html'
});
}, false);

Related

ReactJs PWA not updating on iOS

I'm building a ReactJs PWA but I'm having trouble detecting updates on iOS.
On Android everything is working great so I'm wondering if all of this is related to iOS support for PWAs or if my implementation of the service worker is not good.
Here's what I've done so far:
Build process and hosting
My app is built using webpack and hosted on AWS. Most of the files (js/css) are built with some hash in their name, generated from their content. For those which aren't (app manifest, index.html, sw.js), I made sure that AWS serves them with some Cache-Control headers preventing any cache. Everything is served over https.
Service Worker
I kept this one as simple as possible : I didn't add any cache rules except precache for my app-shell:
workbox.precaching.precacheAndRoute(self.__precacheManifest || []);
Service-worker registration
Registration of the service worker occurs in the main ReactJs App component, in the componentDidMount() lifecycle hook:
componentDidMount() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then((reg) => {
reg.onupdatefound = () => {
this.newWorker = reg.installing;
this.newWorker.onstatechange = () => {
if (this.newWorker.state === 'installed') {
if (reg.active) {
// a version of the SW is already up and running
/*
code omitted: displays a snackbar to the user to manually trigger
activation of the new SW. This will be done by calling skipWaiting()
then reloading the page
*/
} else {
// first service worker registration, do nothing
}
}
};
};
});
}
}
Service worker lifecycle management
According to the Google documentation about service workers, a new version of the service worker should be detected when navigating to an in-scope page. But as a single-page application, there is no hard navigation happening once the app has been loaded.
The workaround I found for this is to hook into react-router and listen for route changes, then manually ask the registered service worker to update itself :
const history = createBrowserHistory(); // from 'history' node package
history.listen(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.getRegistration()
.then((reg) => {
if (!reg) {
return null;
}
reg.update();
});
}
});
Actual behavior
Throwing a bunch of alert() everywhere in the code showed above, this is what I observe :
When opening the pwa for the first time after adding it to the homescreen, the service worker is registered as expected, on Android and iOS
While keeping the app opened, I deploy a new version on AWS. Navigating in the app triggers the manual update thanks to my history listener. The new version is found, installed in the background. Then my snackbar is displayed and I can trigger the switch to the new SW.
Now I close the app and deploy a new version on AWS. When opening the app again :
On Android the update is found immediately as Android reloads the page
iOS does not, so I need to navigate within the app for my history listener to trigger the search for an update. When doing so, the update is found
After this, for both OS, my snackbar is displayed and I can trigger the switch to the new SW
Now I close the app and turn off the phones. After deploying a new version, I start them again and open the app :
On Android, just like before, the page is reloaded which detects the update, then the snackbar is displayed, etc..
On iOS, I navigate within the app and my listener triggers the search for an update. But this time, the new version is never found and my onupdatefound event handler is never triggered
Reading this post on Medium from Maximiliano Firtman, it seems that iOS 12.2 has brought a new lifecycle for PWAs. According to him, when the app stays idle for a long time or during a reboot of the device, the app state is killed, as well as the page.
I'm wondering if this could be the root cause of my problem here, but I was not able to find anyone having the same trouble so far.
So after a lot of digging and investigation, I finally found out what was my problem.
From what I was able to observe, I think there is a little difference in the way Android and iOS handle PWAs lifecycle, as well as service workers.
On Android, when starting the app after a reboot, it looks like starting the app and searching an update of the service worker (thanks to the hard navigation occuring when reloading the page) are 2 tasks done in parallel. By doing that, the app have enough time to subscribe to the already existing service worker and define a onupdatefound() handler before the new version of the service worker is found.
On the other hand with iOS, it seems that when you start the app after a reboot of the device (or after not using it for a long period, see Medium article linked in the main topic), iOS triggers the search for an update before starting your app. And if an update is found, it will be installed and and enter its 'waiting' status before the app is actually started. This is probably what happens when the splashscreen is displayed...
So in the end, when your app finally starts and you subscribe to the already existing service worker to define your onupdatefound() handler, the update has already been installed and is waiting to take control of the clients.
So here is my final code to register the service worker :
componentDidMount() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then((reg) => {
if (reg.waiting) {
// a new version is already waiting to take control
this.newWorker = reg.waiting;
/*
code omitted: displays a snackbar to the user to manually trigger
activation of the new SW. This will be done by calling skipWaiting()
then reloading the page
*/
}
// handler for updates occuring while the app is running, either actively or in the background
reg.onupdatefound = () => {
this.newWorker = reg.installing;
this.newWorker.onstatechange = () => {
if (this.newWorker.state === 'installed') {
if (reg.active) {
// a version of the SW already has control over the app
/*
same code omitted
*/
} else {
// very first service worker registration, do nothing
}
}
};
};
});
}
}
Note :
I also got rid of my listener on history that I used to trigger the search for an update on every route change, as it seemed overkill.
Now I rely on the Page Visibility API to trigger this search every time the app gets the focus :
// this function is called in the service worker registration promise, providing the ServiceWorkerRegistration instance
const registerPwaOpeningHandler = (reg) => {
let hidden;
let visibilityChange;
if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
hidden = 'hidden';
visibilityChange = 'visibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
hidden = 'msHidden';
visibilityChange = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
hidden = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
window.document.addEventListener(visibilityChange, () => {
if (!document[hidden]) {
// manually force detection of a potential update when the pwa is opened
reg.update();
}
});
return reg;
};
As noted by Speckles (thanks for saving me the headache), iOS installs the new SW before launching the app. So the SW doesn't get a chance to catch the 'installing' state.
Work-around: check if the registration is in the waiting state then handle it.
I've made an (untested) example of handling this. - a mod to the default CRA SW.

How to find if electron app is in foreground?

I have a requirement where I want to perform an action inside the electron app only when it is in foreground.
It is an electron-react application. On mounting of a component, I want to schedule a periodic task which only runs when the app is in focus or is being used by the user. And pause the task when the app goes in background.
How can we detect the Electron app being in foreground?
You can use the isFocused method from BrowserWindow. To get your own BrowserWindow, you can do this :
remote.BrowserWindow.getAllWindows();
This will return all your app's windows. So to get the first / primary window, you could deconstruct the array like this :
const [yourBrowserWindow] = remote.BrowserWindow.getAllWindows();
console.log(yourBrowserWindow.isFocused());
You can use the focus / blur events on your BrowserWindow to be notified when the app is focused / unfocused.
mainWindow = new BrowserWindow({})
mainWindow.on('focus', () => {
console.log('window got focus')
})
mainWindow.on('blur', () => {
console.log('window blur')
})
You may want to update the component's state within these event handlers or use any other method to keep track of the current focus status.
This assumes that you have a single application window. If you have multiple, you'll need to extend the check to cover all of your windows.

Ionic/Cordova iOS - invoke function on app open

Is it possible to invoke a function after applications is re-opened (closed with home button, not closed as a process)?
Yes, you can do this using by injecting the $ionicPlatform service into either a run block (for the entire app) or into a single controller.
Here is an example of it in a run block:
.run(function($ionicPlatform) {
$ionicPlatform.on('resume', function(){
// Do sweet stuff!
});
}
And here it is in a controller:
.controller(function($ionicPlatform) {
$ionicPlatform.on('resume', function(){
// Do sweet stuff!
});
}
Note that this is really just a wrapper for Cordova's resume lifecycle event. You can see more information about the $ionicPlatform service and the 'on' method in the Ionic framework docs here.

Appcelerator: Event when reopening App

I want my app to reload data when it will be reopened (from iOS "Multitasking").
I've tested:
Ti.UI.addEventListener('reload', function() {
alert('reloaded app');
});
but this event just gets fired when the App will be opened the first time.
The app entering the foreground is an app level event. So you need to register on Ti.App, not Ti.UI. In fact I can't find any reference to the event you are using.
Ti.App.addEventListener('resume', function() {
alert('reloaded app');
});
Or you can use "resumed" for after it has completely returned.
See this page

Showing splash screen in PhoneGap/Cordova 1.5.0

I'm trying to get my splash screen to show for my PhoneGap/Cordova native iOS app. The default or boolean for this behavior is set to 'YES'. I'm trying to get the screen to show for 2 seconds. At the moment, it only shows for a split second and then goes right into the app. Since my app does not download any data for the web on start, it loads pretty quickly.
According to this advice, this solution works for some. I'm using the latest Cordova 1.5.0 build: http://shazronatadobe.wordpress.com/2011/09/15/ios-phonegap-splash-screen-control/
I've turned the AutoHideSplashScreen to 'NO' in the Cordova.plist and I'm using this code:
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
setTimeout(function() {
navigator.splashscreen.hide();
}, 2000);
I've tried putting the setTimeout function within a function, but to no avail. Like so:
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function hideSplash() {
setTimeout(function() {
navigator.splashscreen.hide();
}, 2000);
}
And then loading the 'hideSplash()' when the Body loads. But to no avail.
Anything wrong with my code?
OK, I took RespectTheCode's advice and removed the device ready event out of the onLoad function. This is the working code. I'm putting the full code for other's who are learning:
<script>
document.addEventListener("deviceready", onDeviceReady, false);
setTimeout(function() {
navigator.splashscreen.hide();
}, 1000);
</script>
The 1000 is one second for those who don't know. Will not work for less than one second i.e 500. Splash screen just hangs.
This is working for me when I install and app works fine,however, when I restart the device (iPad2) the splash screen hangs like the previous problem (above paragraph) and will not enter the app. Weird bug.
Anyone else experience this?
I'm on iOS 5.1 building with Xcode 4.3.1 and Cordova 1.5.0
I am using Cordova 2.1.0 and now 2.2.0.
When calling navigator.splashscreen.hide(), the Splash Screen didn't disappear.
Using the following code, it worked:
private static native void hideSplashScreen() /*-{
$wnd.Cordova.exec(null, null, "SplashScreen", "hide", []);
}-*/;
Hope this helps

Resources