Showing posts with label Ionic. Show all posts
Showing posts with label Ionic. Show all posts

Friday, 30 October 2020

How can i fill color between 4 lines in canvas?

I am trying to fill color between lines in ionic. I want fill color between line when four line touch each other. For that i created a canvas demo with touch event.

html file:

 <canvas #canvasDraw width="300" height="300" (touchstart)="handleTouchStart($event)"
        (touchmove)="handleTouchmove($event)" 
        (touchend)="handleTouchEnd($event)">
        You need a browser that supports HTML5!
 </canvas>

ts file:

import { Component, ElementRef, ViewChild } from '@angular/core';

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss'],
})
export class HomePage {
    @ViewChild('canvasDraw', { static: false }) canvas: ElementRef;

    canvasElement: any;
    lines: any[];
    isDown: boolean = false;
    startX: number;
    startY: number;
    nearest: any;
    offsetX: any;
    offsetY: any;

    constructor() {
    }

    ngAfterViewInit() {
        this.canvasElement = this.canvas.nativeElement;
        this.lines = [];
        this.lines.push({ x0: 75, y0: 25, x1: 125, y1: 25 });
        this.lines.push({ x0: 75, y0: 100, x1: 125, y1: 100 });
        this.lines.push({ x0: 50, y0: 35, x1: 50, y1: 85 });
        this.lines.push({ x0: 150, y0: 35, x1: 150, y1: 85 });
        this.draw();
        //this.reOffset();
        requestAnimationFrame(() => {
            this.reOffset()
        })
    }

    reOffset() {
        let BB = this.canvasElement.getBoundingClientRect();
        this.offsetX = BB.left;
        this.offsetY = BB.top;
    }

    // select the this.nearest line to the mouse
    closestLine(mx, my) {
        let dist = 100000000;
        let index, pt;
        for (let i = 0; i < this.lines.length; i++) {
            //
            let xy = this.closestXY(this.lines[i], mx, my);
            //
            let dx = mx - xy.x;
            let dy = my - xy.y;
            let thisDist = dx * dx + dy * dy;
            if (thisDist < dist) {
                dist = thisDist;
                pt = xy;
                index = i;
            }
        }
        let line = this.lines[index];
        return ({ pt: pt, line: line, originalLine: { x0: line.x0, y0: line.y0, x1: line.x1, y1: line.y1 } });
    }

    // linear interpolation -- needed in setClosestLine()
    lerp(a, b, x) {
        return (a + x * (b - a));
    }

    // find closest XY on line to mouse XY
    closestXY(line, mx, my) {
        let x0 = line.x0;
        let y0 = line.y0;
        let x1 = line.x1;
        let y1 = line.y1;
        let dx = x1 - x0;
        let dy = y1 - y0;
        let t = ((mx - x0) * dx + (my - y0) * dy) / (dx * dx + dy * dy);
        t = Math.max(0, Math.min(1, t));
        let x = this.lerp(x0, x1, t);
        let y = this.lerp(y0, y1, t);
        return ({ x: x, y: y });
    }

    // draw the scene
    draw() {
        let ctx = this.canvasElement.getContext('2d');
        let cw = this.canvasElement.width;
        let ch = this.canvasElement.height;
        ctx.clearRect(0, 0, cw, ch);
        // draw all lines at their current positions
        for (let i = 0; i < this.lines.length; i++) {
            this.drawLine(this.lines[i], 'black');
        }
        // draw markers if a line is being dragged
        if (this.nearest) {
            // point on line this.nearest to mouse
            ctx.beginPath();
            ctx.arc(this.nearest.pt.x, this.nearest.pt.y, 5, 0, Math.PI * 2);
            ctx.strokeStyle = 'red';
            ctx.stroke();
            // marker for original line before dragging
            this.drawLine(this.nearest.originalLine, 'red');
            // hightlight the line as its dragged
            this.drawLine(this.nearest.line, 'red');
        }        
    }

    drawLine(line, color) {
        let ctx = this.canvasElement.getContext('2d');
        ctx.beginPath();
        ctx.moveTo(line.x0, line.y0);
        ctx.lineTo(line.x1, line.y1);
        ctx.strokeStyle = color;
        ctx.stroke();
    }

