Using Media Capture plugin with iOS error IONIC: Failed to load resource: unsupported URL

Hey Ionites in desperate need of your insight on this issue. using camera review plugin to capture multiple images in succession then display the last image on screen before proceeding to the next screen. The images are supposed to upload to firebase and the last one I take a screenshot of so I can track progress. When I take the screenshot it uploads to firebase fine but the 5 images preceding it do not upload I get the following error

this seems to be an issue on these web communities http://technology.ezeenow.com/Posts/146690/Failed_to_load_resource_unsupported_url

All the solutions I found only work for ionic 1.x.x nothing for ionic 2 or 2.3…
Any insight and I mean anything at all would be greatly appreciated.

Chuck

1 Like

@mharington I need youuuuuu :frowning:

This application works fine on Android platform fyi

May I see:

How you’re displaying the image in HTML and the corresponding typescript?

Sure thing!!

Html

<ion-content >

  <button  *ngIf="showScreenshtoButton" class="wood-border" style="position: absolute; height: 100vh; width: 100%; left: 0; top: 0;">

  </button>


    <img *ngIf="pictureUrl" width="500px" height="cover" [src]="pictureUrl ">



</ion-content>

import { Component, NgZone } from '@angular/core';
import { NavController, ModalController, NavParams } from 'ionic-angular';
import { Screenshot, CameraPreview } from 'ionic-native';
import { Observable } from 'rxjs/Rx';
import  firebase from 'firebase';
import { BackgroundMode } from 'ionic-native';
import { Platform } from 'ionic-angular';
import { Camera, File, MediaCapture, MediaFile, CaptureError, CaptureImageOptions } from 'ionic-native';
import { mSocialShare } from '../../modals/mSocialShare/mSocialShare';
import { AuthData } from '../../providers/auth-data';


@Component({
    selector: 'page-swip',
    templateUrl: 'swip.html'
})
export class SwipPage {

    timer;
    timerSubscription;
    pictureUrl: string = '';
    screenshots = firebase.storage().ref('/shots/');
    baseFileName = "";
    screenshotCounter = 0;
    showScreenshtoButton = false;

    constructor(public authData: AuthData, private zone: NgZone, public modalController: ModalController, public navCtrl: NavController, public params: NavParams, public platform: Platform) {

        this.timer = Observable.timer(0, 2800);

        // this.startPreview();

    }


    startPreview() {


        let tapEnabled: any = false;
        let dragEnabled: any = false;
        let toBack: any = true;
        let alpha = 1;
        let rect: any = {
            x: 0,
            y: 0,
            width: this.platform.width(),
            height: this.platform.height()
        };

        CameraPreview.startCamera(
            rect,
            "front",
            tapEnabled,
            dragEnabled,
            toBack,
            alpha
        );

        // this.startScreencapture();

    }

    stopPreview() {

        CameraPreview.stopCamera();

        // this.stopScreencapture();

    }

    refresh() {
        window['location'].reload();
    }

