Background timer for react-native ios - ios

I need to restrict one my functionality with a timer. So I am using react-native-background-timer plugin for that. In case of android, its working fine and I am getting my expected output. But in case of IOS it working only when app is in foreground, when I press home button after 4-5 seconds this plugin timer also gets paused. I have followed all instructions mentioned in this plugin. Still no luck.
Here is my code:-
BackgroundTimer.start();
setInterval(() => {
// Here I am writing my business logic
//Which works properly in case of foreground.
}, 1000)
I am also added comment here to get implementation help.
Please let me know. Is I am doing anything wrong?
Also suggest any alternatives for my functionality.

You mentioned plugin is wroking fine, because it's using dispatchAsync method which is basically using in IOS to do small background work.
Check Usage Crossplatform section.
BackgroundTimer.runBackgroundTimer(() => {
console.log("Background Timer");
//Check above log will appear after every 3 seconds.
//Your timer reducing and updating code goes here
},
3000);
//Don't forget to remove Timer
//rest of code will be performing for iOS on background too
BackgroundTimer.stopBackgroundTimer();

Related

Can anyone recommend the solution to solve ionic background issue in IOS

The app is able to send the HTTP POST successfully as long as it's in the foreground, but as soon as it goes to the background, the HTTP POST appears to stop. This is only an issue for iOS.
I tried the cordova-plugin-background-mode plugin but i don't want the audio part. is there any working example code using angular ng.IHttpService.
public GetEmployeeList(): ng.IPromise<Mobile.Models.Employee[]> {
return this.$http.get("~/api/Employee/EmployeeList")
.then((response: ng.IHttpPromiseCallbackArg<Mobile.Models.Employee[]>): Mobile.Models.Employee[] => {
return response.data;
});
}
if you just wanna keep your app alive when its in the background, surely the audio part is the easiest way.and to sove your particular issue, you need know how the "Background Model" works. https://upload-images.jianshu.io/upload_images/1501971-91e6c1164e13c3ee.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000
Being curious why dont you wanna use the normal way to salve the problem since there are so many tracks to use with the background model.

Refresh app every time user opens it

I'm using Phonegap Cordova and have an iOS app and web app that sync information to each other, the problem I'm having though is that if the user has the iOS open on their device, but minimized, the data doesn't update realtime. So if they add something on the web app and look at the iOS app the changes wouldn't have been made on the iOS side so they'd have to close the app and relaunch. This isn't very user friendly.
Would anyone have any advice how to fix this? Perhaps refresh the app every time they open, or scroll up to refresh manually?
Any help would be great! Thank you.
use this plugin :
cordova-plugin-background
and in index use this code for refrech the app
document.addEventListener('deviceready', function () {
cordova.plugins.backgroundMode.enable();
cordova.plugins.backgroundMode.onactivate = function () {
setInterval(function () {
location.reload();
}, 10000);
}
}, false);
you app it' well refrech in backround every 10000 second you can change the time
You definitely have a few options here:
You can use Cordova's resume event which should fire when the user brings the app back to the foreground (at least I think that's what it does, I haven't used that event myself)
If it applies to your use case, you could use the push plugin to push data to your device and trigger updates
A manual slide down to refresh would also be good, maybe even on top of the options above

IONIC2 - app gets killed after some time even when using Background Geolocation

