Quantcast
Channel: Ionic Forum - Latest topics
Viewing all 70918 articles
Browse latest View live

Ionic Header width goes past scrolling bar

$
0
0

@AIBug wrote:

I have a floating Ionic Header so when I scroll, the header stays at the top of the page. The problem is that the header goes past the scrolling bar on the right side of the page which looks really crappy. I want it to stop before the scrolling bar, but I’m not sure how :confused: anyone have any ideas? Actually, this website is a great example of the kind of header that i want lol. I’m not sure why my header laps over the scroll bar though :confused:

Posts: 1

Participants: 1

Read full topic


Video not loading mime type not found

$
0
0

@AIBug wrote:

so… i’m trying to get a video on my page from a data.json

the code is basically the same as the IonicConferenceApp’s page: speaker details.
Except, I switched the profile picture out for a video.

It is strange, if i source the video directly, it works fine.

here is my code, then i’ll explain more.

html

<div class="sermon-background">
<div class="topRoom" >
  <video controls="controls" preload="metadata" autoplay="autoplay" webkit-playsinline="webkit-playsinline" class="videoPlayer">
   <source [src]="sermon?.sermonVideo" type="video/mp4" />
  </video>
</div>
<div class="topRoom2">
  <svg width="100%" height="calc(1vw + 1vh + 6vmin)">
    <rect width="100%" height="calc(1vw + 1vh + 6vmin)" style="fill:rgba(44, 44, 44, 0.548);stroke-width:0;stroke:rgb(60,200,160)" />
    <text dominant-baseline="middle" text-anchor="middle" x="50%" y="55%" fill="white" style="font-size: calc(1vw + 1vh + 2vmin); font-family: 'Quicksand', sans-serif; font-weight: calc(.1vw + .1vh + .1vmin); text-shadow: 1px 1px 0px rgba(44, 44, 44, 0.445), 2px 2px 0px rgba(44, 44, 44,0.445), 3px 3px 0px rgba(44, 44, 44, 0.445) ">{{sermon?.name}}</text>
  </svg>
</div >
<img [src]="sermon?.profilePic" [alt]="sermon?.name">

so, the profilePic from the same place using the same method loads fine.

also, if I use “src=assets/videos/Sermon1.mp4”, that works fine.

here is my data.json

      "name": "Finding Grace",
  "profilePic": "/assets/img/stuffs/PastorEvaFace.jpg",
  "sermonVideo": "/assets/videos/Sermon1.mp4",
  "about": "Learn to fnid Grace in every circumstance and realize just how much God has given you.",
  "sum": "God has given us grace, we just need to open our eyes.",
  "location": "Everywhere",
  "id": "1"

anyone have any idea why it can’t run the video? profilePic runs fine…

I get the error “No video with supported format and mime type not found” when i try video

Thank in advance for taking a peak

Posts: 1

Participants: 1

Read full topic

What happened to my array in typescript...?

How do make ionic app detech change when update is made?

$
0
0

@Geelario wrote:

Good day house, please I need your help, I noticed that my ionic app doesn’t detect change when an update is made. I have a profile page that displays authenticated users data from an api( i.e username and email). Also, a profile_edit page that updates user data. But I noticed that when I update user data and navigate to the profile page, the change doesn’t reflect on the profile page unless I navigate to another page and back before it detects the change. I tried using BehaviourSubject but I don’t really know how to implement it. I have spent days on this, please I need your assistance. Thanks. My code below

profile.page.ts

  public  customerData: any

  constructor ( WC: WoocommerceService) {
   }

  ngOnInit() {


// this retrieve authenticated user id
    this.isUserLoggedIn = localStorage.getItem('currentUserId');

// this retrieve user data  from an api call
    this.WC.getUserInfo(this.isUserLoggedIn).subscribe((data)=>{

      this.customerData = data;  

    });

  }

profile.html

 <ion-col size="12">
    <ion-label *ngIf="customerData" class="ion-text-center">
      <p>{{ customerData.first_name}} {{ customerData.last_name}}</p>
      <ion-card-subtitle>{{customerData.email}}</ion-card-subtitle>
    </ion-label>
  </ion-col>

woocommerce service page

export class WoocommerceService {

 private authenticationState = new BehaviorSubject<any>([]);
  data = this.authenticationState.asObservable();

//getting authenticated users details from woocommerce

getUserInfo(id){

  this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}?consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;

  console.log('API url for retrive customer: ', this.apiUrl);

  this.customerData = this.http.get(this.apiUrl);

 // STORE WHATEVER DATA YOU WANT IN THE SUBJECT 

   this.authenticationState.next(this.customerData);

   return this.customerData;

}


// this update user data
updateCustomerData(id, customerDataUpdated){

  let headers = new HttpHeaders ({

    "Content-Type" : "application/json"

  });

  this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}?consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;

 // console.log('API url for retrive customer data: ', this.apiUrl);

  return new Promise((resolve, reject) => {

    this.http.put(this.apiUrl, customerDataUpdated, {headers} ).subscribe(

      response => {

        resolve(response);

        this.authenticationState.next(this.customerData);

        console.log('Customer Data Updated: ', response);
    },

    error => {

      resolve(error);

     console.log('Customer Data Updated failed ', error);

    }

    )

  });

}
}

Posts: 1

Participants: 1

Read full topic

Backend for a food ordering mobile app

$
0
0

@Remling wrote:

Hello,

i want to make a simple food ordering mobile app, but i’m struggling with the decision of the right backend solution. I need the backend to keep track of the cart and maybe also the payment.
And of course user data, but thats something every backend can do.

What would be a good solution for that? i thought about using firebase, but i’m not sure if thats right.

Posts: 1

Participants: 1

Read full topic

Capacitor Share

$
0
0

@RaulGM wrote:

Hi everyone! Does anyone have a capacitor share example? I need to share some text with WhatsApp. I don’t know if there is a deep link to reference.

I literally have

import { Plugins } from '@capacitor/core';
const { Share } = Plugins;

let shareRet = await Share.share({
 title: 'See cool stuff',
 text: 'Really awesome thing you need to see right meow',
 url: 'http://ionicframework.com/',
 dialogTitle: 'Share with buddies'
});

I got the following error:
ERROR Error: Uncaught (in promise): Web Share API not available

Posts: 1

Participants: 1

Read full topic

Ionic React How can I hide the IonTabs, I'm so desperate please help ASAPPP

$
0
0

@Ohmpudit wrote:

<IonTabBar slot="bottom">
        <IonTabButton tab="myWarranty" href="/myWarranty">
          <IonIcon icon={document} />
          <IonLabel>Warranty</IonLabel>
        </IonTabButton>
        <IonTabButton tab="addWarranty" href="/addWarranty">
          <IonIcon icon={addCircleOutline} />
          <IonLabel>Add Warranty</IonLabel>
        </IonTabButton>
        <IonTabButton tab="history" href="/history">
          <IonIcon icon={refresh} />
          <IonLabel>History</IonLabel>
        </IonTabButton>
      </IonTabBar>
    </IonTabs>

I want the tab bar declared in App.tsx to be hidden in some page like signin, login what should I write

const SignIn: React.FC = (props) => { …}

what would be the approach for Signin?

Posts: 1

Participants: 1

Read full topic

Pull data from firebase into a calendar

$
0
0

@ryan-kelly1997 wrote:

Hi,
I want to have a calendar that pulls information from a database in firestore and populates the corresponding dates in the calendar. For example if there was an event on the 28th march I want the calendar to connect to firebase where there is an event inside a collection and when the calendar loads, have the dates from firebase inside the calendar.

I have made the basic calendar in Ionic using ion-2-calendar. I have also established a connection to firebase inside the project and verified this with a console.log() statement which pulls from a sample database collection called competition with a date inside it

The tester collection includes a string for date i.e “28th May” and also a timestamp with the time as well in the format March 28th 2020 I’m not sure which is best to use.

If anyone could help me with this, it would be appreciated

Code is here

Html

Calendar Page
<ion-calendar [(ngModel)]="date"
  (onChange)="onChange($event)"
  [type]="type"
  [format]="'YYYY-MM-DD'">
</ion-calendar>

TS
import { Component } from ‘@angular/core’;
import {tap} from ‘rxjs/operators’;
import {AngularFirestoreModule, AngularFirestore} from ‘@angular/fire/firestore’;
import {Injectable} from ‘@angular/core’;

@Component({
selector: ‘app-home’,
templateUrl: ‘home.page.html’,
styleUrls: [‘home.page.scss’],
})
export class HomePage {
date: string;
type: ‘string’;

constructor(private afs:AngularFirestore) {
this.afs.collection(‘competition’).valueChanges().subscribe(data=>{console.log(data);
})
}

Posts: 1

Participants: 1

Read full topic


Error when trying to create a project

$
0
0

@bilibekour wrote:

I have installed the latest version of ionic:
C:\Users\Bilal>npm install -g @ionic/cli
C:\Users\Bilal\AppData\Roaming\npm\ionic -> C:\Users\Bilal\AppData\Roaming\npm\node_modules@ionic\cli\bin\ionic

