Background Geolocation For Ionic2 - background

i'm trying to use background geolocation , i found this link :
[a link] https://www.joshmorony.com/adding-background-geolocation-t…/ .
"Geoposition is not knwon " type script error .
ionic version :2.2.1 , node version :6.10.0 , cordova version:6.5.0 .any suggestion for ionic2 geoloca
location-tracker :
import { Injectable, NgZone } from '#angular/core';
import { Geolocation,Geoposition, BackgroundGeolocation } from 'ionic-native';
import 'rxjs/add/operator/filter';
#Injectable()
export class LocationTracker {
public watch: any;
public lat: number = 0;
public lng: number = 0;
constructor(public zone: NgZone) {
}
startTracking() {
// Background Tracking
let config = {
desiredAccuracy: 0,
stationaryRadius: 20,
distanceFilter: 10,
debug: true,
interval: 2000
};
BackgroundGeolocation.configure((location) => {
console.log('BackgroundGeolocation: ' + location.latitude + ',' + location.longitude);
// Run update inside of Angular's zone
this.zone.run(() => {
this.lat = location.latitude;
this.lng = location.longitude;
});
}, (err) => {
console.log(err);
}, config);
// Turn ON the background-geolocation system.
BackgroundGeolocation.start();
// Foreground Tracking
let options = {
frequency: 3000,
enableHighAccuracy: true
};
this.watch = Geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition ) => {
console.log(position);
// Run update inside of Angular's zone
this.zone.run(() => {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
});
});
}
stopTracking() {
console.log('stopTracking');
BackgroundGeolocation.finish();
this.watch.unsubscribe();
}
}
tion

Assuming that you have already run the following commands;
ionic plugin add cordova-plugin-geolocation
npm install --save #ionic-native/geolocation
ionic plugin add cordova-plugin-mauron85-background-geolocation
npm install --save #ionic-native/background-geolocation
try importing the plugins as follows:
import { BackgroundGeolocation } from '#ionic-native/background-geolocation';
import { Geolocation, Geoposition } from '#ionic-native/geolocation';

Related

React native - Expo SQLite - Unable to resolve module ../assets/terezeen.db