    handleTouchStart(e) {
        // tell the browser we're handling this event
        let tch = e.touches[0];
        // tch.preventDefault();
        // tch.stopPropagation();
        // mouse position
        this.startX = tch.clientX - this.offsetX;
        this.startY = tch.clientY - this.offsetY;
        // find this.nearest line to mouse
        this.nearest = this.closestLine(this.startX, this.startY);
        this.draw();
        // set dragging flag
        this.isDown = true;
    }

    handleTouchEnd(e) {
        // tell the browser we're handling this event
        let tch = e.touches[0];
        // tch.preventDefault();
        // tch.stopPropagation();
        // clear dragging flag
        this.isDown = false;
        this.nearest = null;
        this.draw();
    }

    handleTouchmove(e) {
        if (!this.isDown) { return; }
        // tell the browser we're handling this event
        let tch = e.touches[0];
        // tch.preventDefault();
        // tch.stopPropagation();
        // mouse position
        const mouseX = tch.clientX - this.offsetX;
        const mouseY = tch.clientY - this.offsetY;
        // calc how far mouse has moved since last mousemove event
        let dx = mouseX - this.startX;
        let dy = mouseY - this.startY;
        this.startX = mouseX;
        this.startY = mouseY;
        // change this.nearest line vertices by distance moved
        let line = this.nearest.line;
        line.x0 += dx;
        line.y0 += dy;
        line.x1 += dx;
        line.y1 += dy;
        // redraw
        this.draw();

        let ctx = this.canvasElement.getContext('2d');
        ctx.beginPath();
        ctx.rect(line.x0, line.y0, line.x1, line.y1);
        ctx.fillStyle = "red";
        ctx.fill();
    }

}

enter image description here

How to fill color when four line touch or connect?



from How can i fill color between 4 lines in canvas?

Connect and Print in th esc/pos mobile printerusing ionic

I am thinking to develop a Android application related to connect a Bluetooth POS printer and print the same in printer ...once connected device in local starage and transaction details are stored in local db and sync to server on daily basis .. I I have limited experience in dotnet as well as angular. Is xamarin or ionic is best suited for my requirement please suggest

EDIT: i need sample solution ionic latest version application which print in the esc/pos thermal printer take the printer from Paired devices (Printer is able to auto connect to mobile)

Please any experienced in suggest me a print the simple text in pos portable printer ( For ex: https://www.tvs-e.in/mp-280-lite/)



from Connect and Print in th esc/pos mobile printerusing ionic

Monday, 26 October 2020

Navigation issue with CanDeactivate guard in Ionic 5

In my Ionic 5 application I have the following navigation path.

PageHome -> PageA ->  PageB

I have implemented CanDeactivate guard for PageA.

export class LeavePageGuard implements CanDeactivate<isDeactivatable>{
  canDeactivate(
    component: isDeactivatable
  ): Observable<boolean> | Promise<boolean> | boolean {
    return component.canPageLeave();
  }
}

When user edit something and press back button before saving I am raising a popup to confirm if user wants to leave.

  async canPageLeave() {

    if (this.byPassNav) {
      this.byPassNav = false;
      return true;
    }
    if (JSON.stringify(this.dataOld) != JSON.stringify(this.data)) {

      const alert = await this.alertCtrl.create({
        header: 'Unsaved Chnages',
        message: 'Do you want to leave?',
        buttons: [
          {
            text: 'No',
            role: 'cancel',
            handler: () => { }
          },
          {
            text: 'Yes'),
            role: 'goBack',
            handler: () => { }
          }
        ]
      });
      await alert.present();
      let data = await alert.onDidDismiss();
      if (data.role == 'goBack') {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  }

To move forward to PageB I am using a boolean byPassNav. I am setting this value to TRUE before moving forward and the method canPageLeave is returning TRUE.

The forward navigation is not working in one scenario except the following.

on PageA change some data and click on back button -> Confirmation pop up will open -> Select No -> Confirmation pop up will close and the same page remains open. Select button to move forward to PageB.

This will move the navigation to pageB but also will make the page as Root Page and remove all route history. I can't go back from PageB after this flow.



from Navigation issue with CanDeactivate guard in Ionic 5

Tuesday, 20 October 2020

Time format change according to time settings of phone in ionic5 angular9

I need to parse the time according to the phone settings(both android and IOS). If I select 24 hours in the device, need to show the 24 hour date in application and for the 12 hours selection, need to show the 12 hour time format in application. How can I find which time format is I selected in the device through the code.



from Time format change according to time settings of phone in ionic5 angular9

Sunday, 18 October 2020

Ionic Capacitor - how to play ringtone/alarm on Android device?

I would like to know if there is a way to play Android device ringtone/alarm using Ionic Capacitor (not Cordova)?

If it is possible, please provide me with a simple solution (include required npm packages and code). If not, please tell me how to do it with a simple typescript - I do not want to do it with a Cordova.

Also, I do not want to use Capacitor Local Notifications. I want ringtone sound only.

Thank you for any help :))



