Appcelerator: Event when reopening App - ios

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

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.

Delete Data from Web SQL database whenever phonegap Application's exit event occurs

I have two Questions:
What is the exit event of phone-gap Application? I haven't find it yet.
How to Delete Data from All the tables whenever exit event occurs? and insert it back from the web service whenever the deviceready() event of phonegap occurs.
Thanks in advance.
Regards.
I think you are looking for the pause event. The documentation reads like this:
The pause event fires when the native platform puts the application into the background, typically when the user switches to a different application.
You can attach a handler to this event like this:
document.addEventListener("pause", onPause, false);
Now the onPause method will be called everytime your app is going to the background and you can drop your tables there somewhat like this:
function onPause() {
db.transaction(function (tx) {
tx.executeSql("DROP TABLE foo",[],
function(tx,results){console.log("Successfully Dropped")},
function(tx,error){console.log("Could not delete")}
);
});
}
Assuming the db variable holds your WebSQL database and you're trying to drop the table named foo.

jQuery UI Focus Issue

I am getting Issue
unable to get property'_focusTabbable'of undefined or null reference
I am using Jquery-ui-1.10.2.custom.js
Here I am getting issue in
if ( !$.ui.dialog.overlayInstances ) {
// Prevent use of anchors and inputs.
// We use a delay in case the overlay is created from an
// event that we're going to be cancelling. (#2804)
this._delay(function() {
// Handle .dialog().dialog("close") (#4065)
if ( $.ui.dialog.overlayInstances ) {
this.document.bind( "focusin.dialog", function( event ) {
if ( !that._allowInteraction( event ) ) {
event.preventDefault();
**$(".ui-dialog:visible:last .ui-dialog-content")
.data( widgetFullName )._focusTabbable();**
}
});
}
});
}
This bug arises when you open a dialog and then, in an action button of this dialog, call a method that opens a second dialog. When you attempt to close the second dialog, the bug appears.
To prevent this from happening, close the first dialog immediately, and then call the second dialog.
$('#dialog1').dialog({
buttons: {
'No': function () {
$(this).dialog('close')
},
'Yes': function () {
// This works
$(this).dialog('close');
// Open second dialog
OpenSecondDialog()
// This doesn't work. A bug will arise when attempting to close the second dialog
$(this).dialog('close');
}
}
});
I'm opening one dialog and then another to confirm changes which were done in the first dialog. When confirming it doesn't close the first dialog which was opened. So I'm just destroying everything to get rid of the focus issue.
$(".ui-dialog-content").dialog('destroy');
I just put this one in the confirm function of the last dialog so it destroys all my dialogs (since they have the same class).
Just for future reference (and in case anyone else experiences this problem), I got the same error in jQuery UI 1.10.3 when re-opening a dialog after partial postbacks in asp.net. I found out that this was due to a variable $.ui.dialog.overlayInstances that is supposed to evaluate to 1 before the dialog is closed. Since every time the dialog is opened the variable is increased by 1, when the user pressed the close button my value often evaluated to 2 or more. My solution was to reset $.ui.dialog.overlayInstances to 1 every time I opened the dialog. So:
$("#myDiv").dialog("open");
$.ui.dialog.overlayInstances = 1;
I was working jquery-ui-1.12.1 and encountered the same error and as Emyr pointed out this bug has been fixed.
My first workaround used George Beiers approach. Close dialog1 before creating dialog2, then I would restore dialog1 after closing dialog2. The result didn't look so well but it cleared the error in every browser except Internet Explorer.
Turns out there was a function that was attempting to closed my dialog1(already closed) before closing dialog2. Once I reordered the code I was able to keep dialog1 open while I displayed dialog2.
My suggestion if you are having trouble fixing this issue is to add a console log message on the beforeClose and open events to keep an eye for odd behavior.
I remember that error.
For me was
I tried to open a modal by code, then I opened other modal also by code...
They opened well... but if tried again, I received that error.
I had to close the first modal before open a new one.

How to detect user idle time since last touch and return the app to home page using phonegap

I would like to check for the user idle time since last touch and return the app to the home page after some period of time. I want this to be done using phonegap.
I googled and did find few solutions but I want to detect the idle time and return the app to the home page.
Thanks.
Using jQuery you *could bind a start touch event and end touch event then using a timer to execute a function
$('body').bind('touchstart',function() {
clearInterval(myTimer);
});
$('body').bind('touchend', function() {
myTimer = setInterval(function() {
/* return user to homepage */
},30000);
});
Touch events are a little buggy in mobile devices. But you set an Interval timer to run after a set amount of time after the last touch is detected. Remembering to clear it on the next touchstart event. Its a bit messy but should work (I havent tested it btw)
I got this working by setTimeout('Redirect()', 10000); where Redirect fn is function Redirect() { window.location.href="mylink.html"; }

Resources