    guid() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
    }

    takeScreenshot() {

        Screenshot.URI(80).then(res => {
            console.log(res);
            this.getBlob(res.URI)
                .then((blob) => {
                    console.log("upload");
             firebase.storage().ref('/shots/').child( firebase.auth().currentUser.uid)
                 .child("last_screenshot.jpg")
                    .put(blob)
                    .then((savedPicture) => {
                        console.log("last saved to fire");
                    }).catch(err=>{console.log(err);});



                });
            this.openModal(res.URI);
        })
            .catch(() => console.error("screenshot error"));



    }

    savePic(mediaFile, screenshotCounter) {
        //let filePath = mediaFile.substring(0, mediaFile.lastIndexOf('/'));
        let fileName = "picture_"+screenshotCounter+".jpg";
        //console.log(filePath);
        console.log(fileName);

        this.getBlob(mediaFile)
            .then((blob) => {


                 firebase.storage().ref('/shots/').child( firebase.auth().currentUser.uid)
                 .child(fileName)
                    .put(blob)
                    .then((savedPicture) => {
                        console.log("saved to fire");
                    }).catch(err=>{console.log(err);});

            });

    }

    getBlob(url) {
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest();
            xhr.responseType = 'blob';
            xhr.onload = (event) => {
                var blob = xhr.response;
                resolve(blob);
            };
            //xhr.onerror = reject();
            xhr.open('GET', url);
            xhr.send();
        })
    }

    startCamera() {

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

            this.platform.ready().then(() => {


                let tapEnabled: any = false;
                let dragEnabled: any = false;
                let toBack: any = true;
                let alpha = 1;
                let rect: any = {
                    x: 0,
                    y: 0,
                    width: this.platform.width(),
                    height: this.platform.height()
                };

                CameraPreview.startCamera(
                    rect,
                    'front',
                    tapEnabled,
                    dragEnabled,
                    toBack,
                    alpha
                );

                resolve();


            });

        });


    }
    ngAfterViewInit() {

        this.takePicture2();

        setTimeout(() => {
            this.takePicture2()
        }, 2000)
    }

    takePicture2() {

        this.startCamera().then(() => {


            this.screenshotCounter = 1;

            this.baseFileName = "picture";

            CameraPreview.takePicture({ maxWidth: 300, maxHeight: 300 });

            CameraPreview.setOnPictureTakenHandler().subscribe(pic => {

                this.savePic(pic[1], this.screenshotCounter);

                console.log(this.screenshotCounter);

                setTimeout(() => {

                    if (this.screenshotCounter >= 5) {

                        this.zone.run(() => {

                            this.pictureUrl = pic[1];
                            console.log(this.pictureUrl);
                            CameraPreview.stopCamera();
                            setTimeout(() => {
                                this.showScreenshtoButton = true
                            }, 2000);
                        });

                    } else {

                        this.screenshotCounter += 1;

                        CameraPreview.takePicture({ maxWidth: 300, maxHeight: 300 });

                    }
                }, 2000);

            });

        });


    }

    takePicture() {


        this.baseFileName = this.guid();

        this.captureScreenshot();

        this.screenshotCounter += 1;

        setTimeout(() => {
            this.captureScreenshot();
        }, 1000);

        this.screenshotCounter += 1;


        setTimeout(() => {
            this.captureScreenshot();
        }, 1000);


    }

    takePhoto() {

        this.baseFileName="picture";
        var counter = 1;

        this.captureMedia().then((mediaFiles: Array<any>) => {

            mediaFiles.forEach(mediaFile => {
                let filePath = mediaFile.fullPath.substring(0, mediaFile.fullPath.lastIndexOf('/'));
                File.readAsDataURL(filePath, mediaFile.name).then((blob: string) => {
                    this.screenshots.child('camera').child(this.baseFileName + '_' + counter + '.jpg').putString(blob.substring(23), 'base64', { contentType: 'image/jpeg' });
                    counter += 1;
                }, (err) => {
                    console.log('Error converting file to base64', err);
                })
                console.log(mediaFile);
            });

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


    }

    captureMedia() {

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

            let options: CaptureImageOptions = { limit: 3 };

            MediaCapture.captureImage(options)
                .then(
                (data: MediaFile[]) => resolve(data),
                (err: CaptureError) => reject(err)
                );

        });


    }

    openCameraPreview() {

        /*
         let tapEnabled: any = false;
         let dragEnabled: any = false;
         let toBack: any = true;
         let alpha = 1;
         let rect: any = {
         x: 0,
         y: 0,
         width: this.platform.width(),
         height: this.platform.height()
         };

         CameraPreview.startCamera(
         rect,
         'rear',
         tapEnabled,
         dragEnabled,
         toBack,
         alpha
         );
         CameraPreview.takePicture({maxWidth:640, maxHeight:640});

         CameraPreview.setOnPictureTakenHandler().subscribe((pic) => {
         console.log(pic);
         })

         CameraPreview.stopCamera();
         */

    }

    openCamera() {

        Camera.getPicture({
            quality: 95,
            destinationType: Camera.DestinationType.DATA_URL,
            sourceType: Camera.PictureSourceType.CAMERA,
            allowEdit: false,
            encodingType: Camera.EncodingType.PNG,
            targetWidth: 500,
            targetHeight: 500,
            saveToPhotoAlbum: false
        }).then(imageData => {
            console.log(this.baseFileName + '.png');

            if (imageData  != null) {

              firebase.storage().ref('/shots/').child( firebase.auth().currentUser.uid).child('Picture'+this.screenshotCounter+'.png')
                    .putString(imageData, 'base64', { contentType: 'image/png' })
                    .then((savedPicture) => {
                        console.log("saved to fire");
                    }).catch(err=>{console.log(err);});
            }

            this.stopScreencapture();
        }, error => {
            console.log("ERROR -> " + JSON.stringify(error));
            this.stopScreencapture();
        })

    }

    startScreencapture() {

        this.screenshotCounter = 0;

        this.timerSubscription = this.timer.subscribe(t => {
            this.screenshotCounter += 1;
            this.captureScreenshot();
        });

    }

    stopScreencapture() {

        this.screenshotCounter = 0;

        this.timerSubscription.unsubscribe();

    }

    captureScreenshot() {

        //Save screenshot to firebase storage
        Screenshot.URI(80).then((screenshot) => {
            let imageData = screenshot.URI;
            console.log('saving screeshot..')

            if (imageData  != null) {


               firebase.storage().ref('/shots/').child( firebase.auth().currentUser.uid).child('Picture'+this.screenshotCounter+'.png')
                    .putString(imageData, 'base64', { contentType: 'image/png' })
                    .then((savedPicture) => {

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

//            this.screenshots.child('screenshots').child(this.baseFileName + '_' + this.screenshotCounter + '.jpg').putString(imageData, 'base64', { contentType: 'image/jpeg' });
        });

    }

    openModal(lastFilePath: any) {

        setTimeout(() => {
            let modal = this.modalController.create(mSocialShare, { filePath: lastFilePath });
            modal.present();
        })
    }

}


Also I want to mention the code works on android perfectly. Though its sloppy V_V. Just iOS. I’m looking up stuff about unsafe urls I think it has to do with that
https://angular.io/docs/ts/latest/guide/security.html#!#xss

How to post code.

Thank you kind sir, that threw me for a loop

Incidentally, your guid() function isn’t RFC 4122 compliant. I would recommend installing the ‘uuid’ npm module and using its v4() function instead.

changes made same error. I didnt even consider the guid() function since it worked on android.
Is there any content policy, or config.xml configuration i am missing when it comes to IOS10 and up. The application takes the photos and its supposed to upload to firebase however instead it saves to the gallery I cant shake the feeling it has to do with some kind of external permissions strictly for ios since it works on android.

found this but implementing into angular is my issue

looks like cordovan-plugin-file issue
Even after updating I am getting the same error

@trevaun23 @mhartington @Gajotres @rapropos @bengtler is there any ionic or Cordova version of this converter

I can use seems to be exactly what I need. Any input would be greatly appreciated

@seanhill you got the magic touch

@Sujan12 any thoughts?

First off, sorry for the late reply.

Basically, using the FIleOpener and converting to base64 won’t work?

Thanks for getting tome. Yeah i had to give up on getting this to work… With the asset-library being depracated my code just wasn’t compatible for ios

Oh depreciated? I had no idea… I don’t code for iOS that much so I’m unfamiliar with the file system, but alright. I would be able to help more effectively in Android based problems though. Just letting you know.

Thanks Mate i appreciate your help . Definitely was a learning experience trying to figure it out for 2-3 months

1 Like