  • @ionic/cli@6.6.0
    added 227 packages from 157 contributors in 276.868s

but when I try to create an app it gives me this error, some help please:
C:\ionic>ionic start reprise blank
No valid exports main found for ‘C:\Users\Bilal\AppData\Roaming\npm\node_modules@ionic\cli\node_modules\is-promise’

Posts: 1

Participants: 1

Read full topic

Scroll position iOS doesn't set

$
0
0

@alokjkumar97 wrote:

Hi there

I’m building a simple chat application and I’m facing an issue with setting the scroll position in iOS. It seems to work find on other platforms, including browser. Ionic v5, using Capacitor, building with Appflow.

The container needs to be scrolled to the bottom by default when the data loads. The page then listens for new messages. If a new message is added then the page should scroll to the bottom if the scroll position is within the bottom 150% of the client height. If not, a FAB appears indicating a new message has appeared and the user can select the button to scroll to the button.

The markup is as so. I have a custom domChange directive which listens to dom changes in the div. I prefer to put the scroll logic here as I was experiencing bugs putting it in the message listener before.

<ion-content>
  <div class="chat-container" (click)="containerClick();" (scroll)="scroll($event)" #chatContainer>
    <div class="wrapper" *ngIf="messages.length > 0" (domChange)="onDomChange($event)">
      <!-- Excuse my inline styling, this is just for debug -->
      <div style="width:100%;text-align:center;padding:20px;" *ngIf="loadingMore"><ion-spinner></ion-spinner></div>
      <ng-container *ngFor="let message of messages">
        <chat-bubble
        [sent]="message.from === authService.user.id"
        [delivered]="message.delivered"
        [position]="message.position"
        [timestamp]="message.createdAt.getTime()"
        [content]="message.content"
        >
        </chat-bubble>
      </ng-container>
    </div>
  </div>
  <ion-fab vertical="bottom" horizontal="center" slot="fixed" *ngIf="showScrollBtn">
    <ion-fab-button size="small" (click)="scrollToBottom()"><ion-icon name="arrow-down-outline"></ion-icon></ion-fab-button>
  </ion-fab>
</ion-content>

The CSS is relatively simple but I am use a column-reverse flexbox and I think this might be one of the causes to the issue. The column-reverse means the webview renders the scroll at the bottom by default.

.chat-container {
  height: 100%;
  flex-grow: 1;
  overflow: auto;
  display: flex;
  flex-direction: column-reverse;
  overflow-x: hidden;
  padding: 0 16px 0 16px;
}

And then the relevant functions are:

  public onDomChange(event: any) {
    if(event.addedNodes.length > 0 && event.addedNodes[0].localName == 'chat-bubble') {
      const scrollTop = (this.platform.is('ios') && !this.platform.is('mobileweb')) ? this.chatContainer.nativeElement.scrollTop + this.chatContainer.nativeElement.scrollHeight : this.chatContainer.nativeElement.scrollTop;
      /*
       * Because of the column-reverse iOS sees the bottom of the div as scrollTop = 0 and the top of the div as scrollTop = -scrollHeight
       * Android sees it as scrollTop = scrollHeight at the bottom and scrollTop = 0 at the top
      */
      const scrollHeight = this.chatContainer.nativeElement.scrollHeight;
      const clientHeight = this.chatContainer.nativeElement.clientHeight * 1.5;

      const newMessageIndex = this.messages[this.messages.length - 1].index;

      if((this.messages.length <= 30 || scrollHeight - scrollTop <= clientHeight) && this.channel.lastConsumedMessageIndex < newMessageIndex) {
        this.scrollToBottom();
      } else if(this.channel.lastConsumedMessageIndex < newMessageIndex) {
        this.showScrollBtn = true;
      }
    }
  }
  public scrollToBottom(): Promise<any> {
    this.showScrollBtn = false;
    this.chatContainer.nativeElement.scrollTop = this.chatContainer.nativeElement.scrollHeight;
    return this.channel.setAllMessagesConsumed();
  }

The scrollToBottom() function works absolutely fine when triggered by the button click event but doesn’t seem to do anything when triggered in the domChange trigger. I think this is because the trigger is called before the chat bubble element has rendered but I’m not sure how to fix this.

Would appreciate any ideas/thoughts

Thanks in advance

Posts: 1

Participants: 1

Read full topic

Ionic 3 Migration Advice

$
0
0

@Willcowd wrote:

Hi All

I’m looking for some general guidance going forward.
I’ve got 2 Ionic 3 projects. One personal and one work one. The personal one is currently causing me the issues.

I can’t deploy to the browser because it doesn’t build the cordova_plugins.js file.
I’ve tried removing browser and adding browser, but this comes back

(node:19649) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SyntaxError: Unexpected token < in JSON at position 258
(node:19649) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Not helpful.

I know my plugins are outdated (See below), but every time I update them, I get caught in “Dependency Hell” and have to go back to where I started and hope that it magically works again.

I’m concerned that if I update the Ionic CLI, the work project is going to break and that’s not going to be deployable.

Will updating the CLI break old projects?

Also, is it possible to run a V3 app and a V4 app on the same computer?

Any help would be much appreciated. As you can tell, I’m getting frustrated with this.

Many thanks
Mark

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.19.2
    ionic (Ionic CLI) : 3.20.0

global packages:

    cordova (Cordova CLI) : 8.0.0 

local packages:

    @ionic/app-scripts : 3.2.4
    Cordova Platforms  : android 7.0.0 browser 5.0.4 ios 4.3.1
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 26.1.1
    Node              : v8.0.0
    npm               : 2.15.12 
    OS                : Linux 4.15

Environment Variables:

    ANDROID_HOME : /home/mark/Programs/Android/Sdk

Misc:

    backend : pro

Posts: 1

Participants: 1

Read full topic

Using router.navigate to navigate between ion-tab s

$
0
0

@vitonimal wrote:

Hello! I am trying to implement navigation between tabs. I read the following documentation: https://ionicframework.com/docs/api/tab-button but it is not solving my use case. Here is what I am trying to do:

I want 3 tabs. Each tab will load a component with specific parameters. My main concern is that I need to pass parameters to each component, and not from the query params. I have in fact read through that SO post : https://stackoverflow.com/questions/56197176/how-to-pass-parameters-through-ionic-4-tabs-buttons

However, I need to pass objects as parameters, and it just does not seem clean at all to use query parameters.

<ion-tabs id="nav-tabs-work-order" tabsPlacement="bottom" tabsHighlight="false" selectedIndex={{tab}}>
  <ion-tab tabTitle="Issued" [root]="issuedWorkOrders" [rootParams]="issuedWorkOrdersParams" tabsHideOnSubPages="true"></ion-tab>
  <ion-tab tabTitle="In Progress" [root]="inProgressWorkOrders" [rootParams]="inProgressWorkOrdersParams" tabsHideOnSubPages="true"></ion-tab>
  <ion-tab tabTitle="Completed" [root]="completedWorkOrders" [rootParams]="completedWorkOrdersParams" tabsHideOnSubPages="true"></ion-tab>
</ion-tabs>

After reading through the doc, I noticed that I would need a structure that looks like:

<ion-tabs>
  <ion-tabs-bar slot="bottom">
    <ion-tab-button (click)="navigateToWorkOrdersList(issuedWorkOrdersParams)">
      <ion-label>Issued</ion-label>
    </ion-tab-button>
    <ion-tab-button (click)="navigateToWorkOrdersList(inProgressWorkOrdersParams)">
      <ion-label>In progress</ion-label>
    </ion-tab-button>
    <ion-tab-button (click)="navigateToWorkOrdersList(completedWorkOrdersParams)">
      <ion-label>Completed</ion-label>
    </ion-tab-button> 
  </ion-tabs-bar>
</ion-tabs>

Here is the issue though! It won’t compile unless I have a tab attribute to each ion-tab-button that would be responsible to navigate to another component (if I understood the doc correctly).

I tried to add a (click) to illustrate that I needed the navigation to occur when I click on the tab (I know that this behaviour occurs in a general use case due to the tab attribute).

Here is the navigation function: (I just realized it is missing a relativeTo param, but the reason for the bug really is the template)


  public navigateToWorkOrdersList(params: any) : void {
    this.router.navigate(['construction/list'], { state: params });
  }

I know that the router that I would need to use would be different than the router above (router-outlet’s router), but the method above shows what I want to achieve with the tabs. In other words, is there a way I can access the tabs’ router?

Note that the error message I am getting is pretty odd:


Then the app freezes.

That being said, how can I reproduce the exact ionic 3 code using the new syntax in ionic 4? Thanks!

I will keep looking on my end and let you know if I can find anything.

Posts: 2

Participants: 1

Read full topic

Problem after install ionic@6.6.0

$
0
0

@mbaybig wrote:

Hi everybody,

I new here and on ionic. I want to use ionic but after installation, i can not create a app.
This my error :
Mianssodila@Mianssodila-PC MINGW64 /e/HybridApps
$ ionic --version
6.6.0

Mianssodila@Mianssodila-PC MINGW64 /e/HybridApps
$ ionic start MyAPPv1 blank
√ Preparing directory .\MyAPPv1 - done!
√ Downloading and extracting blank starter - done!
–no-confirm: Integrate your new app with Capacitor to target native iOS and Android? No

Installing dependencies may take several minutes.

──────────────────────────────────────────────────────────────────────

  Ionic Enterprise, platform and solutions for teams by Ionic

              Powerful library of native APIs
             A supercharged platform for teams