from Ionic Capacitor - how to play ringtone/alarm on Android device?

Saturday, 3 October 2020

Ionic - EACCES (Permission denied) error when uploading video

I'm having some difficulties trying upload video file to server using Cordova Camera Plugin and cordova-plugin-advanced-http. The code works like a charm when uploading an image from gallery, but no matter what I do, I always receive EACCES (Permission denied) when uploading a video from gallery:

file url ->  file:///storage/emulated/0/DCIM/Camera/VID_20200908_114957.mp4
post-post-module-es2015.js:240 {status: -1, error: "There was an error with the request: /storage/emulated/0/DCIM/Camera/VID_20200908_114957.mp4: open failed: EACCES (Permission denied)"

Looking only at the error message, we can conclude it's a permission issue, so I tried use cordova-plugin-android-permissions and request READ_EXTERNAL_STORAGE permission. No success, the app has the permission but the error remains the same.

This is part of the code used to upload

private chooseContentUsingCameraPlugin(SOURCE: number) {
    const options: CameraOptions = {
        destinationType: this.camera.DestinationType.FILE_URI,
        mediaType: this.camera.MediaType.ALLMEDIA,
        sourceType: SOURCE
    };
    this.camera.getPicture(options).then((contentUrl: string) => {
        if (contentUrl.indexOf('://') === -1)
            contentUrl = 'file://' + contentUrl;
        const queryIndex = contentUrl.lastIndexOf('?');
        if (queryIndex !== -1)
            contentUrl = contentUrl.substring(0, queryIndex);
        console.log('file url -> ', contentUrl);
        this.startUpload(contentUrl);
    }, (err) => this.onUploadError(err));
}

private startUpload(fileUrl){
    ...
    this.nativeHttp.uploadFile(req.url, null, headers, fileUrl, fileName).then(res => {
        let data = res.data;
        if (res.data && (req.responseType === undefined || req.responseType === 'json'))
            data = JSON.parse(res.data);
        console.log(data)
    }).catch(error => {
        console.log(error)
    });
}

can someone explain what could be causing this issue?



from Ionic - EACCES (Permission denied) error when uploading video

Friday, 2 October 2020

Unable to set interval up to max 2 min or until condition met using angular

here what my scenario is i have 2 api's apiOne and apiTwo and when ever i call the apiOne is should give response and if the response is success then i have to send this repsonse to apiTwo as param then apiTwo will give another response in that i may get like "created" ,"in_progress" . here the issue is

  1. How can i call the apitwo using interval for every 3 seconds until i get the response as "in_progress" and if i didnt get the response as like above then i need to poll the apiTwo till max 2 min and cancel the call. if i get the response as in_progress then i need to stop the interval or max 2 min cancel the interval or subcription.

  2. I already wrote the code in nested way but it is not efficient .

below is my code

 initiate() {
    this.showProgress = true;
    
    const data = {
      id: this.id,
      info: this.Values.info,
    };

    // First Api call
    
    this.userServ.start(data).subscribe(res => {
     
      this.Ids = res['Id'];
      if (this.Ids) {
      
      
      // Second Api call
      
        this.Service.getStatus(this.Ids).subscribe(resp => {

          if (resp) {
            
            this.Status = res['Status'];
            
            // if resp is In_Progress
            
            if (this.Status === 'In_Progress') {
              this.Start();
            } else {

            // if resp is not In_Progress then i get the response i am calling the api
            
              this.intervalTimer = interval(3000).subscribe(x => {

                this.Service.Status(this.Ids).subscribe(ress => {
                 
                  this.Status = ress['Status'];
                  if (this.Status === 'In_Progress') {
                    this.delayStart();
                    this.intervalTimer.unsubscribe();
                  }
                });
              });

            }
          }

        }, err => {
          console.log(err);
        });
      }

    }, error => {
      console.log(error);
    });

  }


from Unable to set interval up to max 2 min or until condition met using angular

Tuesday, 22 September 2020

ionic serve on iOS 14 device. Error "Invalid Service"

After upgrading an iPhone6s to iOS 14 and Xcode to the latest version, I am unable to serve the app.

The error stack is as following

Error: InvalidService
    at LockdownProtocolReader.parseBody (/usr/local/lib/node_modules/native-run/node_modules/node-ioslib/dist/protocol/lockdown.js:35:19)
    at LockdownProtocolReader.onData (/usr/local/lib/node_modules/native-run/node_modules/node-ioslib/dist/protocol/protocol.js:52:40)
    at TLSSocket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:295:12)
    at readableAddChunk (_stream_readable.js:271:9)
    at TLSSocket.Readable.push (_stream_readable.js:212:10)
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:186:23)

