Capacitor Camera API throws error when running on web - ionic4

I am following the instructions for Capacitor Camera APi https://capacitor.ionicframework.com/docs/guides/ionic-framework-app
The plugin works fine when running the application on an android device ionic capacitor run android -l but when serving the app on web I am getting this runtime error:
core.js:15724 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'split' of undefined
TypeError: Cannot read property 'split' of undefined
at camera.js:62
at new ZoneAwarePromise (zone.js:910)
at CameraPluginWeb.push../node_modules/#capacitor/core/dist/esm/web/camera.js.CameraPluginWeb._getCameraPhoto (camera.js:60)
at CameraPluginWeb.<anonymous> (camera.js:40)
at step (tslib.es6.js:99)
at Object.next (tslib.es6.js:80)
at tslib.es6.js:73
at new ZoneAwarePromise (zone.js:910)
at Module.__awaiter (tslib.es6.js:69)
at HTMLElement.<anonymous> (camera.js:29)
at resolvePromise (zone.js:831)
at zone.js:741
at rejected (tslib.es6.js:71)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
at Object.onInvoke (core.js:17299)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:390)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:150)
at zone.js:889
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Object.onInvokeTask (core.js:17290)
This is my code:
import {Injectable} from '#angular/core';
import {from, Observable} from 'rxjs';
import {CameraOptions, CameraResultType, CameraSource, Plugins} from '#capacitor/core';
const { Camera } = Plugins;
#Injectable()
export class MediaService {
takePhoto(): Observable<string | void> {
const options: CameraOptions = {
quality: 100,
allowEditing: false,
source: CameraSource.Camera,
resultType: CameraResultType.Base64
};
return from(Camera.getPhoto(options).then(photo => {
return 'data:image/png;base64,' + photo.base64String;
}).catch(err => {
console.error('Error: ', err);
}));
}
}
I also added these in main.ts
import { defineCustomElements } from '#ionic/pwa-elements/loader';
// Call the element loader after the platform has been bootstrapped
defineCustomElements(window);
Is there anything i am doing wrong or this is a bug in Capacitor Camera API

The problem is the camera can't be used from http, it needs https. Try running with ionic serve --ssl and update the capacitor.config.json to use the https url
"server": {
"url": "http://192.your.local.ip:8100"
}

If you are using Ionic With Capacitor then this is for you
1)install pwa element
"#ionic/pwa-elements": "^1.4.1",
2)In your main.ts file add this line
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
// Call the element loader after the platform has been bootstrapped
defineCustomElements(window); // add this line

Related

Svelte/ Rollup Error “missing global variable name”