I installed the expo SQLite package with the expo filesystem and assets package.
I am trying to load a pre-configured database but I keep getting these errors:
Android Bundling failed 341ms
Unable to resolve module ../assets/terezeen.db from D:\Skola\Vysoka\bakala\frontend\App.js:
None of these files exist:
* terezeen.db
* ..\assets\terezeen.db\index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
23 | }
24 | await FileSystem.downloadAsync(
> 25 | Asset.fromModule(require("../assets/terezeen.db")).uri,
| ^
26 | FileSystem.documentDirectory + "SQLite/terezeen.db"
27 | );
28 | return SQLite.openDatabase("terezeen.db", "1.0");
App.js
import * as SQLite from 'expo-sqlite';
import * as FileSystem from 'expo-file-system';
import { Asset } from 'expo-asset';
async function openDb() {
if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory + "SQLite")).exists) {
await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + "SQLite");
}
await FileSystem.downloadAsync(
Asset.fromModule(require("../assets/terezeen.db")).uri,
FileSystem.documentDirectory + "SQLite/terezeen.db"
);
return SQLite.openDatabase("terezeen.db", "1.0");
}
export default function App() {
const db = openDb();
metro.config.js
const { getDefaultConfig } = require("metro-config");
module.exports = (async () => {
const {
resolver: { sourceExts, assetExts },
} = await getDefaultConfig();
return {
transformer: {
babelTransformerPath: require.resolve(
"react-native-svg-transformer"
),
},
resolver: {
assetExts: [
assetExts.filter((ext) => ext !== "svg"),
assetExts.push('db')
],
sourceExts: [...sourceExts, "svg"],
},
};
})();
react-native.config.js
module.exports = {
project: {
ios: {},
android: {}
},
assets:['./assets/fonts/'],
dependencies: {
"react-native-sqlite-storage": {
platforms: {
android: {
sourceDir:
"../node_modules/react-native-sqlite-storage/platforms/android-native",
packageImportPath: "import io.liteglue.SQLitePluginPackage;",
packageInstance: "new SQLitePluginPackage()"
}
}
}
}
}
File tree:
|assets
|--fonts
| |--font.otf <-- here is the method
|--terezeen.db
|
|src
|--assets <- just for case of the problem
|--fonts
|--font.otf
|--terezeen.db
|
|App.js <- file that calls the sqlite
After the installation of those expo packages I am also disallowed to use custom font because now it won't find it.
I have edited the metro.config.js like this:
const { getDefaultConfig } = require('expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('db');
module.exports = defaultConfig;
Also, I thought that the directory of the database should be linked with android, so instead of linking it in the root directory I was linking it with the android directory.
Now the code looks like this:
async function openDb() {
if (!(await FileSystem.getInfoAsync(FileSystem.documentDirectory + "SQLite")).exists) {
await FileSystem.makeDirectoryAsync(FileSystem.documentDirectory + "SQLite");
}
await FileSystem.downloadAsync(
Asset.fromModule(require("./src/assets/terezeen.db")).uri,
FileSystem.documentDirectory + "SQLite/terezeen.db"
);
return SQLite.openDatabase("terezeen.db", "1.0");
}
export default function App() {
const db = openDb();

vue3 testing library - How to use globalProperties in tests

I am new to Vue and followed the recommendation to use vue testing library. The only issue is I can't seem to find a way to inject my code into globalProperties in render function.
Does anyone know of an example where I can inject or mock it out?
main.js
app.config.globalProperties.$globals = globalMethods
...
const app = createApp(App)
app.config.globalProperties.$globals = globalMethods
app.config.globalProperties.$globalVars = globalVars
app.component("font-awesome-icon", fontawesome)
app.use(applicationStore);
app.use (Hotjar, hotjarConfig)
app.use(i18n)
app.use(router)
app.mount('#app')
From my vue component in create I am able to call
Component.vue
let formatedObj = this.$globals.maskValues(this.inputValue, this.inputType, this);
...
,
created() {
let formatedObj = this.$globals.maskValues(this.inputValue, this.inputType, this);
this.myInputValue = formatedObj.formatedString;
this.formatedCharacterCount = formatedObj.formatedCharacterCount;
this.prevValue = this.myInputValue;
},
...
tesst.spec.js
import { render } from '#testing-library/vue'
import FormatedNumericInput from '#/components/Component.vue'
import {globalMethods} from'#/config/global-methods'
const label = 'Price'
const initSettings = {
props: {
inputId: 'testInputId1',
labelTxt: label
}
};
beforeEach(() => {
});
test('a simple string that defines your test', () => {
const { getByLabelText } = render(FormatedNumericInput, initSettings)
const input = getByLabelText(label)
// testing logic
expect(input != null).toBe(true)
expect(FormatedNumericInput != null).toBe(true)
})
** ERROR **
TypeError: Cannot read property 'maskValues' of undefined
85 | },
86 | created() {
> 87 | let formatedObj = this.$globals.maskValues(this.inputValue, this.inputType, this);
| ^
88 | this.myInputValue = formatedObj.formatedString;
89 | this.formatedCharacterCount = formatedObj.formatedCharacterCount;
90 | this.prevValue = this.myInputValue;
at Proxy.created (src/components/FormatedNumericInput.vue:87:37)
The second argument of render() is passed to #vue/test-utils mount(), so you could include the global.mocks mounting option to mock $globals.maskValues:
const { getByLabelText } = render(FormatedNumericInput, {
...initSettings,
global: {
mocks: {
$globals: {
maskValues: (inputValue, inputType) => {
const formatedString = globalFormatValue(inputValue) // declared elsewhere
return {
formatedString,
formatedCharacterCount: formatedString.length,
}
}
}
}
}
})
This is my solution in actual Vue3/Vite/Vitest environment, I set some mocks globally, so I don't need to in every test suite.
// vitest.config.ts
import { mergeConfig } from 'vite';
import { defineConfig } from 'vitest/config';
import viteConfig from './vite.config';
export default defineConfig(
mergeConfig(viteConfig, { // extending app vite config
test: {
setupFiles: ['tests/unit.setup.ts'],
environment: 'jsdom',
}
})
);
// tests/unit.setup.ts
import { config } from "#vue/test-utils"
config.global.mocks = {
$t: tKey => tKey; // just return translation key
};
so for you it will be something like
config.global.mocks = {
$globals: {
maskValues: (inputValue, inputType) => {
// ...implementation
return {
formatedString,
formatedCharacterCount,
}
}
}
}

How to parse serverless.yml file in script

I need to read the serverless.yml config for use in some test mocks.
The following worked until a recent change:
const serverless = new Serverless()
await serverless.init()
const service = await serverless.variables.populateService()
How does one read the file now? There is an astounding lack of documentation in regards to using serverless progamically.
Well I ended up taking some code from the AppSync emulator package. I am not sure it covers it does a full parsing but it does the job for me.
import Serverless from 'serverless'
import path from 'path'
import fs from 'fs'
class ConfigServerless extends Serverless {
async getConfig(servicePath) {
this.processedInput = {
commands: [],
options: { stage: 'dev' }
}
this.config.servicePath = servicePath
this.pluginManager.setCliOptions(this.processedInput.options)
this.pluginManager.setCliCommands(this.processedInput.commands)
await this.service.load(this.processedInput)
this.pluginManager.validateCommand(this.processedInput.commands)
return this.variables
.populateService(this.pluginManager.cliOptions)
.then(() => {
this.service.mergeArrays()
this.service.setFunctionNames(this.processedInput.options)
this.service.validate()
})
}
}
const normalizeResources = config => {
if (!config.resources) {
return config.resources
}
if (!config.resources.Resources) {
return {}
}
if (!Array.isArray(config.resources.Resources)) {
return config.resources
}
const newResources = config.resources.Resources.reduce(
(sum, { Resources, Outputs = {} }) => ({
...sum,
...Resources,
Outputs: {
...(sum.Outputs || {}),
...Outputs
}
}),
{}
)
return {
Resources: newResources
}
}
export async function loadServerlessConfig(cwd = process.cwd()) {
const stat = fs.statSync(cwd)
if (!stat.isDirectory()) {
cwd = path.dirname(cwd)
}
const serverless = new ConfigServerless()
await serverless.getConfig(cwd)
const { service: config } = serverless
const { custom = {} } = config
const output = {
...config,
custom: {
...custom
},
resources: normalizeResources(config)
}
return output
}

ionic v3 native camera plugin didn't work on android

using ionic cordova plugin didn't work on open camera or gallery on android
Ionic:
ionic (Ionic CLI) : 4.12.0
Ionic Framework : ionic-angular 3.9.2
#ionic/app-scripts : not installed
Cordova:
cordova (Cordova CLI) : 8.1.2 (cordova-lib#8.1.1)
System:
NodeJS : v10.15.3
npm : 6.9.0
OS : Windows 10
takePicture() {
const options: CameraOptions = {
quality: 75,
destinationType: this.camera.DestinationType.NATIVE_URI ,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.CAMERA,
allowEdit: true,
correctOrientation: true,
targetWidth: 300,
targetHeight: 300,
saveToPhotoAlbum: true
}
alert("1");
this.camera.getPicture(options).then(imageData => {
let base64Image = 'data:image/jpeg;base64,' + imageData;
this.image = base64Image;
alert("done");
}, error => {
// Utils.showToast( null,JSON.stringify(error));
});
}
u're missing the most important step,
Make sure you introduce a camera in providers in app.module.ts
u should create a PictureProvider file like this
import { Injectable } from '#angular/core';
import { Defer } from '../../common/Defer';
import { Camera } from '#ionic-native/camera';
export enum PictureSource {
PhotoLibrary,
Camera,
Local,
Remote,
}
#Injectable()
export class PictureProvider {
constructor(private camera: Camera, ) {
console.log('Hello PictureProvider Provider');
}
fromCamera(source: PictureSource, options?, ) {
let mergedOtions = this.getOptions(source, options);
if (options)
for (let k in options)
mergedOtions[k] = options[k];
let defer = Defer.create();
navigator['camera'].getPicture(
imageUri => defer.resolve(imageUri),
(message: string) => {
console.log(message);
defer.reject();
},
mergedOtions,
);
return defer.promise;
}
private getOptions(source, options?) {
return {
sourceType: source == PictureSource.PhotoLibrary ? this.camera.PictureSourceType.PHOTOLIBRARY : this.camera.PictureSourceType.CAMERA,
destinationType: this.camera.DestinationType.NATIVE_URI,
quality: 50,
mediaType: this.camera.MediaType.PICTURE,
allowEdit: options.allowEdit,
correctOrientation: true,
targetWidth: options.targetWidth,
targetHeight: options.targetHeight
}
}
}
Execute as needed
this.picture.fromCamera(1, {
allowEdit: true,
targetWidth: 256,
targetHeight: 256,
destinationType: this.camera.DestinationType.DATA_URL, //直接返回base64
}).then(base64Img => {
this.headImg = this.encodeBase64Img(base64Img);
}).catch(Defer.NoOP);

Is there a location settings change listener for react native?

I am trying figure out how to listen to event when the user turns on or off the location in the settings. I tried navigator.geolocation.watchposition but didn't have much success, since it does not listen to the respective event.
npm install --save react-native-location
react-native link
var React = require('react-native');
var { DeviceEventEmitter } = React;
var { RNLocation: Location } = require('NativeModules');
Location.getAuthorizationStatus(function(authorization) {
//authorization is a string which is either "authorizedAlways",
//"authorizedWhenInUse", "denied", "notDetermined" or "restricted"
});
Location.requestAlwaysAuthorization();
Location.startUpdatingLocation();
Location.setDistanceFilter(5.0);
var subscription = DeviceEventEmitter.addListener(
'locationUpdated',
(location) => {
/* Example location returned
{
coords: {
speed: -1,
longitude: -0.1337,
latitude: 51.50998,
accuracy: 5,
heading: -1,
altitude: 0,
altitudeAccuracy: -1
},
timestamp: 1446007304457.029
}
*/
}
);
Refer to this site for more details.
You can use https://www.npmjs.com/package/react-native-system-setting
useEffect(() => {
const locationListener = SystemSetting.addLocationListener(
(locationEnabled) => console.log(locationEnabled),
);
return () => SystemSetting.removeListener(locationListener);
}, []);