I have an IONIC2 app, which needs to wake up every morning at 8 AM for 20 minutes to send user reminders based on the user's geolocation.
I am using this plugin (which uses IOS significant changes API to monitor changes in user's location)
https://github.com/mauron85/cordova-plugin-background-geolocation
The problem:
The app doesn't get killed when I close the app and the background geolocation works for me fine for some time. I have tested upto an hour. But when I wake up next morning, I find the app was killed by IOS.
I know there is another plugin to keep the app running in the background https://github.com/katzer/cordova-plugin-background-mode, but I have read tons of complaints from people that it will cause your app to be rejected by the AppStore (In fact, the plugin has a disclaimer to the same effect too).
For waking up the app tomorrow, I simply set a setTimeout
setTimeout(function(){
console.log('waking up');
self.helper.scheduleLocalNotification('Hello World', 'Good Morning', 10, "");
self.ionViewDidEnter();
}, wakeupinMilliSeconds);
Here is my geolocation code:
setupBackGroundGeolocation(){
let config = {
desiredAccuracy: 100,
stationaryRadius: 50,
distanceFilter: 100,
interval: 5000,
pauseLocationUpdates: false,
debug: false, // enable this hear sounds for background-geolocation life-cycle.
stopOnTerminate: false, // enable this to clear background location settings when the app terminates
};
BackgroundGeolocation.configure((location) => {
console.log('[js] BackgroundGeolocation callback: ' + location.latitude + ',' + location.longitude);
this.currentLocation.lat = location.latitude;
this.currentLocation.lng = location.longitude;
Promise.all([
//I do some calculations here.
]).then(d => {
// IMPORTANT: You must execute the finish method here to inform the native plugin that you're finished,
// and the background-task may be completed. You must do this regardless if your HTTP request is successful or not.
// IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background.
BackgroundGeolocation.finish(); // FOR IOS ONLY
});
}, (error) => {
console.log('BackgroundGeolocation error');
}, config);
// Turn ON the background-geolocation system. The user will be tracked whenever they suspend the app.
BackgroundGeolocation.start();
}
I don't use this plugin but had same symptons. I couldn't figure out what was wrong: no error messages, no clues but app kept closing after a few hours.
I guess there was something messed up after installing and uninstalling so many cordova plugins. Now the app is much more stable. I removed and added platform. That seemed to do the job.
I've been reading about ionic2 and performance. Among so many reasons, a possibility about low performance and crash is related not to unsubscribe from observables. Read about async pipe and .unsubscribe observables when component is destroyed ngOnDestroy
Another problem i found was a very basic mistake developing in angular. I loaded everything in the app module so this required lot of memory to load the entire app at once. I guess with slow terminals that can affect more. Anyway, basic angular concepts as .module files should be understood.

iOs Swift: How to pass a task to the background thread?

In my iOS app I have a task that is executed perodically with a timer (the task is checking my database every 10 seconds):
var timer: dispatch_source_t!;
timer = Dispatch.timerAsync(interval: intervalTime){
//my task here
}
if a speciifc parameter in my database is set then I stop the timer and process the results (including updating the UI) in the main thread:
dispatch_async(dispatch_get_main_queue()) {
self.processResults();
}
Now what I'm trying to do is to make this work when the user switches to another app. When my app goes to the background the timer stops working and when I go back to my app it starts working again. I wanted to know if it is possible to pass this task with the timer to the background thread when the user switches to another app so that my app still checks the database every 10 seconds and if the parameter in the database is set the user gets a notification (local notification). I would like to avoid using Apple's remote notification if possible... Is this possible?
I don't have enough experience with app programming so I wanted to get some idea to see if I'm approaching this problem the right away. Any input, suggestion or sample code is very appreciated. Thanks!

PhoneGap - Cordova / Application freeze during 5 seconds when resumed through app icon

I own an AngularJs app that I converted into a native app through Cordova.
The whole works on iOS (iphone), however I've just noticed that if I put the app on the background, then reopen/resume it, the application sometimes "freezes" for about 5 seconds then works.
No scrolling, no click events, for 5 seconds.
Any known reason to this? How to avoid it? It's very frustrating.
I found the code causing the issue:
document.addEventListener("resume", function () {
$rootScope.$broadcast('retrieveAllNotifications', null);
}, false);
So, according to the documentation:
Interactive functions like alert() when the resume event fires will
need to be wrapped in a setTimeout call with a timeout value of zero,
or else the app will hang. e.g.
So I transformed to:
document.addEventListener("resume", function () {
$timeout(function () {
$rootScope.$broadcast('retrieveAllNotifications', null);
}, 0);
}, false);
but it still hangs.
However, when I remove the broadcast, it works.
How to fix it? Increasing the timeout to 1 second for instance?
Actually, I noticed that I retrieved more than 500 notifications that are displayed (though hidden) in HTML.
What I've done is to delete a lot of notifications, and I noticed no more freeze.
It was just too heavy for the phonegap app to display 500 notifications at once without freezing.

Resources