Skip to content

Instantly share code, notes, and snippets.

@squio
Last active April 5, 2022 10:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squio/1ff10bcca2aa1427a919e1c35cbc82fb to your computer and use it in GitHub Desktop.
Save squio/1ff10bcca2aa1427a919e1c35cbc82fb to your computer and use it in GitHub Desktop.
Ionic App Resume
import { TestBed } from '@angular/core/testing';
import { AppResumeService } from './app-resume.service';
describe('AppResumeService', () => {
let service: AppResumeService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AppResumeService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
/**
* Service to handle App Resume events and data
*
* Life cycle:
*
* - call saveState() from the page where the app should resume
* - check hasData on entering the module
* - if hasData is true, get the data with getData()
* - call resetState() when done
*
* On App Resume, when plugin data is available, and the app
* location was set with saveState, the data is restored and
* the saved location opened.
*
* @see https://github.com/ionic-team/capacitor/issues/2931
*/
import { Injectable, NgZone } from '@angular/core';
import { Storage } from '@capacitor/storage';
import { Router } from '@angular/router';
import { RestoredListenerEvent } from '@capacitor/app';
@Injectable({
providedIn: 'root'
})
export class AppResumeService {
private _hasData: boolean = false;
public get hasData(): boolean {
return this._hasData;
}
private _restoredState: RestoredListenerEvent;
constructor(
private router: Router,
private zone: NgZone,
) {}
public async saveState()
{
const location = this.router.url;
await Storage.set({
key: 'lastAppLocation',
value: location
});
}
public async resetState()
{
await Storage.remove({
key: 'lastAppLocation'
});
this._hasData = false;
this._restoredState = null;
}
public async restoreAppState(state: RestoredListenerEvent)
{
this._restoredState = state;
if (this._restoredState.success)
{
this._hasData = true;
const location = await Storage.get({key: 'lastAppLocation'});
if (location?.value)
{
console.log(`Restored state from ${this._restoredState.pluginId}.${this._restoredState.methodName}() for ${location.value}`);
this.zone.run(() => {
return this.router.navigateByUrl(location.value);
});
}
else
{
console.log(`Restored state from ${this._restoredState.pluginId} without saved location, ignoring`);
}
}
else
{
console.log(`Restored state error from ${this._restoredState.pluginId}, error ${this._restoredState.error}`);
this.resetState();
}
}
public getData()
{
return this._restoredState.data;
}
}
// In App Component add:
import { AppResumeService } from './services/app-resume.service';
import { App, RestoredListenerEvent } from '@capacitor/app';
// ...
constructor(
private platform: Platform,
private resumeService: AppResumeService,
)
{
App.addListener('appRestoredResult', (event: RestoredListenerEvent) => {
this.resumeService.restoreAppState(event);
});
}
}
// In App Module add:
import { AppResumeService } from './services/app-resume.service';
// ...
@NgModule({
declarations: [
AppComponent,
],
providers: [
AppResumeService,
// ...
],
// ...
bootstrap: [AppComponent]
})
export class AppModule
{
}
// Add this to your photo page
import { Camera, CameraDirection, CameraResultType, CameraSource, Photo } from '@capacitor/camera';
import { AppResumeService } from 'src/app/services/app-resume.service';
// ..
export class MyPhoto {
constructor(
private appResumeService: AppResumeService,
) {}
async ionViewWillEnter()
{
await this.appResumeService.saveState();
if (this.appResumeService.hasData)
{
// We know this is a Camera result of type Photo:
const pluginData: Photo = this.appResumeService.getData();
console.log('Restored photo data format:', pluginData.format);
console.log('Restored photo data:', pluginData.base64String.substring(0, 50), '⋯');
this.imageURL = 'data:image/jpeg;base64,' + pluginData.base64String;
}
}
async ionViewDidLeave()
{
await this.appResumeService.resetState();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment