How to subscribe Ionic 2 platform.pause EventEmitter? - ionic-framework

I'm trying to use the following code to subscribe, but it doesn't work.
import { Platform } from 'ionic-angular';
#Page({
templateUrl: 'build/pages/test.html',
})
export class Test {
constructor(private platform: Platform) {
this.platform.pause.subscribe(() => {
console.log('paused')
});
}
}
I'm using Ionic 2 with TypeScript, Angular 2. As platform.pause is an EventEmitter provided by Ionic 2, I suppose it should be able to be subscribed. However, when I put the application to the background, console.log('pause') is not fired.
Should I add Platform to providers or something like that? Plus, this.platform is not null. this.platform.ready().then(()=>{console.log('ready')}) works perfectly.

I think you missed platform.ready() as below
constructor( private platform: Platform ) {
platform.ready().then(() => {
this.platform.pause.subscribe(() => {
console.log('[INFO] App paused');
});
this.platform.resume.subscribe(() => {
console.log('[INFO] App resumed');
});
});
}
The above code worked for me. Hope it helps you as well.

Related

Ionic 5 - SwipeToClose is impossible

My problem is quite simple : I try to implement a component in modal, but when I try to add SwipeToClose, it's not working (The modal stay static even if I try to swipe down) ...
I'm really confused, but I've create a Stackblitz to show you my issue in detail, maybe I miss something important ... : https://stackblitz.com/edit/ionic-angular-v5-u4wmun
My component :
import { Component, Injectable } from '#angular/core';
import { NavController, ModalController } from '#ionic/angular';
import { ModalComponent } from './modal/modal.component';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myModal:any;
constructor(
public modalController: ModalController
) {
}
async presentModal() {
this.myModal = await this.modalController.create({
component: ModalComponent,
swipeToClose: true,
backdropDismiss: true
});
return await this.myModal.present();
}
}
Thanks to your time !
PS : I try to use it in iOS only, I've already try on my iOS device and it's doesn't work too ...
swipe to close is only available for modals in ios mode(currently ionic v5). So, specify the mode of your modal to be ios
this.myModal = await this.modalController.create({
component: ModalComponent,
swipeToClose: true,
mode: 'ios',
backdropDismiss: true
});
SwipeToClose Gesture only works on IOS mode and could be applied on card modals and will be deprecated by next release. If you apply following method to IonContent element or first element in body, it detects swipeDown gesture and kinda solves that issue and works with all modes.
constructor(public gestureCtrl: GestureController) { }
swipeDownToCloseModal = (elm: HTMLElement)=>{
const swipeGesture: Gesture = this.gestureCtrl.create({
el:elm,
threshold:1,
maxAngle:95,
gestureName:'swipeGesture',
onEnd:e=>{
if(e.velocityY>0.15 && e.deltaY>100 && elm.getBoundingClientRect().y===0){
this.modal.dismiss(); //change
}
}
});
swipeGesture.enable(true);
};

Ionic Low Energy Bluetooth devices not being listed

I am trying to build a prototype Ionic app which runs on Android, where I simply want to see the list of connected devices via Low Energy Bluetooth. The physical devices which I am using is a smart watch Ticwatch E which is connected to my phone via Bluetooth v4.1/BLE. When I run the app, it shows that there are o devices connected via Bluetooth v4.1/BLE. Below is the code. Can anyone help me with this?
(I am new to typescript and javascript- occasionally write a couple of lines of code, so there could also be code mistake)
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { BluetoothLE, DeviceInfo } from '#ionic-native/bluetooth-le';
import { Platform } from 'ionic-angular';
import { Toast } from '#ionic-native/toast';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
foundDevices = [];
constructor(public navCtrl: NavController, public bluetoothle: BluetoothLE, public plt: Platform,
private toast: Toast
) {
let connectedObj: DeviceInfo[] = [];
this.plt.ready().then((readySource) => {
bluetoothle.requestPermission().then(dataTemp => {
console.log('Platform ready from', readySource);
this.toast.show("Platform ready from", '5000', 'center').subscribe(
toast => {
console.log(toast);
}
);
this.bluetoothle.initialize().then(ble => {
console.log('ble', ble.status) // logs 'enabled'
this.toast.show(ble.status, '15000', 'center').subscribe(
toast => {
console.log(toast);
});
this.bluetoothle.retrieveConnected().then(connectedObj => {
this.toast.show("Length: " + connectedObj.devices.length, '25000', 'center').subscribe(
toast => {
console.log(toast);
});
});
});
});
});
}

Build issue for ionic app