     Learn more: https://ion.link/enterprise

──────────────────────────────────────────────────────────────────────

npm.cmd i
npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated fsevents@1.2.12: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm ERR! Unexpected end of JSON input while parsing near ‘…:"^1.10.0"},“dist”:{"’

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Mianssodila\AppData\Roaming\npm-cache_logs\2020-04-26T01_56_54_998Z-debug.log
[ERROR] An error occurred while running subprocess npm.

    npm.cmd i exited with exit code 1.

    Re-running this command with the --verbose flag may provide more information.

Mianssodila@Mianssodila-PC MINGW64 /e/HybridApps
$

PLEASE I NEED HELP

Best Regards,

Posts: 1

Participants: 1

Read full topic

Beginner - Ionic 4 Help - Transferring data from Tab 3 (form) to tab 4

$
0
0

@brown34 wrote:

I am trying to transfer the data on tab 3 (Reserve) to the tab 4 (MyTables). I am going to be completely honest. I do not know how to write in ionic at all. Person teaching doesnt help as he talks like we know. Any help would be appreciated. I am almost at the point to pay someone to do it. I can zip the file if needed or uploaded but thats alot of code for 5 folders.

Posts: 1

Participants: 1

Read full topic

App rejected because of permissions in a SafariViewController only app

$
0
0

@webappdev2020 wrote:

Hello,
I have issues to get my app approved by Apple. My web app is using WebRTC which is not supported by the default WebView of Apple. Because of this, I’m using the “SafariViewController Cordova Plugin” which opens my web app in a SafariViewController / Safari window after clicking on a button. Then my web app asks the user for the permissions for the camera, microphone and location access. This request is displayed in the default Safari dialog and can’t be modified. This looks like to be the problem.

Apple rejected my app with this information:

Please revise the relevant purpose string in your app’s Info.plist file to specify why the app is requesting access to the user's microphone and location.

They attached the following screenshot:

As you can see here, my app has this kind of informations in the Info.plist:

	<key>NSMicrophoneUsageDescription</key>
	<string>To access your microphone so that you can talk with a chat partner.</string>
	<key>NSCameraUsageDescription</key>
	<string>To access your camera roll so that you can upload images, show you to a chat partner and scan QR codes.</string>
	<key>NSPhotoLibraryUsageDescription</key>
	<string>To access your camera roll so that you can upload images.</string>
	<key>NSPhotoLibraryAddUsageDescription</key>
	<string>To access your camera roll so that you can upload images.</string>
	<key>NSLocationWhenInUseUsageDescription</key>
	<string>To access your position so that a chat partner can be searched near you.</string>
	<key>NSLocationAlwaysUsageDescription</key>
	<string>To access your position so that a chat partner can be searched near you.</string>
	<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
	<string>To access your position so that a chat partner can be searched near you.</string>
	<key>NSLocationUsageDescription</key>
	<string>To access your position so that a chat partner can be searched near you.</string>

They are not displayed because it’s not possible to ask in a Safari window for these permissions with a custom dialog like described in the Info.plist. It’s always a default dialog.

Did someone of you have this kind of problem?
My app is adding a native functionality to be able to scan QR codes. When the user is using this functionality for the first time, there is a dialog with the message set in the Info.plist file. This permission is not “transferred” to the new SafariViewController / Safari window so that the Safari window has to ask for these permissions again with a default dialog.

Thank you and best regards.

Posts: 1

Participants: 1

Read full topic


kurentoUtil Test Error

$
0
0

@peterkhang wrote:

I am using kurento-magic-mirror client sources to connect to kurento server.

I have migrated this source to ionic :slight_smile:

import { Component, OnInit,ViewChild,ElementRef, HostListener, NgZone  } from '@angular/core'
import { AuthServiceProvider } from 'src/app/providers/auth-service/auth-service'
import { v4 as uuidv4 } from 'uuid'
import { environment } from 'src/environments/environment'
import { WebRtcPeer, KurentoClient } from 'kurento-utils'
import { QueueingSubject } from 'queueing-subject'
import { Subscription, Observable, timer } from 'rxjs'
import { Timer } from 'interval-timer'
import { share, switchMap, retryWhen, delay, map } from 'rxjs/operators'
import { PushEvent, Status } from 'src/app/providers/common/common'
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';

import makeWebSocketObservalbe, {
  normalClosureMessage,
  WebSocketOptions,
  GetWebSocketResponses,
} from 'rxjs-websockets'

//https://github.com/webhacking/WebRTC-Example-With-Typescript/blob/master/src/main.ts
@Component({
  selector: 'app-webrtc',
  templateUrl: './webrtc.page.html',
  styleUrls: ['./webrtc.page.scss'],
})
export class WebrtcPage implements OnInit {
  isRecording = false
  @ViewChild('videoInput',{read: ElementRef,static: true}) videoInput: ElementRef<HTMLElement>
  @ViewChild('videoOutput',{read: ElementRef,static: true}) videoOutput: ElementRef<HTMLElement>
  webRtcPeer: WebRtcPeer = null
  input: QueueingSubject<string> = null
  websocket: Observable<GetWebSocketResponses<string>> = null
  messages: Observable<string | ArrayBuffer | Blob> = null
  messagesSubscription: Subscription = null
  isSubscribed: boolean = false
  status: Status = Status.I_CAN_START
  loading = null
  I_CAN_START = 0
  I_CAN_STOP = 1
  I_AM_STARTING = 2


  constructor(public auth: AuthServiceProvider, public androidPermissions: AndroidPermissions) { 
    
  }

  ngOnInit() {
  }

  IonViewDidEnter() {

  }

  IonViewWillLeave() {
    

    if( this.webRtcPeer ) {
      this.stop()
    }

    if( this.isConnected() ) {
      this.close()
    }
  }

  isConnected(): boolean {
    return this.messagesSubscription && !this.messagesSubscription.closed
  }

  send(message: any): void {
    try {
      this.input.next(JSON.stringify(message))
    } catch(e) {
      console.log('socket send error : ' + JSON.stringify(e))
      this.closeWebsocket()
    }
  }

  closeWebsocket() {
    try { this.messagesSubscription.unsubscribe() } catch(e) {}
    this.messagesSubscription = null
    this.messages = null
    this.websocket = null
    try { this.input.unsubscribe() } catch(e) {}
    this.input = null
    this.isSubscribed = false
  }

  startResponse(message) {
    this.status = Status.I_CAN_STOP
    console.log("SDP answer received from server. Processing ...");
  
    this.webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
      if (error)
        return console.error(error);
    });
  }

  connect() {

    if( this.isConnected() ) {
      this.closeWebsocket()
    }

    this.isSubscribed = false
    // this.eventList = []
    // this.eventList.unshift({path: 'SEND', message: PushEvent.CONNECT})
    this.input = new QueueingSubject<string>()
    this.websocket = makeWebSocketObservalbe(environment.wsHostUrl)
    this.messages = this.websocket.pipe(
      switchMap((getResponses: GetWebSocketResponses) => {
        console.log('websocket opened')
        return getResponses(this.input)
      }),
      retryWhen((errors) => {
        errors.subscribe(sourceError => {
          console.log(JSON.stringify(sourceError))
        })
        return Observable.create(obs => obs.eror(PushEvent.DISCONNECTED))
      }),
      share(),
    )
    this.messagesSubscription = this.messages.subscribe(
      (message: string | ArrayBuffer | Blob ) => {

        try {
          let received: any = null
          if( message instanceof ArrayBuffer ) {
            received = JSON.parse(String.fromCharCode.apply(null, new Uint16Array(message)))
          } else if( message instanceof Blob ) {
            throw new Error('Blob message is not allowed')
          } else {
            console.log('received message:', message)
            received = JSON.parse(message)
          }
          var parsedMessage = received.data
          console.info('Received message: ' + parsedMessage)
          switch (parsedMessage.id) {
            case 'startResponse':
                this.startResponse(parsedMessage);
                break;
            case 'error':
                if (this.status === Status.I_AM_STARTING) {
                  this.status = Status.I_CAN_START
                }
                console.log("Error message from server: " + parsedMessage.message);
                break;
            case 'iceCandidate':
                this.webRtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {
                  if (error) {
                      console.error("Error adding candidate: " + error);
                      return;
                  }
                });
                break;
            default:
                if (this.status === Status.I_AM_STARTING) {
                  this.status = Status.I_CAN_START
                }
                console.log('Unrecognized message', parsedMessage);
            }
        } catch(e) {
          console.log(JSON.stringify(e))
        }
      },
      (error: Error) => {
        const { message } = error
        if (message === normalClosureMessage) {
          // this.eventList.unshift({path: 'RECV', message: PushEvent.UNSUBSCRBE})
          this.closeWebsocket()
        } else {
          // this.eventList.unshift({path: 'RECV', message: PushEvent.UNSUBSCRBE})
          console.log('socket was disconnected due to error: ', message)
          this.closeWebsocket()
        }
      },
      () => {
        console.log('the connection was closed in response to the user')
        // this.eventList.unshift({path: 'RECV', message: PushEvent.CLOSED})
        this.closeWebsocket()
      }
    )
  }
  
  close() {
    
    try {
      if( this.isSubscribed ) {
        //this.unsubscribe()
      }

      const localTimer = new Timer({
        startTime: 300,
        endTime: null,
        updateFrequency: null,
        selfAdjust: true,
        countdown: false,
        animationFrame: false
      })

      localTimer.on('start', () => {
        // this.eventList.unshift({path: 'RECV', message: PushEvent.CLOSED})
        this.closeWebsocket()
      })

      localTimer.start()

    } catch(e) {}
  }

  onOffer(offerSdp) {
    console.info('Invoking SDP offer callback function ' + location.host);
    var message = {
       id : 'start',
       sdpOffer : offerSdp
    }
    this.send(message);
  }

 
  onIceCandidate(candidate) {
    console.log("Local candidate" + JSON.stringify(candidate));

    var message = {
      id: 'onIceCandidate',
      candidate: candidate
    };
    this.send(message);
  }

  async startAfterCheckPermission() {

    var list = [
      this.androidPermissions.PERMISSION.CAMERA,
      this.androidPermissions.PERMISSION.MODIFY_AUDIO_SETTINGS,
      this.androidPermissions.PERMISSION.RECORD_AUDIO,
      this.androidPermissions.PERMISSION.INTERNET,
      this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE,
    ]
    
    this.androidPermissions.requestPermissions(list).then( result => {
      if( result.hasPermission )
        this.start() 
      else
        this.auth.presentAlert('Media Device Permission Not Granted')
    }, err => {
        this.auth.showError(err)
    })
  }

  async start() {
    console.log("Starting video call ...")
    this.status = Status.I_AM_STARTING
    this.loading = await this.auth.showLoading()
    
    console.log("Creating WebRtcPeer and generating local sdp offer ...");
 
    var constraints = {
      audio: true,
      video: {
        width: 640,
        framerate: 15
      }
    }
    var options = {
        audio: true,
        localVideo: this.videoInput,
        remoteVideo: this.videoOutput,
        onicecandidate: this.onIceCandidate,
        mediaConstraints: constraints,

      }

    this.webRtcPeer = new WebRtcPeer.WebRtcPeerSendrecv(options,
      function (error) {
        if (error) {
          return console.error(error);
        }
        this.webRtcPeer.generateOffer(this.onOffer);
      });

    if( ! this.websocket ) {
      this.auth.presentAlert('Cannot create webRtc adapter')
      this.loading.dismiss()
    } else {

      if( !this.isConnected() ) {
        this.connect() 
      }
    }
  }

  stop() {
    console.log("Stopping video call ...");
    this.status = Status.I_CAN_START

    if (this.webRtcPeer) {
      this.webRtcPeer.dispose();
      this.webRtcPeer = null;
  
      var message = {
        id : 'stop'
      }
      this.send(message);
    }

    this.loading.dismiss()
  }
}

