Offline support for React Native App - ios

I am looking to add offline support to a React Native application. The app currently runs off an API that is backed by a Postgres db.
I am already using NetInfo to determine whether a user has a connection or not but am looking to understand the best way to add offline capabilities where a user can continue to update their data and information and then just have everything sync when they get a connection again.
It seems like a pouchdb/couchdb solution is often recommended - however, I don't want to change my database at all. Ideally, I'd love to have some sort of way to store "jobs" of API calls in a queue and then execute them once connection is restored.
What is the best way to go about getting this offline functionality on a React Native App.
Thanks in advance!

You may use e.g. redux for data storage in general. Assuming you have a LOAD_POSTS_DATA action, which a component may fire at a point of time you may use a a reducer like this:
export const LOAD_POSTS_DATA = 'LOAD_POSTS_DATA';
var connected = ... // filled by NetInfo
const initialState = {
data: [],
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case LOAD_POSTS_DATA:
if (connected) {
return {
open: true,
};
}
return state;
default:
return state;
}
}
export function load() {
return {
type: LOAD_POSTS_DATA,
};
}
This would only not load the data, for the deferring you would write a second reducer like this:
const CLEAR_QUEUE = 'CLEAR_QUEUE';
import { LOAD_POSTS_DATA } from './otherReducer';
var connected = ... // filled by NetInfo
const initialState = {
queue: [],
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case LOAD_POSTS_DATA:
if (!connected) {
var q = state.queue;
q.push(action);
return {
queue: q,
};
}
return state;
case CLEAR_QUEUE:
return {
queue: []
}
default:
return state;
}
}
// needs to be called as soon as you go back only
// requires redux-thunk
export function getOperations() {
return (dispatch, getState) => {
const { thisReducer: { queue } } = getState();
queue.forEach(action => dispatch(action));
return {
type: CLEAR_QUEUE,
};
};
}
The second one stores every deferrable action (needs to be imported from other reducers) and uses redux-thunk to get hold of the actions and dispatch them as soon as you are back online.

Take a look at realm: https://realm.io, you can use it as database on your app, then as soon as you have the connectivity you can sync the data.

Related

Flutter Blue Writing Automatically

I have used Flutter Blue for a college work, where I need to create an application to fetch and pass information to an equipment. The passing of this data must be automatic, as in any application (after all the end user should not look for the services and characteristics necessary to carry out the process). The problem is that I am not being able to perform the data passing soon after connecting with the device.
I'm using the App example I downloaded at https://github.com/pauldemarco/flutter_blue, so the basic idea is that as soon as I connect to my bluetooth device I send a message to a certain device. There is already an answered question that has the interest of setting notifications when connecting at Flutter Blue Setting Notifications
I followed the same example but instead of using _setNotification (c) I used the _writeCharacteristic (c), but it does not work.
_connect(BluetoothDevice d) async {
device = d;
// Connect to device
deviceConnection = _flutterBlue
.connect(device, timeout: const Duration(seconds: 4))
.listen(
null,
onDone: _disconnect,
);
// Update the connection state immediately
device.state.then((s) {
setState(() {
deviceState = s;
});
});
// Subscribe to connection changes
deviceStateSubscription = device.onStateChanged().listen((s) {
setState(() {
deviceState = s;
});
if (s == BluetoothDeviceState.connected) {
device.discoverServices().then((s) {
services = s;
for(BluetoothService service in services) {
for(BluetoothCharacteristic c in service.characteristics) {
if(c.uuid == new Guid("06d1e5e7-79ad-4a71-8faa-373789f7d93c")) {
_writeCharacteristic(c);
} else {
print("Nope");
}
}
}
setState(() {
services = s;
});
});
}
});
}
I have changed the original code so that it prints me the notifications as soon as I perform the writing method. The notifications should show me a standard message that is in the firmware of the device, but instead it is printing me the Local Name of the bluetooth chip, being that if I select the service and characteristic manually the return is the correct message.
You'd need to elaborate how you're executing writes on the descriptor - inside _writeCharacteristic(c).
BluetoothDescriptor.write() is a Future per docs, you should be able to catch any errors thrown during write.

Access multiple Realtime Databases of the same firebase app project