When I am importing "AmazonCognitoIdentity" in my Routify project I am getting "missing global variable name" error.
Error message:
bundles src/main.js  dist\build\bundle.js...
LiveReload enabled
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
/js/amazon-cognito-identity.min.js (imported by src\pages\_components\Login.svelte)
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
/js/amazon-cognito-identity.min.js (guessing 'amazonCognitoIdentity_min_js')
created dist\build\bundle.js in 2.7s
bundles src/sw.js  dist\sw.js...
created dist\sw.js in 1.6s
Following is my code
import { AmazonCognitoIdentity } from "/js/amazon-cognito-identity.min.js";
const authenticationData = {
Username: userName,
Password: password,
};
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
authenticationData
);
console.log(authenticationDetails);
const poolData = {
UserPoolId: "xxxx”
ClientId: "xxxxxxx",
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
const userData = {
Username: userName,
Pool: userPool,
};
console.log(userData);
const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
const accessToken = result.getAccessToken().getJwtToken();
console.log(`on sucess: ${accessToken}`);
},
onFailure: function (err) {
console.log(`onfailure: ${err}`);
console.log(err);
},
});
and also I’ve linked the following file in _index.html
<script src="./js/amazon-cognito-identity.min.js"></script>
<script src="./js/amazon-cognito-auth.min.js"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>
And the same process in working good in normal Html ad JavaScript files.
npm i amazon-cognito-identity-js
run this command first then update your import to this:
import { AmazonCognitoIdentity } from 'amazon-cognito-identity-js';
Flowing error is thrown after incorporating
npm i amazon-cognito-identity-js
import { AmazonCognitoIdentity } from 'amazon-cognito-identity-js';
ERROR:
(!) Plugin node-resolve: preferring built-in module 'buffer' over local alternative at 'E:\ec-website\htx-pp-client\node_modules\buffer\index.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
buffer (imported by node_modules\amazon-cognito-identity-js\es\AuthenticationHelper.js, node_modules\amazon-cognito-identity-js\es\CognitoUser.js, node_modules\amazon-cognito-identity-js\es\CognitoJwtToken.js)
[!] Error: 'AmazonCognitoIdentity' is not exported by node_modules\amazon-cognito-identity-js\es\index.js, imported by src\pages_components\Login.svelte
After adding this line to rollup.config.js
rollup.external = ["AmazonCognitoIdentity", "amazon-cognito-identity-js"];
rollup.output = {
file: "dist/build/bundle.js",
format: "umd",
interop: "esModule",
globals: {
"amazon-cognito-identity-js": "AmazonCognitoIdentity",
},
};
The above error is gone. But at run time throws a new error
Uncaught TypeError: Cannot read property 'AmazonCognitoIdentity' of undefined
I got past this error by adding
import polyfills from "rollup-plugin-node-polyfills";
...
plugins: [
polyfills(),
...
to my rollup.config.js
My guess is, you need to change the import statement so that it is relative:
import { AmazonCognitoIdentity } from "./js/amazon-cognito-identity.min.js";
I don't know where this file is, but you need to have . or .. at the start of the location.
As I'm not an expert I yet cannot explain you why.
import AmazonCognitoIdentity from 'amazon-cognito-identity-js';
Is your import correct?

TypeError Object is not a constructor (evaluating new_pubnubReact.default')

I am new to react native and am trying to create push notifications for android.
I am using the following tutorial from PubNub.
PubNub tutorial
When I run my app in the android studio emulator after finishing the tutorial I get the following error.
Not quite sure what it means of how to fix it as when I google the problem nothing comes up.
Here is my code
import React from 'react';
import PushNotificationIOS from 'react-native';
import PubNubReact from 'pubnub-react';
const PushNotification = require('react-native-push-notification');
export default class App extends React.Component {
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR_PUBNUB_PUBLISH_KEY_HERE',
subscribeKey: 'YOUR_PUBNUB_SUBSCRIBE_KEY_HERE'
});
this.pubnub.init(this);
PushNotification.configure({
// Called when Token is generated.
onRegister: function(token) {
console.log( 'TOKEN:', token );
if (token.os == "ios") {
this.pubnub.push.addChannels(
{
channels: ['notifications'],
device: token.token,
pushGateway: 'apns'
});
// Send iOS Notification from debug console: {"pn_apns":{"aps":{"alert":"Hello World."}}}
} else if (token.os == "android"){
this.pubnub.push.addChannels(
{
channels: ['notifications'],
device: token.token,
pushGateway: 'gcm' // apns, gcm, mpns
});
// Send Android Notification from debug console: {"pn_gcm":{"data":{"message":"Hello World."}}}
}
}.bind(this),
// Something not working?
// See: https://support.pubnub.com/support/solutions/articles/14000043605-how-can-i-troubleshoot-my-push-notification-issues-
// Called when a remote or local notification is opened or received.
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// Do something with the notification.
// Required on iOS only (see fetchCompletionHandler docs: https://reactnative.dev/docs/pushnotificationios)
// notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// ANDROID: GCM or FCM Sender ID
senderID: "sender-id",
});
}
}
pubnub-react library has been completely changed in version 2.0.0. It no longers includes pubnub JavaScript SDK by default so you have to install it as well.
Here is the link to new PubNub React repository, and in the README.md file you can find examples on how to use it.
If you want to use the older version that is compatible with the tutorial/blog post you may be reading, please install the older version of the PubNub React SDK like so:
$ npm install pubnub-react#1
To summarize the changes, pubnub-react now uses Context and Hooks API to propagate PubNub instance deep into the children tree.
Provider
You need to include the provider somewhere top in the component tree.
import React from 'react'
import PubNub from 'pubnub'
import { PubNubProvider } from 'pubnub-react'
const pubnub = new PubNub({}) // PubNub configuration
export const App = () => {
return <PubNubProvider client={pubnub}>
<Child />
</PubNubProvider>
}
Consumer
To use the PubNub instance somewhere else, you can now just use the usePubNub hook.
import { usePubNub } from 'pubnub-react'
export const Child = () => {
const pubnub = usePubNub()
return <div>I am using PubNub!</div>
}

