Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all 49418 articles
Browse latest View live

Cache images not Uploading to server

$
0
0

Hi

I’ve created an application that takes photos and then needs to send them up to a server.

The problem that I’m having is that when doing the upload only some of the images are sent to the server.

It seems that images that come from the file location work fine.

file:///data/user/0/io.ionic.starter/files/filename.jpg

and then the images that come from the cache don’t upload at all.

file:///data/user/0/io.ionic.starter/cache/filename.jpeg

First question, what would cause the same code to save the images in different locations? Could this be a product of using local storage?

I’ve pretty much followed the Your First Ionic App: React tutorial to create the app. I did make some changes as I didn’t require a gallery.

I’ve included the entire hook file that I’m using below.

Thanks in advance.

import { useState, useEffect } from "react";
import { useCamera } from "@ionic/react-hooks/camera";
import { useFilesystem, base64FromPath } from "@ionic/react-hooks/filesystem";
import { useStorage } from "@ionic/react-hooks/storage";
import { isPlatform } from "@ionic/react";
import {
  CameraResultType,
  CameraSource,
  CameraPhoto,
  Capacitor,
  FilesystemDirectory,
} from "@capacitor/core";

export interface Photo {
  filepath: string;
  webviewPath?: string;
  base64?: string;
}

export interface GalleryPhoto {
  webviewPath?: string;
  base64?: string;
}

const PHOTO_STORAGE = "photos";

export function usePhoto() {
  const { getPhoto } = useCamera();
  const [photos, setPhotos] = useState<Photo[]>([]);
  const { deleteFile, getUri, readFile, writeFile } = useFilesystem();
  const { get } = useStorage();

  useEffect(() => {
    /* On mobile, we can directly point to each photo file on the Filesystem and 
    display them automatically. On the web, however, we must read each image from 
    the Filesystem into base64 format, using a new base64 property on the Photo 
    object. This is because the Filesystem API uses IndexedDB under the hood. */
    const loadSaved = async () => {
      const photosString = await get(PHOTO_STORAGE);
      const photosInStorage = (photosString
        ? JSON.parse(photosString)
        : []) as Photo[];

      // Running on the web
      if (!isPlatform("hybrid")) {
        for (let photo of photosInStorage) {
          const file = await readFile({
            path: photo.filepath,
            directory: FilesystemDirectory.Data,
          });
          photo.base64 = `data:image/jpeg;base64,${file.data}`;
        }
      }
      setPhotos(photosInStorage);
    };
    loadSaved();
  }, [get, readFile]);

  const takePhoto = async (fileNamePrefix: string) => {
    const cameraPhoto = await getPhoto({
      resultType: CameraResultType.Uri,
      source: CameraSource.Camera,
      quality: 65,
      width: 700,
      height: 900,
    });

    const fileName = `${fileNamePrefix}-${new Date().getTime()}.jpg`;
    // return await savePhoto(cameraPhoto, fileName);
    const savedFileImage = await savePhoto(cameraPhoto, fileName);
    // console.log(savedFileImage.base64);
    // console.log(savedFileImage.filepath);
    // console.log(savedFileImage.webviewPath);
    const newPhotos: Photo[] = [savedFileImage, ...photos];

    setPhotos(newPhotos);
  };

  const savePhoto = async (photo: CameraPhoto, fileName: string) => {
    let base64Data: string;

    // Check if we are running on Capacitor or Cordova. (On mobile device)
    if (isPlatform("hybrid")) {
      const file = await readFile({
        path: photo.path!,
      });
      base64Data = file.data;
    } else {
      base64Data = await base64FromPath(photo.webPath!);
    }

    await writeFile({
      path: fileName,
      data: base64Data,
      directory: FilesystemDirectory.Data,
    });
    return getPhotoFile(photo, fileName, base64Data);
  };

  const getPhotoFile = async (
    cameraPhoto: CameraPhoto,
    fileName: string,
    base64: string
  ): Promise<Photo> => {
    if (isPlatform("hybrid")) {
      // Get the new, complete filepath of the photo saved on filesystem
      const fileUri = await getUri({
        directory: FilesystemDirectory.Data,
        path: fileName,
      });

      // Display the new image by rewriting the 'file://' path to HTTP
      // Details: https://ionicframework.com/docs/building/webview#file-protocol
      return {
        filepath: fileUri.uri,
        webviewPath: Capacitor.convertFileSrc(fileUri.uri),
        base64,
      };
    }

    // Use webPath to display the new image instead of base64 since it's already loaded into memory
    return {
      filepath: fileName,
      webviewPath: cameraPhoto.webPath,
      base64,
    };
  };

  const deletePhoto = async (photo: Photo) => {
    // Remove this photo from the Photos reference data array
    const newPhotos = photos.filter((p) => p.filepath !== photo.filepath);

    // delete photo from filesystem
    const filename = photo.filepath.substr(photo.filepath.lastIndexOf("/") + 1);
    await deleteFile({
      path: filename,
      directory: FilesystemDirectory.Data,
    });
    setPhotos(newPhotos);
  };

  const selectPhoto = async (): Promise<void> => {
    const galleryPhoto = await getPhoto({
      resultType: CameraResultType.Uri,
      source: CameraSource.Photos,
      quality: 100,
    });
    const photo = {
      filepath: galleryPhoto.path ?? "",
      webviewPath: galleryPhoto.webPath,
      base64: galleryPhoto.base64String,
    };
    const newPhotos: Photo[] = [photo, ...photos];
    setPhotos(newPhotos);
  };

  return { photos, takePhoto, selectPhoto, deletePhoto };
}