But this.webRtcPeer = new WebRtcPeer.WebRtcPeerSendrecv() returns null: So I have got error as followings .

2020-04-26 15:46:28.777 10434-10716/io.bory.speechmate E/cr_VideoCapture: CameraDevice.StateCallback onOpened
2020-04-26 15:46:28.778 10434-10716/io.bory.speechmate V/Surface: sf_framedrop debug : 0x4f4c, game : false, logging : 0
2020-04-26 15:46:28.782 10434-10716/io.bory.speechmate I/CameraManager: getCameraCharacteristics : cameraId = 1
2020-04-26 15:46:28.785 10434-10716/io.bory.speechmate I/CameraManager: getCameraCharacteristics : cameraId = 1
2020-04-26 15:46:28.821 3647-3788/? D/MdnieScenarioControlService:  packageName : io.bory.speechmate    className : io.bory.speechmate.MainActivity
2020-04-26 15:46:28.887 10434-10434/io.bory.speechmate E/chromium: [ERROR:web_contents_delegate.cc(218)] WebContentsDelegate::CheckMediaAccessPermission: Not supported.
2020-04-26 15:46:28.905 10434-10434/io.bory.speechmate E/Capacitor/Console: File: http://localhost/93-es2015.7ef3d9410b63064250ff.js - Line 1 - Msg: TypeError: Cannot read property 'generateOffer' of undefined

