ionic2: network connectivity check during splash screen - ionic2

I've been trying hard to figure out how to check for network connectivity while the splashscreen is being displayed.I've searched for the code in many places but most of those articles are outdated.
I followed the tutorial that's mentioned here:https://www.thepolyglotdeveloper.com/2016/01/determine-network-availability-in-an-ionic-2-mobile-app/
But then I found out that Network.connection is deprecated and has been replaced by Network.type on the ionic2 website.
So I've replaced the word connection with Network.type everywhere.
So I checked out the ionic2 website and found this code which I included in the home.ts file.
import {Network} from 'ionic-native';
checkConnection() {
//console.log("entrou");
//console.log(Network);
let disconnectSubscription = Network.onDisconnect().subscribe(() => {
console.log('network was disconnected :-( ')
});
disconnectSubscription.unsubscribe();
console.log("watch network");
console.log("Conexao" + Network.type);
let connectSubscription = Network.onConnect().subscribe(() => {
console.log('network connected!');
setTimeout(() => {
console.log('network status');
console.log(Network.type);
if (Network.type === 'WIFI') {
console.log('we got a wifi connection, woohoo!');
}
}, 3000);
});
console.log("Sub" + connectSubscription);
connectSubscription.unsubscribe();
}
here is my home.html file
`<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button ion-buttton (click)="checkConnection()">Check Network</button>
</ion-content>`
I tried implementing the same code but doesn't work.
I want to know what is the exact code that I can use ?
What is that I need to import to use this code if it is the right one?
Also I want to know how to run it during the splashscreen ?
On the console I found these errors
"Native: tried calling Network.type, but the Network plugin is not installed.
Network plugin: 'ionic plugin add cordova-plugin-network-information'
But i've already installed the required plugin following that above command.I also installed "npm install ionic-native".
I reinstalled them on seeing this error but this still persists.