Not receiving fcm message when app is close in Android with react-native-firebase

I followed the steps mentioned here.
Now, I'm receiving messages when the app is in foreground via firebase.messaging().onMessage and in the background, via a headless task I defined according to the same guide, but I don't receive messages when the app is closed
I am using one plus 6, where I even disabled the Battery optimize option for my phone, tried installing a signing build but none of it is working.
This is my bgMessaging.js
import firebase from 'react-native-firebase';
// Optional flow type
import type { RemoteMessage } from 'react-native-firebase';
export default async (message: RemoteMessage) => {
const channel = new firebase.notifications.Android.Channel('channel-id', 'channel-Name', firebase.notifications.Android.Importance.Max)
.setDescription('Description');
firebase.notifications().android.createChannel(channel);
const localNotification = new firebase.notifications.Notification()
.setNotificationId(message.messageId)
.setTitle("Title")
.setSubtitle('Test')
.setBody("Body")
.setData(message.data)
.android.setChannelId('channel-id')
.android.setAutoCancel(false)
.android.setPriority(firebase.notifications.Android.Priority.High);
firebase.notifications().displayNotification(localNotification);
return Promise.resolve();
}
Even added this on AndroidManifest.xml
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
Am I missing anything on native side?
You can go to http://pushtry.com/ and set the jSON as :
{
"to":FCM_TOKEN
"notification": {
"body": "body",
"title": "title"
},
"priority":'high'
}

React-Native aws-amplify PubSub error

import Amplify, { Auth } from 'aws-amplify'
import config from './aws-exports'
import { PubSub } from 'aws-amplify';
import { AWSIoTProvider } from 'aws-amplify/lib/PubSub/Providers';
...
PubSub.subscribe('myTopicTest').subscribe({
next: data => console.log('Message received', data),
error: error => console.error(error),
close: () => console.log('Done'),
});
The call to PubSub.subscribe throws :
TypeError: One of the sources for assign has an enumerable key on the prototype chain. Are you trying to assign a prototype property? We don't allow it, as this is an edge case that we do not support. This error is a performance optimization and not spec compliant.
Reference :
https://github.com/aws/aws-amplify/issues/750
Does anybody has a workaround or solution for this error?
Thanks

How to pass data to push notification with react native

Im using
React Native Push Notification https://github.com/zo0r/react-native-push-notification
How can I pass my pushMessage(chat) into the notification?
I have this onNotification and PushNotificationIOS error when received push message from server.
error on device
which part should I work on?
ps: im not understand how this work -> notification.finish(PushNotificationIOS.FetchResult.NoData);
App.js
--------
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// process the notification
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
});
class App extends Component{
componentDidMount(){
const connection = signalr.hubConnection('https://api.abc.com');
const proxy = connection.createHubProxy('chatHub');
proxy.on('pushMessage', (chat) => {
PushNotification.localNotificationSchedule({
message: "My Notification 1",
date: new Date(Date.now())
});
});
}
}
PushNotificationIOS is an API provided by react-native so maybe you import it from react-native like so
import { PushNotificationIOS } from 'react-native'
PushNotification uses PushNotificationIOS. You have to add and import it.
Do the following.
In the console, run this if using Yarn: yarn add #react-native-community/push-notification-ios...
... or run this if using NPM: npm install #react-native-community/push-notification-ios
Then, in your file where you use PushNotification, add this line among your other imports:
import PushNotificationIOS from "#react-native-community/push-notification-ios"