I am using FileChooser ionic plugin for Android and FilePicker plugin for IOS. If I use the same code to build android and IOS app, it's giving me the error that FilePicker plugin cant be added to Android.
To build app on different platforms currently, I am maintaining two different branches for iOS build and android build.
I want to maintain my code on only one branch. How can I do that?
Solutions which didn't work:
Searched for the plugin which can work on both iOS and Android but it's not available
Searched if we can add plugins under the platform in config.xml
I found no way to detect the platform and add the plugins accordingly
You can add platform specific checks and use plugins accordingly.
import { Platform } from 'ionic-angular';
import { FileChooser } from '#ionic-native/file-chooser';
import { FilePath } from '#ionic-native/file-path';
import { IOSFilePicker } from '#ionic-native/file-picker';
constructor(
private fileChooser: FileChooser,
private filePicker: IOSFilePicker,
private filePath: FilePath,
private platform: Platform) {
}
chooseFile() {
if (this.platform.is('ios')) {
this.pickFileFromIOSDevice();
}
else if (this.platform.is('android')) {
this.pickFileFromAndroidDevice();
}
}
pickFileFromIOSDevice() {
this.filePicker.pickFile()
.then(
uri => {
this.fileName = uri.substring(uri.lastIndexOf("/") + 1);
}
)
.catch(error => {
this.showError(error);
});
}
pickFileFromAndroidDevice() {
this.fileChooser.open()
.then(
uri => {
this.filePath.resolveNativePath(uri)
.then(file => {
this.fileName = file.substring(file.lastIndexOf("/") + 1);
})
.catch(err => console.log(err));
}
)
.catch(error => {
this.showError(error);
});
}

Network service not working in browser

I've written a provider to help track network connectivity using the Native Network plugin:
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network';
import { Platform } from 'ionic-angular';
#Injectable()
export class Connectivity {
public online: boolean = false;
constructor(private network: Network) {
this.network.onDisconnect().subscribe(() => {
console.log('Network offline');
this.online = false;
});
this.network.onConnect().subscribe(() => {
this.online = true;
console.log('Network online');
});
});
}
}
I've installed the relevent plugins (package.json):
"cordova-plugin-network-information": "^2.0.1",
...
"#ionic-native/network": "^4.7.0",
And I've included my provider in my app.module.ts:
providers: [
Network,
StatusBar,
SplashScreen,
Connectivity,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
Yet, when I run the app in the browser, neither of the observables fire. If I try print: console.log(this.network.type) in the provider constructor, it just prints null.
The answer here is that the native network plugin doesn't work in the browser. Even though it has "browser" listed as a supported platform:
It is referring to the Cordova Browser which is different to a web browser. I found this out after discussion on the Ionic Slack channel.
You need to instead write a Provider that:
Detects platform
If on a native device, use the native network plugin
If in a browser, use the browser API
For others with the same problem:
Here is some clarification on why you have two different APIs available
Here is an example of a provider that uses a variety of approaches for finding location (this isn't the same as my question, but is similar in the solution as it uses a browser API as well as the Ionic Native API)
In my application I use "cordova-plugin-network-information": "^ 2.0.1"
and "#ionic-native / network": "^ 4.6.0"
I can share the same service I use. this is currently working
'# angel / core' import {Injectable};
From the '# Ionic-native / network' resource {Network};
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network';
#Injectable()
export class NetworkProvider {
constructor(private _network: Network) { }
isConnectInternet() {
return this._network.onConnect();
}
isDisconnect() {
return this._network.onDisconnect();
}
enter code here
connectionType() {
if (this._network.type == 'none' ) {
return false;
} else {
return true;
}
}
}
I am using this service into my project which is on following environment
cli packages:
#ionic/cli-utils : 1.19.2
ionic (Ionic CLI) : 3.20.0
global packages:
cordova (Cordova CLI) : 8.0.0
this is my provider file, network.ts.
import { Functions } from './../functions';
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network';
import { Events } from 'ionic-angular';
/*
Generated class for the NetworkProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
export enum ConnectionStatusEnum {
Online,
Offline
}
#Injectable()
export class NetworkProvider {
previousStatus;
constructor(public functions:Functions,
public network: Network,
public eventCtrl: Events) {
this.previousStatus = ConnectionStatusEnum.Online;
}
public initializeNetworkEvents(): void {
this.network.onDisconnect().subscribe(() => {
if (this.previousStatus === ConnectionStatusEnum.Online) {
this.eventCtrl.publish('network:offline');
}
this.previousStatus = ConnectionStatusEnum.Offline;
});
this.network.onConnect().subscribe(() => {
if (this.previousStatus === ConnectionStatusEnum.Offline) {
this.eventCtrl.publish('network:online');
}
this.previousStatus = ConnectionStatusEnum.Online;
});
}
make sure that you are running
ionic cordova run browser
not
ionic serve

Splash screen make http request and pass the response to another page

What I am trying to do is when the splash screen is loading, a http request is made to the server to pull some information and pass the response to another page.
Below is the code I am working with.
import { Component } from '#angular/core';
import { Platform, LoadingController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { CacheService } from "ionic-cache/ionic-cache";
import { Apis } from './apis';
import { StayPage} from '../pages/stay/stay';
#Component({
templateUrl: 'app.html',
providers: [Apis]
})
export class MyApp {
rootPage = StayPage;
constructor(platform: Platform, cache: CacheService, public loadingCtrl: LoadingController, public Apis: Apis ) {
cache.setDefaultTTL(60 * 60);
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.Apis.types().subscribe( response => {
response.results;
StatusBar.styleDefault();
Splashscreen.hide();
}, err => {
this.Apis.error( err );
});
});
}
}
When I run the above code, the splash screen is stuck on loading and doesn't move to another page.
You need to make HTTP request in constructor or ngOnInit of StayPage.
export class StayPage implements OnInit {
...
constructor(public navCtrl: NavController,
public navParams: NavParams
public http: Http) { }
ngOnInit(){
this.http.get(apiUrl)
.subscribe(
responseSuccess => ...
responseError => ...
}
}
}