Posts: 1

Participants: 1

Read full topic

Best way to use conditions (*ngIf vs. functions)

$
0
0

@keber wrote:

Hi all,

I’m wondering what’s the best way to show or hide HTML elements based on conditions in Ionic applications. I’m not sure if I’m currently doing it right / the way it should be.

Let’s say I have a couple of themes (products) displayed by cards with the ion-card components. Some of the products can be purchased via InApp Purchases and others are free.
I now have to make sure which one are free, paid, have been purchased etc. and therefore display either a click function to open a modal or navigate to the page where the product can be purchased.

My HTML code currently looks like this:

<ion-grid>
      <ion-row>
        <ion-col *ngFor="let theme of themes">
          <!-- If it's a free theme or already owned, display useTheme function -->
          <ion-card *ngIf="theme.category == 'free' || theme.owned == true" (click)="useTheme(theme.themeID)">
            <ion-badge *ngIf="theme.owned == true">purchased</ion-badge>
            <ion-img [src]="theme.src"></ion-img>
          </ion-card>
          <!-- If it's a paid theme and not owned, provide a link to the purchase page -->
          <ion-card *ngIf="theme.category == 'paid' && theme.owned == false" routerLink="link/to/theme/purchase">
            <ion-badge>1,99 EUR</ion-badge>
            <ion-img [src]="theme.src"></ion-img>
          </ion-card>
          <ion-text>{{theme.description}}</ion-text>
        </ion-col>
      </ion-row>
    </ion-grid>

Is this the right way? Or do you suggest handling the if/else stuff in the array item in my .ts files and avoiding *ngIf-conditions like these in my HTML?