I found some explanations about connecting multiple databases from separate app projects with angularfire2. But I would like to access databases within the same project.
The documentation stated:
// Get the default database instance for an app
var database = firebase.database();
// Get a secondary database instance by URL
var database = firebase.database('https://testapp-1234.firebaseio.com');
How can I do this with angularfire2?
I know you got a working answer here : https://github.com/angular/angularfire2/issues/1567
tested with : "angularfire2": "^5.0.0-rc.6.0", "firebase": "^4.12.1"
I've built a minimalist wrapper inspired of the #1567 I'd like to share. There are 2 methods with different or same project to use multiple databases.
You'll probably use the first one, I don't really understand the point of using multiple databases within multiple project.
#Injectable()
export class AngularFireWrapper {
// Default database
private _firebaseDb = this.afDb.database;
constructor(private afDb: AngularFireDatabase,
#Optional() dbName: string) {
console.log('Hello AngularFireWrapper, db :', dbName || 'default');
// 1st Method, same project, same auth
// environment.dbUrls = {
// ...
// otherDb: 'https://DB_NAME_SAME_PROJECT.firebaseio.com/'
// }
if (dbName && environment.dbUrls[dbName]) {
const app: any = this.afDb.app;
this._firebaseDb = app.database(environment.dbUrls[dbName]);
}
// 2nd Method, other project, different auth =/
// environment.dbConfigs = {
// ...
// otherDb: {...} // usual firebase configs
// }
if (dbName && environment.dbConfigs[dbName]) {
this._firebaseDb = firebase.initializeApp(environment.dbConfigs[dbName], dbName)
.database();
}
}
db(dbName): AngularFireWrapper {
return new AngularFireWrapper(this.afDb, dbName);
}
object(path: string): AngularFireObject<any> {
const ref = this._firebaseDb.ref(path);
return this.afDb.object(ref);
}
list(path: string, queryFn?: QueryFn): AngularFireList<any> {
const ref = this._firebaseDb.ref(path);
return this.afDb.list(ref, queryFn);
}
}
Copy-Paste, inject it as you usually do with your custom services and then :
export class MyApp {
constructor(private afW: AngularFireWrapper) {
this.afW.object('test')
.valueChanges()
.subscribe(console.log)
// => output default db values
this.afW.db('otherDb').object('test')
.valueChanges()
.subscribe(console.log)
// => output otherDb values
}

Pass custom data to service worker sync?

I need to make a POST request and send some data. I'm using the service worker sync to handle offline situation.
But is there a way to pass the POST data to the service worker, so it makes the same request again?
Cause apparently the current solution is to store requests in some client side storage and after client gets connection - get the requests info from the storage and then send them.
Any more elegant way?
PS: I thought about just making the service worker send message to the application code so it does the request again ... but unfortunately it doesn't know the exact client that registered the service worker :(
You can use fetch-sync
or i use postmessage to fix this problem, which i agree that indexedDB looks trouble.
first of all, i send the message from html.
// send message to serviceWorker
function sync (url, options) {
navigator.serviceWorker.controller.postMessage({type: 'sync', url, options})
}
i got this message in serviceworker, and then i store it.
const syncStore = {}
self.addEventListener('message', event => {
if(event.data.type === 'sync') {
// get a unique id to save the data
const id = uuid()
syncStore[id] = event.data
// register a sync and pass the id as tag for it to get the data
self.registration.sync.register(id)
}
console.log(event.data)
})
in the sync event, i got the data and fetch
self.addEventListener('sync', event => {
// get the data by tag
const {url, options} = syncStore[event.tag]
event.waitUntil(fetch(url, options))
})
it works well in my test, what's more you can delete the memory store after the fetch
what's more, you may want to send back the result to the page. i will do this in the same way by postmessage.
as now i have to communicate between each other, i will change the fucnction sync into this way
// use messagechannel to communicate
sendMessageToSw (msg) {
return new Promise((resolve, reject) => {
// Create a Message Channel
const msg_chan = new MessageChannel()
// Handler for recieving message reply from service worker
msg_chan.port1.onmessage = event => {
if(event.data.error) {
reject(event.data.error)
} else {
resolve(event.data)
}
}
navigator.serviceWorker.controller.postMessage(msg, [msg_chan.port2])
})
}
// send message to serviceWorker
// you can see that i add a parse argument
// this is use to tell the serviceworker how to parse our data
function sync (url, options, parse) {
return sendMessageToSw({type: 'sync', url, options, parse})
}
i also have to change the message event, so that i can pass the port to sync event
self.addEventListener('message', event => {
if(isObject(event.data)) {
if(event.data.type === 'sync') {
// in this way, you can decide your tag
const id = event.data.id || uuid()
// pass the port into the memory stor
syncStore[id] = Object.assign({port: event.ports[0]}, event.data)
self.registration.sync.register(id)
}
}
})
up to now, we can handle the sync event
self.addEventListener('sync', event => {
const {url, options, port, parse} = syncStore[event.tag] || {}
// delete the memory
delete syncStore[event.tag]
event.waitUntil(fetch(url, options)
.then(response => {
// clone response because it will fail to parse if it parse again
const copy = response.clone()
if(response.ok) {
// parse it as you like
copy[parse]()
.then(data => {
// when success postmessage back
port.postMessage(data)
})
} else {
port.postMessage({error: response.status})
}
})
.catch(error => {
port.postMessage({error: error.message})
})
)
})
At the end. you cannot use postmessage to send response directly.Because it's illegal.So you need to parse it, such as text, json, blob, etc. i think that's enough.
As you have mention that, you may want to open the window.
i advice that you can use serviceworker to send a notification.
self.addEventListener('push', function (event) {
const title = 'i am a fucking test'
const options = {
body: 'Yay it works.',
}
event.waitUntil(self.registration.showNotification(title, options))
})
self.addEventListener('notificationclick', function (event) {
event.notification.close()
event.waitUntil(
clients.openWindow('https://yoursite.com')
)
})
when the client click we can open the window.
To comunicate with the serviceworker I use a trick:
in the fetch eventlistener I put this:
self.addEventListener('fetch', event => {
if (event.request.url.includes("sw_messages.js")) {
var zib = "some data";
event.respondWith(new Response("window.msg=" + JSON.stringify(zib) + ";", {
headers: {
'Content-Type': 'application/javascript'
}
}));
}
return;
});
then, in the main html I just add:
<script src="sw_messages.js"></script>
as the page loads, global variable msg will contain (in this example) "some data".

NativeScript firebase: Firebase instance is not persisted in background service while application is closed

I'm trying to tap on the incoming call using a following background service in NativeScript and searching the incoming number in Firebase Database.
The firebase.query from nativescript-plugin-firebase code works fine if the application UI is visible or minimized in Android but when the application is closed (however, the service is running in background), it throws firebase.query: TypeError: Cannot read property 'child' of null error. Any Idea.
app/broadcastreceivers/NotificationEventReceiver.js:
var application = require("application");
var firebase = require("nativescript-plugin-firebase");
var incomingCallDetected = false;
var TelephonyManager = application.android.context.getSystemService(android.content.Context.TELEPHONY_SERVICE);
android.support.v4.content.WakefulBroadcastReceiver.extend("com.tns.broadcastreceivers.NotificationEventReceiver", {
onReceive: function (context, intent) {
if (intent.getAction() === 'android.intent.action.PHONE_STATE') {
incomingCallDetected = true;
}
}
});
var callStateListener = android.telephony.PhoneStateListener.extend({
onCallStateChanged: function (state, phoneNumber) {
if (incomingCallDetected && state === 1) { // incoming call ringing
firebase.query(
function(result) {
console.log(JSON.stringify(result));
},
"/calls",
{
singleEvent: true,
orderBy: {
type: firebase.QueryOrderByType.CHILD,
value: 'PhoneNumber'
},
range: {
type: firebase.QueryRangeType.EQUAL_TO,
value: phoneNumber.replace(/\s+/g, '').substr(-10)
}
}
);
incomingCallDetected = false;
}
}
});
TelephonyManager.listen(new callStateListener(), android.telephony.PhoneStateListener.LISTEN_CALL_STATE);
Update: This line in nativescript-plugin-firebase causes the problem because firebaseInstance does not persist in the service once the application is closed.
I think thats because the firebase is never initiated in background service, I guess you are doing it only in app code so it works when it is on foreground.

SignalR and Kendo Ui Scheduler

I'm working in an implementation using SignalR and the Kendo Scheduler. When a new task is created (for exemple), the SchedulerDataSource transport send the connection hub id to the server as an additional parameter:
transport: {
read: { url: global.web_path + 'Home/Tasks' },
update: { url: global.web_path + 'Home/UpdateTask', type: 'PUT', contentType: 'application/json' },
create: { url: global.web_path + 'Home/CreateTask', type: 'POST', contentType: 'application/json' },
destroy: { url: global.web_path + 'Home/DeleteTask', type: 'DELETE', contentType: 'application/json' },
parameterMap: function (options, operation) {
if (operation == "destroy" && options.models) {
return JSON.stringify({ taskId: options.models[0].Id, callerId: $.connection.hub.id });
}
if (operation !== "read" && options.models) {
return JSON.stringify({ tasks: options.models, callerId: $.connection.hub.id });
}
}
},
The server do whatever it has to do, and send a notification to every other user, except de caller:
[HttpPost]
public JsonResult CreateTask(List<ScheduledEvent> tasks, string callerId)
{
...create task and other stuff
//broadcast the newly created object to everyone except caller
var hubContext = GlobalHost.ConnectionManager.GetHubContext<Notebooks.Hubs.SchedulerHub>();
hubContext.Clients.AllExcept(callerId).UpdateSchedule(task);
//return the object to caller
return Json(task);
}
Once the other clients receive a new task from the hub, it is added to the SchedulerDataSource:
hub.client.updateSchedule = function (scheduledEvent) {
schedulerDataSource.add(scheduledEvent);
}
Everything seems to work fine, and it really took me some time to realize this behavior: if a client have the scheduler window open, this window is closed once the schedulerDataSource is updated. This is expected or am I doing something wrong?
Edit: I just realized how old this question is, so you have probably moved on to other things by now, or the pushCreate method may not have existed back then.
I think this may be how it works, but it seems like it should be able to add those events behind the scenes without having to close the edit window. Have you tried the pushCreate method? If that doesn't work, since the add automatically closes the edit dialog, maybe when the events come in, if the dialog is open, you could store the new events, then add them when the user closes the edit dialog.
My answer is now even older ;) but I faced this very same issue today.
First, I'm quite sure this is indeed the expected behavior. You can see in the kendo sources the call of the close editor window method in the transport update and create methods of the scheduler.
Below is what I've done to bypass the issue .
The idea is as simple as to prevent the edit window to close when an appointment modification comes from another hub client.
Server-side : modify the hub methods (example with update method)
public MyAppointmentViewModel Update(MyAppointmentViewModel appointment)
{
if (!appointmentService.Update(appointment))
throw new InvalidOperationException("Something went wrong");
else
{
Clients.Others.PrepareBeforeAddOrUpdateSignal(appointment.Id);
Clients.Others.Update(appointment);
return appointment;
}
}
Here you see we inform every other clients (through PrepareBeforeAddOrUpdate) we're about to update an appintment.
Client-side now (in index.cshtml for instance)
schedulerHub.client.prepareBeforeAddOrUpdateSignal = function(id){ lastModifiedRdvId = id; };
schedulerHub.client.create = function(appointment){ lastModifiedRdvId = 0; }; /* reset the variable for next time */
schedulerHub.client.update = function(appointment){ lastModifiedRdvId = 0; }; /* reset the variable for next time */
function SchedulerEditor()
{
return $(".k-scheduler-edit-form").data("kendoWindow");
}
var eventBeforeChanges = null;
var lastModifiedRdvId = 0;
function onEditorClose(e) {
if (eventBeforeChanges != null) {
if (lastModifiedRdvId > 0 && eventBeforeChanges.Id != lastModifiedRdvId)
e.preventDefault();
else {
var editWin = SchedulerEditor(); /* unbind this callback and use default behavior again */
editWin.unbind('close', onEditorClose);
}
}}
function onEditRdv(e) {
var editWin = SchedulerEditor();
if (editWin != null) /*Bind the close event */
editWin.unbind('close', onEditorClose).bind('close', onEditorClose);
eventBeforeChanges = e.event;
/* continue onEditRdv */
}
you see here the close event is prevented when the appointment id is not the appointment id beeing updated by the current client.
And fortunately, preventing the close event prevents the annoying behavior of having a sort of ghost appointment after one has been changed by another hub client.
I'm sorry if I'm not clear or if the code isn't clear enough. I can provide more information if necessary.
Bye

Resources