In your config.xml add the following:
<preference name="AutoHideSplashScreen" value="false" />
This will make the SplashScreen stay visible until you manually hide it.
Then in your app.component.ts do the following:
constructor(private platform: Platform) {
platform.ready().then(() => {
// Check the network stuff here and do what you need to do
if (Network.type == 'WIFI') console.log('We are on WIFI!');
else console.log('We aren't on WIFI');
// then hide the splash screen manually
SplashScreen.hide();
});
}

hi, make sure you have ionic-native to the latest version:
https://github.com/driftyco/ionic-native/blob/master/CHANGELOG.md
please see this for implementation:
https://forum.ionicframework.com/t/using-ionic-2-rc-4-native-network/75715/4
there is another problem associated with this , where on disconnect fires twice rather than only once:
IONIC 2 native Network.onDisconnect() running code twice
I hope this helps.... besides there is no need to check during splashscreen.... make a provider for check network status, and then call your new provider/service in app.component.ts
Oh and dont pay attention to the message:Native: tried calling Network.type, but the Network plugin is not installed.
Just make sure you have added it correctly: ionic plugin add cordova-plugin-network-information --save

reference from this -
https://ionicframework.com/docs/native/network/
install :
$ ionic cordova plugin add cordova-plugin-network-information
$ npm install --save #ionic-native/network
and put this code in app.component.ts
import { Network } from '#ionic-native/network';
constructor(private network: Network) { }
// watch network for a disconnect
let disconnectSubscription =
this.network.onDisconnect().subscribe(() => {
console.log('network was disconnected :-(');
});
// stop disconnect watch
disconnectSubscription.unsubscribe();
// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() =>
{
console.log('network connected!');
// We just got a connection but we need to wait briefly
// before we determine the connection type. Might need to wait.
// prior to doing any api requests as well.
setTimeout(() => {
if (this.network.type === 'wifi') {
console.log('we got a wifi connection, woohoo!');
}
}, 3000);
});
// stop connect watch
connectSubscription.unsubscribe();
and add code in to app.module.ts
import { Network } from '#ionic-native/network';
...
#NgModule({
...
providers: [
...
Network
...
]
...
})
export class AppModule { }`
Hope this will helpful.

Related

Expo - SplashScreen freezes in production with 'eas build' but with 'expo build' it works correctly

Here is the problem. SplashScreen freezes in production with eas build but with expo build it works correctly.
I have not had any problems locally and also not with eas build.
In production, with eas build, the SplashScreen is rendered and hidden without problems when the application starts, then the LogIn screen is rendered. Afterwards, when logging in indeed, the SplashScreen appears (I don't know why) and gets stuck there.
This is the App.js file. I think the problem is not here, because the initial SplashScreen is hidden when the LogIn screen is rendered.
SplashScreen.preventAutoHideAsync()
const App: FC = () => {
const [appIsReady, setAppIsReady] = useState(false)
useEffect(() => {
async function prepare() {
try {
await getFonts()
await setTokenFromStorage()
} catch (e) {
console.warn(e)
} finally {
setAppIsReady(true)
}
}
prepare()
}, [])
const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
await SplashScreen.hideAsync()
}
}, [appIsReady])
useEffect(() => {
if (appIsReady) onLayoutRootView()
}, [appIsReady])
return appIsReady ? (
<Provider store={store}>
<ContextProvider>
<AppNavigator />
<Toast config={toastConfig} />
</ContextProvider>
</Provider>
) : null
}
export default App
I don't really know what files I should look at to inspect the problem, but I also don't understand why the app behavior is correct when I build with expo build but not with eas build.
Testing before the build!
In order not to waste your time, Use this cmd expo start --no-dev --minify to see if your production bundle would work as charm.
Good luck!
Well, this issue was fixed when I updated the SDK version to 47.
Check out the release of Expo SDK 47 here https://blog.expo.dev/expo-sdk-47-a0f6f5c038af, and upgrade your app.

"__zone_symbol_currentTask":{"type":"microTask","state":"notScheduled","source":"Promise.then","zone":"angular","cancelFn":null,"runCount":0}}

I am getting this error
"__zone_symbol_currentTask":{"type":"microTask","state":"notScheduled","source":"Promise.then","zone":"angular","cancelFn":null,"runCount":0}}
while login facebook from my hybrid application. I have used
ng2-cordova-oauth
plugin to achieve facebook login. My code look like.
import { Component } from '#angular/core';
import {IonicPage, NavController, Platform} from 'ionic-angular';
import {OauthCordova} from '../../../node_modules/ng2-cordova-oauth/platform/cordova';
import {Facebook} from '../../../node_modules/ng2-cordova-oauth/core';
#IonicPage()
#Component({
selector: 'page-facebook',
templateUrl: 'facebook.html',
})
export class FacebookPage {
public oauth: OauthCordova;
private provider: Facebook;
public constructor(public navCtrl: NavController, private platform: Platform) {
this.oauth = new OauthCordova();
this.provider = new Facebook({
clientId: "1807864452579635",
appScope: ['id','story','picture','link','type','full_picture','message']
});
}
public login() {
this.platform.ready().then(() => {
this.oauth.logInVia(this.provider).then((success) => {
alert(JSON.stringify(success));
}, (error) => {
console.log(JSON.stringify(error));
});
});
}
}
I ran into this on a project I was working on too. The problem turned out to be that the ng2-cordova-oauth dependencies weren't installed. Specifically we had to run:
cordova plugin add cordova-plugin-inappbrowser
cordova plugin add cordova-plugin-whitelist
cordova prepare
You may also have to whitelist your site using the information found at https://github.com/apache/cordova-plugin-whitelist
Edit: You can't use ng2-cordova-oauth from the browser. You have to use a device or a simulator.
note that it is unlikely for anyone to see the original error in this code since it in part depends on external dependencies
You can use
JSON.stringify(error,Object.getOwnPropertyNames(e));
to get a clear description of the error you getting, because The __zone_symbol_currentTask is a property inserted into the Error object by Angular and JSON.stringify does not output the Error object's own properties (by default)
see also: Is it not possible to stringify an Error using JSON.stringify?

Ionic 2: Loading screen does not get dismissed

I have an application made with Ionic 2, The work flow is like this
Case A . When user is using app for the first time
User Logs in (loading is shown)
When successfully logged in loading window is hidden and user is forwarded to Dashboard page.
In dashboard page items are loaded via ajax request.
Case B. When user is already logged in before
The first screen is Dashboard and items are loaded via ajax request.
Problem
In case A, when user logs in and forwarded to DashboardPage, the loading screen doesn't gets dismissed. Sometimes it gets dismissed but most of the time it doesnot? Is this an ionic bug or am I doing something wrong??
Here is my DashboardPage
//imports here
export class DashboardPage {
public loadingmsg: any;
public ajaxRequest: any;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private webservice: WebService,
private loadingCtrl: LoadingController
)
{
this.loadDashboardContents();
}
loadDashboardContents(){
//other codes
this.loadingmsg = this.loadingCtrl.create({
content:"Loading contents, please wait..."
});
this.loadingmsg.present();
this.ajaxRequest = this.webservice.getDashboardContents(params).subscribe(data => {
this.loadingmsg.dismiss().then(()=>{
//other codes to save retrieved data to localstorage.
});
});
}
}
UPDATE
The login method from login page
loginUser(){
this.loading=this.loadingctrl.create({
content:"Logging in, please wait..."
});
this.loading.present();
this.ajaxRequest = this.webservice.loginUser(params).subscribe(data => {
this.loading.dismiss();
if(data.status =="ok"){
this.navctrl.push(DashboardPage).then(()=>{
const index = this.viewCtrl.index;
this.navctrl.remove(index);
});
}else{
//show error alert
}
}, err =>{
this.loading.dismiss();
});
}
My Ionic and cordova version information
Ionic Framework: 3.5.0
Ionic App Scripts: 1.3.9
Angular Core: 4.1.3
Angular Compiler CLI: 4.1.3
Node: 6.10.3
OS Platform: Windows 10
Cordova Version: 6.5.0
I am currently using loading in my project and it works well in all case. To ensure loading will always dismiss you need to add some code:
1. duration, dismissOnPageChange
let loading = this.loadingCtrl.create({
content: "",
duration: 5000, //ms
dismissOnPageChange: true
})
2. dissmis when ajax call success or error:
.subscribe(success=>{
//some code
loading.dismiss();
},error=>{
//some code
loading.dismiss();
})
It may be due to the this reference inside your subscribe method. I would try declaring loadingmsg locally and removing this.
loadDashboardContents(){
//other codes
let loadingmsg = this.loadingCtrl.create({
content:"Loading contents, please wait..."
});
loadingmsg.present();
this.ajaxRequest = this.webservice.getDashboardContents(params).subscribe(data => {
loadingmsg.dismiss().then(()=>{
//other codes to save retrieved data to localstorage.
});
});
}

Ionic 2: How to use custom build Cordova Plugin

I'm already created cordova plugin and already used in Ionic 1, its worked. Then I tried to use it in Ionic 2 but I don't really know how to call that plugin. I follow the step from here to create my own plugin. And this is what i did:
plugin.xml
<name>myPlugin</name>
<js-module src="www/myPlugin.js" name="myPlugin">
<clobbers target="myPlugin" />
</js-module>
myPlugin.js
module.exports = {
myFunction: function (success, failure) {
cordova.exec(success, failure, "myPlugin", "myFunction", []);
}
};
hello-ionic.ts
import { Component } from '#angular/core';
declare var cordova: any;
#Component({
selector: 'page-hello-ionic',
templateUrl: 'hello-ionic.html'
})
export class HelloIonicPage {
constructor() {
}
click() {
if (typeof cordova !== 'undefined') {
cordova.plugins.myPlugin.myFunction();
}
}
}
But unfortunately it return me an error "Undefined myFunction" in hello-ionic.ts.
Here is what I did.
hello-ionic.ts
import { Component } from '#angular/core';
declare var myPlugin: any;
#Component({
selector: 'page-hello-ionic',
templateUrl: 'hello-ionic.html'
})
export class HelloIonicPage {
constructor() {
}
click() {
myPlugin.myFuntion(
(data) => {
console.log(data);
},
(err) => {
console.log(err);
});
}
}
declare var myPlugin: any; , myPlugin name I get from <clobbers target="myPlugin" />.
Note: Need to run the project in device only.
Following tutorial is a good resource to learn how to create custom cordova plugin :
https://taco.visualstudio.com/en-us/docs/createplugintutorial/
I have followed this tutorial to create multiple custom plugins and those are working fine in Ionic2.
One more thing to point out that the tutorial has not mentioned that:
You have to add your custom plugin in your ionic 2 project using following command:
ionic plugin add "folder path of your custom plugin"
Updated:
In your plugin.xml file, you have set "myPlugin" as target in clobbers tag.
So you should call your function as followed
window.myPlugin.myFunction();
Tip: Whenever you use custom plugin created by you(or someone else), inspect the application using Chrome Developer tools. In console tab of developer tools, you can inspect the window and other available objects and can find out correct way to call plugin's methods.

Deeplink in Ionic 2 is not working

I am trying deeplinks with ionic 2 according to the procedure explained here, https://ionicframework.com/docs/v2/native/ionic-deeplinks/
First I added the plugin using,
ionic plugin add ionic-plugin-deeplinks --variable URL_SCHEME=http --variable DEEPLINK_HOST=cityknots.com
Then in my app.component.ts
export class MyApp {
rootPage = Wrapper;
constructor(platform:Platform) {
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.
StatusBar.styleDefault();
Deeplinks.route({
'/test': UserHome
}).subscribe((match) => {
console.log('Successfully routed', match);
}, (nomatch) => {
console.warn('Unmatched Route', nomatch);
});
});
}
}
I try to hit the url (http://cityknots.com/test in the ios simulator's browser (safari) after i've built and run the app, but nothing is happening. I expect the app should be launched and navigate to UserHome component. There is nothing in the console too related to this.