1 post - 1 participant

Read full topic


Ionic 4 - Is possible to access a default app

$
0
0

This’s picture how to access default app setting



But I need this.

I want to programmatically a default app setting change a browser user’s device to google chrome Or redirect to default app setting page… also, Checking What’s browser are users currently using?

Thank you and sorry about my language is so bad :’(

2 posts - 2 participants

Read full topic

Using StreamingMedia to play RTMP stream

$
0
0

I’m attempting to use the StreamingMedia Plugin to stream a Facebook Live Stream. I’ll paste my code below, which is basically a copy/paste from the docs. Has anyone had any success using any player to stream a Facebook Live Stream?

const options: StreamingVideoOptions = {
  successCallback: () => { console.log('Video played') },
  errorCallback: (e) => { console.log(e) },
  orientation: 'portrait',
  shouldAutoClose: true,
  controls: false
};

this.streamingMedia.playVideo('rtmps://live-api-s.facebook.com:443/rtmp/1002093633573536?s_bl=1&s_psm=1&s_sc=1002094663573433&s_sw=0&s_vt=api-s&a=AbyTuvN0qkDDb9F3', options);

1 post - 1 participant

Read full topic

Streaming Facebook Live Video in Ionic

$
0
0

I’m trying to use videojs, videojs-flash, and videojs-flashls-source-handler, to play a Facebook Live Stream. I’ve tried about every combination I could think of to try and get this to work, but haven’t had any luck. The closest I’ve gotten is using the flash import for the videojs.options.flash.swf property. This loads what I think is flash (a large play button in the top left corner) but the browser blocks it. Even when allowing Flash it doesn’t work. I haven’t tried loading this up in an emulator yet but that’s my next step.

@capacitor/core 9.1.6
@ionic/angular 5
@capacitor/core 2.2.1
video.js 7.8.4
videojs-flash 2.2.1
@brightcove/videojs-flashls-source-handler 1.4.8

import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import videojs from 'video.js';
import flash from 'videojs-flash/dist/videojs-flash';

@Component({
  selector: 'app-video-js-player',
  templateUrl: './video-js.component.html',
  styleUrls: ['./video-js.component.scss'],
})
export class VideoJSComponent implements OnInit, OnDestroy {
  @ViewChild('target', { static: true }) target: ElementRef;
  
  @Input() options: {
    fluid: boolean;
    aspectRatio: string;
    autoplay: boolean;
    sources: {
      src: string;
      type: string;
    }[];
  };
  player: videojs.Player;

  constructor() {}

  ngOnInit() {
    const options = {
      techOrder: ['flash', 'html5'],
      aspectRatio: '9:16',
      autoplay: true,
      flash: {
        swf: '../node_modules/@brightcove/videojs-flashls-source-handler/dist/video-js.swf'
        //swf: flash
        //swf: '../node_modules/@brightcove/videojs-flashls-source-handler/dist/video-js.swf'
        //swf: 'https://unpkg.com/@brightcove/videojs-flashls-source-handler/dist/video-js.swf'
      },
      controls: true,
      sources: [
        { src: 'rtmps://live-api-s.facebook.com:443/rtmp/1002093633573536?s_bl=1&s_psm=1&s_sc=1002094663573433&s_sw=0&s_vt=api-s&a=AbyTuvN0qkDDb9F3', type: 'rtmp/flv' },
      ],
    };

    this.player = videojs(this.target.nativeElement, options, () => {
      console.log('onPlayerReady', this);
    });

    this.player.fill(true);
    this.player.responsive(true);
  }

  ngOnDestroy() {
    // destroy player
    if (this.player) {
      this.player.dispose();
    }
  }
}

1 post - 1 participant

Read full topic

Ionic 4 Code Obfuscation

$
0
0

i want to obfuscate my ionic 4 app after build to prevent reverse engineering. need suggestions or best way

1 post - 1 participant

Read full topic

Refresher component low frame rate

$
0
0

I using Ionics refresher component inside a ion-content component. I haven’t tested it on iOS yet, but on android (physical device) when pulling down the refresher, the frame rate of the refresher animation drops and the animation gets laggy. When letting it go in order to trigger the refresh, the animation runs smoothly as expected. Also in the browser the whole animation (pulldown and refresh) runs flawlessly.

Has anyone else observed this behavior?

Cap Doctor

💊   Capacitor Doctor  💊 

Latest Dependencies:

  @capacitor/cli: 2.4.2

  @capacitor/core: 2.4.2

  @capacitor/android: 2.4.2

  @capacitor/electron: 2.4.2

  @capacitor/ios: 2.4.2

Installed Dependencies:

  @capacitor/ios not installed

  @capacitor/electron not installed


  @capacitor/cli 2.0.1

  @capacitor/core 2.4.2

  @capacitor/android 2.4.2

[success] Android looking great! 👌

Angular version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/
    

Angular CLI: 10.1.3
Node: 13.14.0
OS: linux x64

Angular: 10.1.3
... cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1000.8
@angular-devkit/build-angular   0.1000.8
@angular-devkit/core            10.0.8
@angular-devkit/schematics      10.0.8
@schematics/angular             10.0.8
@schematics/update              0.1001.3
rxjs                            6.5.5
typescript                      3.9.7

Ionic Version

6.11.9

1 post - 1 participant

Read full topic

Ionic 5 camera photo corrupted

$
0
0

I have this code:
takePicture() {

const options: CameraOptions = {

  quality: 40,

  allowEdit: true,

  correctOrientation: false,

  targetWidth: 200,

  targetHeight: 200,

  destinationType: this.camera.DestinationType.FILE_URI,

  encodingType: this.camera.EncodingType.PNG,

  mediaType: this.camera.MediaType.PICTURE,

  sourceType: this.camera.PictureSourceType.CAMERA    

}

  this.camera.getPicture(options).then(async (imageData) => {

    var thisResult = JSON.parse(imageData);

    this.imageURI_1 = imageData;

    this.imageURI   = thisResult.filename;

    console.log(imageData);

    //this.imageFileName = this.webview.convertFileSrc(imageData);

    const tempFilename =  this.imageURI.substr( this.imageURI.lastIndexOf('/') + 1);

    const tempBaseFilesystemPath =  this.imageURI.substr(0,  this.imageURI.lastIndexOf('/') + 1);

            

    this.file.checkDir(cordova.file.dataDirectory, 'fotos/').then(_ => console.log('yay'))

    .catch(err => {

        this.file.createDir(cordova.file.dataDirectory, 'fotos/', false).then(()=>{

        }).catch((err)=>{

        });

    });          

    

    const newBaseFilesystemPath = cordova.file.dataDirectory+'fotos/';

    await this.file.copyFile(tempBaseFilesystemPath, tempFilename, newBaseFilesystemPath, tempFilename);

    

    const storedPhoto = newBaseFilesystemPath + tempFilename;

    //const displayImage = this.webview.convertFileSrc(storedPhoto);

    

    //file:///

    this.imageURI = storedPhoto.substr(7,storedPhoto.length);

    this.imageFileName =  this.webview.convertFileSrc(storedPhoto);

    //const resolvedImg = this.webview.convertFileSrc(storedPhoto);

    //this.imageFileName = this.sanitizer.bypassSecurityTrustUrl(this.imageFileName);

      this.ftp.connect('ftp.geacademia.com.br', 'geacademia2', 'Cmm1606799!acad').then(async () => {

          const loading = await this.loadingCtrl.create({

            message: 'Aguarde...',

            duration: 2000

          });

          await loading.present();

            

          let nome_arquivo = '/public_html/alliance/camera/user_'+this.cadcliente.USERAPP.toString()+'.png';

          this.ftp.upload(this.imageURI.toString(), nome_arquivo).subscribe(result => {

              this.ftp.disconnect().then(async () => {

                  const { role, data } = await loading.onDidDismiss();

                  console.log('Loading dismissed!'); 

                  this.presentToast("Imagem Carregada com Sucesso");

                  this.cadcliente.FOTO = 'http://geacademia.com.br/alliance/camera/user_'+this.cadcliente.USERAPP.toString()+'.png';

              }, (err) => {

                  console.log("ERROR: " + JSON.stringify(err));

              });

          }, (err) => {

              this.presentToast(JSON.stringify(err));

          });

      }, (err) => {

          //this.status_proc = "";

          //this.status_proc = "Erro ao Enviar Arquivo...";

      });

  }, (err) => {

      console.log(err);

      this.presentToast(err);

  });

}

to take photo at Android works perfectly, but at Iphone, I have this problem!

user_Thiago Almeida_871|200x200

image did not saved correctly at my server

2 posts - 1 participant

Read full topic

Ionic slides in react

$
0
0

hey, I figured out how to use ion-slides slideTo or nextSlide method.

this can be simply done by creating a react reference.

1 post - 1 participant

Read full topic


Ionic serve doesn't work in Safari Browser

$
0
0

Ionic Serve does not work on Safari web browser

Hi, I am having problems with testing my app on Safari as it does not go past the first loaded page.
No error is logged in the console, page reloads whenever an click event is called.
Ionic:
I am using:

   ionic (Ionic CLI)             : 4.5.0 (/usr/local/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 5.3.2
   @angular-devkit/build-angular : 0.900.7
   @angular-devkit/schematics    : 9.0.7
   @angular/cli                  : 9.0.7
   @ionic/angular-toolkit        : 2.2.0 ```

Any suggestions will be highly appreciated, thanks

1 post - 1 participant

Read full topic

Vue "watch"

$
0
0

I want a VueJS function (fetchDataFromAPI) to run every time the page loads.

This code works in the browser, but not in the Android emulator:

watch: {
    '$route': 'fetchDataFromAPI',
},

Any suggestions what to try?

1 post - 1 participant

Read full topic

Ion-datetime: How to add meaningful suffix(es) + feature request

$
0
0

I would like to display the ion-datetime picker with suffixes, like this:

19.12.19 14:39

Using pickerFormat obviously does swallows the separators (the dot as well as the colon), when defined like this:

D.M.YY HH:mm

This documentation [1] shows a way to add suffixes to ion-picker. However, I will not build my own datetime-picker from the bottom up just to get suffixes.

So … in my current code, I tried to use the pickerOptions attribute, hoping to be able to set some suffixes, but no joy. Part of the problem is the mandatory name attribute of a PickerColumn, I guess.

bla.html

<ion-datetime
          placeholder="Select a date"
          displayFormat="D.M.YYYY HH:mm"
          pickerFormat="D.M.YY HH:mm"
          formControlName="taskStartAt"
          [pickerOptions]="pickerOptions"
          (ionChange)="onTaskStartAtChanged($event)"
          [min]="taskService.taskStartMin"
          [max]="taskService.taskStartMax"
        ></ion-datetime>
bla.ts

pickerOptions = {
    animated: false,
    columns: [
      {
        suffix: '.',
      },
      {
        suffix: '.',
      },
      {
        suffix: '.',
      },
      {
        suffix: '.',
      },
      {
        suffix: '.',
      },
      {
        suffix: '.',
      },
    ],
  };

Idea: add the attribute to ion-datetime to keep the separators and show them in non-selectable columns.

pickerFormatKeepSeparator="true"

[1] https://www.learmoreseekmore.com/2020/01/ionic-picker-sample-code-in-angular.html

1 post - 1 participant

Read full topic

In-app purchases v2 don't work in ios 14

Finally made a breakthrough passing data to a component - felt I should share

$
0
0

First I would like to say how I appreciate this forum, and the support crew who are so helpful in answering so many small questions. I tend not to write much - but I spent many hours on so many days searching for the answer to the many questions that naturally arise while programming.

I am a long time programmer - started back in 1974! - but I only started programming ionic/angular four months ago - so I consider myself a skilled newbie. I’m working on a project, and mostly have made good progress, but I find programming in Ionic/Angular very frustrating! The main frustration seems to come from things that an instructor in a course says will work not working. An example of that is the topic of this post “Passing data to a component via html”

I needed to figure this out - and several months ago I spent more than a week trying everything, without success. I finally figured out how to use a service as an exchange - so a component could “ask” what data it was to use by calling the service which the parent had nicely loaded up with data. I consider this a kludge.

Today, finally! I figured out a method that worked - which is what I felt I should share.

In html I had tried to pass data to the child using [myID]=“item.id.”

Then, as everyone said to do - I used @Input(‘myID’) to bind a component variable to that ID.

I only saw the ID as “undefined” which made me crazy.

Then, today, I saw someone in a forum (stack overflow…) make a slight comment:

“use ngAfterContentInit to get the data - not ngOnInit”

This was what I needed to see - the data is undefined in ngOnInit - but is valid in ngAfterContentInit!

So frustrating that I spent weeks struggling with this - finally writing a kludge work around - but now it works, thanks to some wise soul writing in a random post in a random forum.

Just thought I would share.

thanks for your time - and thanks to all those who are so helpful to all who struggle.

4 posts - 2 participants

Read full topic

How to get page to refresh when I change an image

$
0
0

I’ve worked on this problem for a while - and finally just decided to move on - but I thought perhaps if I posted the problem, someone would provide some insight.

I’ve found that I need to trust that angular will update the page when I change underlying data - but so far I’ve not figured out how to make this particular problem work.

I have a profile page where a user can change his profile picture. The html to display the image is this:

<img [src]=“userProfileURL” class=“avatar”>

In the TS file, after the user changes the picture - I go to a lot of work to change the path (userProfileURL) several times - but once it’s set to the new URL - the page does not refresh, and the old picture remains in view

This is not acceptable, but I’m not sure how to make this work.

Any ideas? Thanks very much in advance!

2 posts - 2 participants

Read full topic

How to use SelectOption?

$
0
0

Okay, this is probably a stupid question, but I’m brand new to this and struggling…

If I add an IonSelect, how do I use the selected information? It has this in it:
onIonChange={e => setSubject(e.detail.value)}

So, I assume I can create a function setSubject(e), and then do something with the ‘e’ value, but I can’t figure out where to put it or how to make it work? I’m familiar with javascript and jquery and such for websites, but this is just different enough that I can’t figure it out… Help!

Thanks.

1 post - 1 participant

Read full topic


Unable to clear pages on stack

$
0
0

I am unable to clear pages on stack after logging out, have used this.navCtrl.navigateRoot(’/home’);.
I have been redirected to home page, but when I click on the back-button in the browser, app got redirected to the previous page.

1 post - 1 participant

Read full topic

Ionic 5 - console.log in Android Emulator

$
0
0

I’m not seeing my console.log statements in the Android emulator, I’m pretty sure I was seeing them previously?

I have compiled and released a production version of the app since I was last debugging, is there something I need to do to see the console.log output again??

1 post - 1 participant

Read full topic

How to close ion-item-sliding when lost focus?

$
0
0

I want to close the ion-item-sliding when user swipe on a item to see the options but then focus on some other element for example - click on a button, or want to input in a text input. So basically if user lost the focus or click/touch somewhere else after swipe to open the ion-item-sliding it should get close.

4 posts - 3 participants

Read full topic

Trying to make a Telnet connection to send messages to local hardware

$
0
0

Hi Guys,

I jus started with Ionic and got a bluetooth connection working for a hardware device which needs controlling by an app.
Now my client wanted to do the same with a WiFi system using Telnet.

I found several things on the internet about it but no clear answer if you can do it and if so how you can.

Anyone here could help me out?

Thanks!

1 post - 1 participant

Read full topic

Get Timezone with Intl : iOS, Android, Browser

$
0
0

Using Ionic, is this the correct method to get the timezone for iOS, Android as well as the browser:

Intl.DateTimeFormat().resolvedOptions().timeZone

I am new to App development and I am not sure if the browser object Intl is available in Ionic when deployed as an App.

1 post - 1 participant

Read full topic

Viewing all 49418 articles
Browse latest View live


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