running with --verbose shows the origin of the error

client:lockdownd startService: com.apple.debugserver +898ms
  protocol:lockdown socket write: {"Request":"StartService","Service":"com.apple.debugserver"} +206ms
  protocol:lockdown Response: {"Error":"InvalidService","Request":"StartService","Service":"com.apple.debugserver"} +6ms
  native-run Caught fatal error: Error: InvalidService

my serve script is

ionic cordova run iOS --l --debug --device --address=0.0.0.0 --sourceMap=true

Ionic info:

Ionic:

   Ionic CLI                     : 6.11.8 (/usr/local/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.2.2
   @angular-devkit/build-angular : 0.900.7
   @angular-devkit/schematics    : 9.1.4
   @angular/cli                  : 9.1.4
   @ionic/angular-toolkit        : 2.2.0

Cordova:

   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : ios 5.1.1
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.2.1, (and 20 other plugins)

Utility:

   cordova-res                          : not installed
   native-run (update available: 1.1.0) : 1.0.0

System:

   ios-deploy : 1.10.0
   ios-sim    : 8.0.2
   NodeJS     : v12.18.0 (/usr/local/bin/node)
   npm        : 6.14.5
   OS         : macOS Catalina
   Xcode      : Xcode 12.0 Build version 12A7209

what I have tried so far.

  • reboot Mac
  • reboot iPhone
  • make sure latest iOS/Mac/Xcode version is installed
  • clean build

running on emulator is working fine btw. I can also perform ionic build and run via Xcode on the device.



from ionic serve on iOS 14 device. Error "Invalid Service"

Saturday, 19 September 2020

applied CSS rule for opacity is different from the computed styles

I'm inspecting https://ionicframework.com/docs/api/alert alert..

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Alert</title>
  <script type="module" src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.esm.js"></script>
  <script nomodule src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ionic/core/css/ionic.bundle.css"/>
  <style>
    :root {
      --ion-safe-area-top: 20px;
      --ion-safe-area-bottom: 22px;
    }
  </style>
  <script type="module">
    import { alertController } from 'https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/index.esm.js';
    window.alertController = alertController;
  </script>
</head>
<body>
  <ion-app>
    <ion-header translucent>
      <ion-toolbar>
        <ion-title>Alert</ion-title>
      </ion-toolbar>
    </ion-header>,
    <ion-content fullscreen class="ion-padding">
      <ion-alert-controller></ion-alert-controller>
      <ion-button expand="block">Show Alert</ion-button>
    </ion-content>
  </ion-app>

  <script>
    const button = document.querySelector('ion-button');
    button.addEventListener('click', handleButtonClick);

    async function handleButtonClick() {
      const alert = await alertController.create({
        header: 'Use this lightsaber?',
        message: 'Do you agree to use this lightsaber to do good across the galaxy?',
        buttons: ['Disagree', 'Agree']
      });

      await alert.present();
    }
  </script>
</body>
</html>

There is an element there with .alert-wrapper class on it.

if you'll look at the applied CSS, it will show you opacity: 0, but the computed shows opacity: 1 the element i'm inspecting

applied css

computed styles

I tried removing all the CSS Files from the page, all the javascript, all the other elements I tried to move this element to the body (outside the iframe) and applying the opacity: 0 in the styles, nothing helps, the computed stays opacity: 1..

How is this possible?



from applied CSS rule for opacity is different from the computed styles

Monday, 14 September 2020

Angular Reactive Forms: How to display an error+red border?

I'm starting to use Angular Reactive Forms.

I really like the idea of being able to have async validator(for things that have to check something against the DB), and I like the idea that the GUI doesn't need to know every rule.

So I've a dummy login form:

  loginForm = this.formBuilder.group({
    email: new FormControl(
      '',
        Validators.compose([Validators.required, 
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')])
    ),
    password: new FormControl(
      '',
      Validators.compose([Validators.required, Validators.minLength(8)]
    )),
  });

and the matching view:

       <form class="ion-margin" [formGroup]="loginForm" (ngSubmit)="login()">
        <ion-item lines="none">
          <ion-label position="floating">Email</ion-label>
          <ion-input type="text" formControlName="email"></ion-input>
        </ion-item>

        <ion-item lines="none">
          <ion-label position="floating">Password</ion-label>
          <ion-input type="password"  formControlName="password"></ion-input>
        </ion-item>

        <ion-row class="ion-margin">
          <ion-button type="submit" color="success" expand="block" [disabled]="loginForm.dirty && !loginForm.valid">Sign in</ion-button>
        </ion-row>
      </form>

Currently, I've no visual clue why the user cannot submit the form. Previously I was doing some ASP.Net Core projects, and there was the same kind of approach to have the model and its validations rules declared on the ViewModel/Controller side.

  1. I was kind of expecting that since the ion-input knows its form control name, it would at least be possible to automatically add some kind of red border if the validation fails. Is it normal? Did I miss something?
  2. Is there a way to provide the error message from the .ts file? I mean, it's kind of weird that the ViewModel AND the View has to know about each error(and its parameters(like minlength)) Would it not be the responsability of the Validator to provide an error if one?
  3. What if I've some global errors(like, the combination of username-password is invalid, can I use the form to give this information, or should I manage this elsewhere?

Sorry for the 3 questions in one, but it was with the same example and very close.



from Angular Reactive Forms: How to display an error+red border?

Sunday, 23 August 2020

Cordova ionic 1 visual studio build failed

I am new to mobile development, trying to build blank ionic android app on visual studio 2015. However, getting below error:

1>MSBUILD : cordova-build error : Syntax Error: C:\Users\{username}\AppData\Roaming\npm\node_modules\vs-tac\node_modules\cordova\6.2.0\node_modules\cordova\node_modules\cordova-lib\node_modules\request\node_modules\tough-cookie\lib\cookie.js:32

1>  SyntaxError C:\Users\{username}\AppData\Roaming\npm\node_modules\vs-tac\node_modules\cordova\6.2.0\node_modules\cordova\node_modules\cordovalib\node_modules\request\node_modules\tough-cookie\lib\cookie.js:32

1>MSBUILD : cordova-build error : const punycode = require("punycode");

1>  const punycode = require("punycode");

1>MSBUILD : cordova-build error : ^^^^^


1>MSBUILD : cordova-build error : Use of const in strict mode.


1>  Use of const in strict mode.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


from Cordova ionic 1 visual studio build failed

Saturday, 18 January 2020

Last column jumping to the next row in ion-grid Ionic 4

I am trying to create a footer with 5 buttons/icons. Actually I am trying to replicate a tab, but without using that function. There is enough space to fit the 5 icons with teir label, however, for some reason in Android the last icon is jumping to the next row. I have been trying to play with the width and sizes but I could not obtain the desired result.

Any suggestion?

Long story short: I want that in Android the footer will be displayed as in Ios

Thanks

Ios vs Android view

<ion-footer>
 <ion-toolbar color="light">
  <ion-grid>
   <ion-row> 

    <ion-col>  
      <ion-tab-button >
        <ion-icon src="/assets/couple_on.svg"></ion-icon>
        <ion-label>Info</ion-label>
      </ion-tab-button>
    </ion-col> 

    <ion-col>  
      <ion-tab-button >
        <ion-icon src="/assets/rings_off.svg"></ion-icon>
        <ion-label>Donde</ion-label>
      </ion-tab-button>
    </ion-col> 

    <ion-col>  
      <ion-tab-button >
        <ion-icon src="/assets/church_off.svg"></ion-icon>
        <ion-label>Inicio</ion-label>
      </ion-tab-button>
    </ion-col> 

    <ion-col>
      <ion-tab-button >
        <ion-icon src="/assets/cake_off.svg"></ion-icon>
        <ion-label>Programa</ion-label>
      </ion-tab-button>
    </ion-col>

    <ion-col>
      <ion-tab-button >
        <ion-icon src="/assets/camera_off.svg"></ion-icon>
        <ion-label>Fotos</ion-label>
      </ion-tab-button>
     </ion-col>        
    </ion-row>
   </ion-grid>
  </ion-toolbar>
 </ion-footer>

Edit: When I translated to russian (longer words), and using the nowrap, the last icon was going away from the screen. I tried to reduce the size of the label, but still is not centered. Its annoying because I now it fits, as its seen in Ios:

enter image description here



from Last column jumping to the next row in ion-grid Ionic 4

Wednesday, 15 January 2020

Why Does AdMob Free Crash My App in the iOS Simulator?

I'm trying to add adMobFree to a brand New Ionic 4 project.

I've tried doing this over and over, using different methods and following different tutorials and the result is always the same: the app refuses to run in the iOS Simulator. It just stops at the splash screen.

installation steps

ionic cordova platform add ios
ionic cordova platform add android

ionic cordova plugin add cordova-plugin-admob-free --save --variable ADMOB_APP_ID="ca-app-pub-12345678901234567890"
npm install @ionic-native/admob-free

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { AdMobFree } from '@ionic-native/admob-free/ngx';

@NgModule({
    declarations: [AppComponent],
    entryComponents: [],
    imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
    providers: [
        StatusBar,
        SplashScreen,
        AdMobFree,
        { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

ads.service.ts

import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { AdMobFree, AdMobFreeBannerConfig } from '@ionic-native/admob-free/ngx';

@Injectable({
    providedIn: 'root'
})
export class AdsService {

    bannerId: 'ca-app-pub-12345678901234567890';

    constructor(
        public platform: Platform,
        private admobFree: AdMobFree
    ) { }

    showBanner() {
        this.platform
            .ready()
            .then(() => {
                const bannerConfig: AdMobFreeBannerConfig = {
                    id: this.bannerId,
                    isTesting: false,
                    autoShow: false
                };
                this.admobFree.banner.config(bannerConfig);
                this.admobFree.banner
                    .prepare()
                    .then(() => {
                        this.admobFree.banner.show();
                    })
                    .catch(e => console.log(e));
            })
            .catch(e => console.log(e));
    }
}

home.page.ts

import { Component } from '@angular/core';
import { AdsService } from '../services/ads.service';

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss'],
})
export class HomePage {

    constructor(
        public ads: AdsService
    ) {
        this.ads.showBanner();
    }

}

What am I doing wrong?



from Why Does AdMob Free Crash My App in the iOS Simulator?

Monday, 13 January 2020

How we can get script response methods on runtime in angular JS

I am calling a script URL in the response I need to use the response which contains a method. I need to implement that method in my code. Please suggest if anybody has the solution

I have the below URL and I calling script URL in Directive

script URL = https://botsrv.com/qb/widget/xxxxx/xxxxx

This is my Directive -

directive('demo',[ function () {
    return {
        restrict: 'A',
        link: function(scope, el , attrs) 

            var scriptElem = angular.element(document.createElement('script'));
            scriptElem.attr("src", 'https://botsrv.com/qb/widget/xxxxxx/xxxxx'); // set var appropriately
            el.append(scriptElem);

        }
    };
}])

the script having onSave method This is the method - I need the results from the onSave function in my JS Controller.

onSave: function (results) {
    console.log('onSave method ---- ' , results);
 }


from How we can get script response methods on runtime in angular JS

Sunday, 12 January 2020

ionic-native angular example code to vuejs

With the Ionic Native there is the possibility to use iBeacons via a native-plugin: https://ionicframework.com/docs/native/ibeacon

The example code is written for people that use Ionic with AngularJS, but I'm using VueJS and I cannot figure out how to get this to work:

The Angular version of the Example code:

import { IBeacon } from '@ionic-native/ibeacon/ngx';

constructor(private ibeacon: IBeacon) { }

...


// Request permission to use location on iOS
this.ibeacon.requestAlwaysAuthorization();
// create a new delegate and register it with the native layer
let delegate = this.ibeacon.Delegate();

// Subscribe to some of the delegate's event handlers
delegate.didRangeBeaconsInRegion()
  .subscribe(
    data => console.log('didRangeBeaconsInRegion: ', data),
    error => console.error()
  );
delegate.didStartMonitoringForRegion()
  .subscribe(
    data => console.log('didStartMonitoringForRegion: ', data),
    error => console.error()
  );
delegate.didEnterRegion()
  .subscribe(
    data => {
      console.log('didEnterRegion: ', data);
    }
  );

let beaconRegion = this.ibeacon.BeaconRegion('deskBeacon','F7826DA6-ASDF-ASDF-8024-BC5B71E0893E');

this.ibeacon.startMonitoringForRegion(beaconRegion)
  .then(
    () => console.log('Native layer received the request to monitoring'),
    error => console.error('Native layer failed to begin monitoring: ', error)
  );

But.. what I expected to work was the following in VueJS:

On top of my component importing it: import { IBeacon } from '@ionic-native/ibeacon/ngx';

And use it like this:

foobar() {
let _ibeacon = IBeacon.Delegate()
  alert('Hi iBeacon');
  _ibeacon.didStartMonitoringForRegion()
    .subscribe(
      data => console.log('didStartMonitoringForRegion: ', data),
      error => console.error()
    );
}

But even the alert isn't shown. What IS the correct way to use the iBeacon plugin with Vue and ionic?



from ionic-native angular example code to vuejs

Thursday, 9 January 2020

File size is 0 only for videos in Ionic on iOS 13.2 when selecting videos from Photo Library

In my Ionic3 application I am calculating file size as follows.

HTML

<div>
  <input type="file" accept="*" (change)="onSelect($event)">
  <button ion-button (click)="calcSize()">calculate size</button>
</div>
<p>Size: </p>

TS

  file: File;
  size: number;

  onSelect(event: any) {

    this.file = event.target.files[0];
  }
  calcSize() {

    this.size = this.file.size;
  }

Above code is working perfectly on all the Android devices and iOS devices below iOS 13.2.

But when selecting videos from Photo Library on iOS devices with greater than 13.2, the size is 0 only for video files.

But when selecting videos from iCloud Drive works fine.

Any help is highly appreciated.

Find issue on StackBlitz.



from File size is 0 only for videos in Ionic on iOS 13.2 when selecting videos from Photo Library

Using Vega Charts in an Ionic App causes runtime syntax errors in launching on some devices

Much to my chagrin, I've discovered that an Ionic 4 app that I've developed and tested successfully on my Android (8.0) phone, as well as on an iPhone, freezes on the splash screen on an Android (8.1) tablet and crashes during launch on an iPad. Using adb logcat diagnostic techniques, I observed that on the errant Android tablet, a Syntax Error was being reported in vendor-es5.js, which when I dug into the www folder of my project and went to the referenced line of the error, which said SyntaxError: Unexpected token *, I landed in code that clearly came from node_modules/d3-delaunay/src/delaunay.js and that used the es6 exponentiation operator **, specifically:

r = 1e-8 * Math.sqrt((bounds[3] - bounds[1])**2 + (bounds[2] - bounds[0])**2);

I don't know why this code is problematic on some devices, nor do I know what is causing this code, which is not es5 (?) to end up in the vendor-es5.js file without being transpiled appropriately. To take it a step further, I manually hacked that delaunay.js file to replace all the instances of exponentiation with their equivalent uses of Math.pow() and sure enough, the runtime got further, but eventually ran aground again in a function that came from node_modules/vega-dataflow/src/dataflow/load.js and complained that SyntaxError: Unexpected token function, specifically on this line:

export async function request(url, format) {

Again, obviously async/await is not an es5 construct, so why is it ending up in vendor-es5.js. At this point, I feel like something is systematically wrong here, and I'm not equipped to understand how to overcome it short of maybe switching graphing libraries? I'd like to avoid that if possible, so my questions are:

  1. Why is this happening?
  2. Why does it only have an impact on some, and not all, devices?
  3. Is there a way that I can work around the problem without switching to a different graphing library?


from Using Vega Charts in an Ionic App causes runtime syntax errors in launching on some devices

Wednesday, 8 January 2020

Accelerometer event frequency slows down first 5 min using Angular Ionic on Android device

I am using

window.addEventListener('devicemotion', event => this.watchDeviceMotion(event))

watchDeviceMotion(event: any) {

  let motionData = {
    x: event.acceleration.x,
    y: event.acceleration.y,
    z: event.acceleration.z,
  }
  let rotationData = {
    alpha: event.rotationRate.alpha,
    beta: event.rotationRate.beta,
    gamma: event.rotationRate.gamma
  }

  if (this.getSensorData) {
    // console.log(JSON.stringify(motionData))
    // console.log(JSON.stringify(rotationData))
    this.userData.motionData.push(motionData)
    this.userData.rotationData.push(rotationData)
  }
}

to access accelerometer data on an Android device using Ionic with Angular. When inside the app, the event works at a frequency of 60 Hz but when the app is switched to background, the frequency drops around 9-10 Hz for the first 5 mins and at some point while still in background it goes back at 60 Hz and remains like that indefinitely.

I am also using the background plugin with

this.backgroundMode.enable();
this.backgroundMode.on('activate').subscribe(() => {
  this.backgroundMode.disableWebViewOptimizations();
});

I tried to add disableBatteryOptimizations() to the background plugin with the corresponding condition in config.xml but still no luck.

I also tried the plugins for Device Motion and Gyroscope but they behave the same.

How should I prevent the frequency from slowing down? Has anyone else encountered this problem before?



from Accelerometer event frequency slows down first 5 min using Angular Ionic on Android device

Saturday, 28 December 2019

How to import ionic-angular BaseInput to work with both, JIT and AOT compilation?

I'm working with a pretty standard Ionic v3 project setup and trying to extend BaseInput for a custom component. Since it's not exposed through ionic-angular, I'm trying to import it either through as non-UMD,

import { BaseInput } from 'ionic-angular/util/base-input';

or as UMD,

import { BaseInput } from 'ionic-angular/umd/util/base-input';

The former (non-UMD) case works with the JIT compiler, e.g. when running the app through ionic serve. However, when trying to do a prod build (ionic cordova build <platform> --prod), it fails with seemingly unrelated typescript errors ("Cannot determine the module for class [...] in [...]").

Going with the UMD import poth, prod builds (with the AOT compiler) go through without errors, but trying to run the app fails with an error message:

Error: Cannot find module "."
  at webpackMissingModule (webpack:///node_modules/ionic-angular/umd/util/base-input.js:13:24 <- test-config/karma-integration-test-shim.js:180279:69)
  at webpack:///node_modules/ionic-angular/umd/util/base-input.js:13:24 <- test-config/karma-integration-test-shim.js:180279:147
  at Object.<anonymous> (webpack:///node_modules/ionic-angular/umd/util/base-input.js:19:1 <- test-config/karma-integration-test-shim.js:180288:3)
  at __webpack_require__ (webpack:///webpack/bootstrap%20e1799a6a30ca82a9bd77:19 <- test-config/karma-integration-test-shim.js:20:30)
  at Object.<anonymous> (test-config/karma-integration-test-shim.js:180256:92)
[...]

How can I import BaseInput in a way that complies with both, the JIT and the AOT compiler?



from How to import ionic-angular BaseInput to work with both, JIT and AOT compilation?

Tuesday, 17 December 2019

How to enable App Store promotions for In-app purchases for ionic application?

I am not able use App Store Promotions to promote my in-app purchases because the binary doesn’t include the SKPaymentTransactionObserver method as shown below:

These in-app purchases can’t be promoted on the App Store because your latest approved binary doesn’t include the SKPaymentTransactionObserver method.

The application is developed using Ionic4



from How to enable App Store promotions for In-app purchases for ionic application?