I’m asking because sometimes I face the problem that the images of my paid products are not displayed on the initial app start. They just show up as soon as I click on some elements or navigate to a different page.

Thank you in advance for any suggestions and best regards!

Posts: 1

Participants: 1

Read full topic

Ionic / firebase google login doesn't redirect back

$
0
0

@benasber wrote:

Hi guys, kind of new to using firebase here and I’m running into an issue while developing an Android app.
I’m trying to do google authentication according to this little guide here

so I use the GoogleAuth() function to login:

GoogleAuth() {

    this.AuthLogin(new firebase.auth.GoogleAuthProvider());

  }

  // Auth providers

  AuthLogin(provider) {

    firebase.auth().signInWithRedirect(provider).then(function() {

      return firebase.auth().getRedirectResult();

    })

    .then(function(result) {})

    .catch(function(error) {

      // Handle Errors here.

      var errorCode = error.code;

      var errorMessage = error.message;

    });

  }

And everything goes to plan, except, that when I choose my google account, I get redirected to my app IN THE BROWSER, instead of natively, which messes everything up, as the browser just throws errors and other issues while trying to compile the app.

How do I fire the callback I provided in the function and redirect back to the app, instead of having to continue in the browser?

Thanks a lot!

Posts: 1

Participants: 1

Read full topic

ReactiveForms with capacitor camera plugin not working right

$
0
0

@Nandomando wrote:

Hi there I hope everyone is safe, I been having this problem for like a few days now. Im trying to update my user info and works except for the photo but my form doesnt wanna read the file. i have use another pluging with it camerasource and cameraresulttype to be able to use the camera in the browser as well, the thing is that it works just fine in Desktop but when it comes to a real device android it does not work I try to do some console.log(this.form.get(‘photo’).value and in browser console, works fine i can see the img or photo file but in android it gives me null.
Please help thank you
this are the file:
ngOnInit() {

this.route.paramMap.subscribe(paramMap => {

  if (!paramMap.has('userinfoId')) {

    this.navCtrl.navigateBack('/tabs/tab/profile');

    return;

  }

  this.userinfoId = paramMap.get('userinfoId');

  this.isLoading = true;

  this.userinfoSub = this.userinfoService

    .getUserinfo(paramMap.get('userinfoId'))

    .subscribe(

      userInfo => {

        this.userinfo = userInfo;

        this.form = new FormGroup({

          name: new FormControl(this.userinfo.name, {

            updateOn: 'blur',

            validators: [Validators.required, Validators.maxLength(18)]

          }),

          photo: new FormControl(null)

            // {

            // updateOn: 'blur',

            // validators: [Validators.required]

          // })

        });

        this.isLoading = false;

      },

      error => {

        this.alertCtrl

          .create({

            header: 'An error occurred!',

            message: 'Info could not be fetched. Please try again later.',

            buttons: [

              {

                text: 'Okay',

                handler: () => {

                  this.router.navigate(['/tabs/tab/profile']);

                }

              }

            ]

          })

          .then(alertEl => {

            alertEl.present();

          });

      }

    );

});

}

onUpdateUserInfo() {

if (!this.form.valid) {

  return;

}

this.loadingCtrl

  .create({

    message: 'Updating...'

  })

  .then(loadingEl => {

    loadingEl.present();

    console.log(this.form.value.photo);

    console.log();

    console.log(this.form.get('photo').value);

    this.userinfoService

    .uploadImage(this.form.get('photo').value)

    .pipe(

      switchMap( uploadRes => {

        return this.userinfoService

          .updateUserInfo(

            this.userinfo.id,

            this.form.value.name,

            uploadRes.imageUrl

          );

      })

    )

      .subscribe(() => {

        loadingEl.dismiss();

        this.form.reset();

        this.router.navigate(['/tabs/tab/profile']);

      });

  });

}

Posts: 1

Participants: 1

Read full topic

PWA filesystem

$
0
0

@arsyad wrote:

Hi,

I am trying to create a PWA app that downloads some files (e.g. PDF, Word, Images etc) to a folder on the device. The files will total up to around 700MB or more. The requirement is to develop the app as a PWA and install as a standalone to a mobile device.

I am using Ionic 5 with Angular and Capacitor. Capacitor has a Filesystem plugin which allow to write files to disk easily but I noticed it is writing to a FileStorage within the IndexedDB. From what I read there is a storage limit if it’s being stored within the IndexedDB and also files may be purged.

Is it possible to read/write the files via PWA as if it’s a native / cordova app? It would be probably be something like a Google Drive app but in PWA form.

The reason we are going the PWA route is to skip the app / play store. Is this idea possible with PWA or a better way is to build it as a cordova / native app?

Many thanks in advance!

Posts: 1

Participants: 1

Read full topic

Viewing all 70918 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>