Ionic app doesn't ask permission to access location while installing - ionic-framework

I've followed the following steps to create an app:
ionic start ionic-maps blank
cd ionic-maps
ionic setup sass
ionic io init
ionic platform add android
bower install ngCordova
Added the following lines to index.html:
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
Changed app.js to include ngCordova:
angular.module('starter', ['ionic', 'starter.controllers', 'ngCordova'])
Installed the geolocation plugin:
cordova plugin add cordova-plugin-geolocation
app.js:
.state('app.location', {
url: '/location',
views: {
'menuContent': {
templateUrl: 'templates/location.html',
controller: 'LocationCtrl'
}
}
})
location.html:
<ion-view view-title="Search">
<ion-content>
<h1>Location: {{location}}</h1>
</ion-content>
</ion-view>
controllers.js:
.controller('LocationCtrl', function($scope, $state, $cordovaGeolocation) {
$scope.location = 'Waiting';
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log(lat, lng);
$scope.location = lat + ' ' + lng;
}, function(error) {
console.log('Could not get location: ', error);
$scope.location = 'Could not get location: ' + error + ' :: ' + JSON.stringify(error);
});
})
If I open the /location endpoint in my phone's browser (using ionic serve) I'm shown my current location correctly. So far everything works as expected.
/platforms/android/AndroidManifest.xml has the following lines in it:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I'm building the app using the new cloud package builder using ionic package build android. ionic package list shows that the build was successful.
I expected that I'll be asked for location permission while installing the app from apk. But I'm only asked for full network access. On visiting the /locations screen I get an error [object PositionError. json.stringify(error) is {} and Object.keys(error).length is 0.
Using navigator.geolocation.getCurrentPosition instead of $cordovaGeolocation.getCurrentPosition doesn't help.
alert(error.code) is 2 and alert(error.message) is application does not have sufficient geolocation permisions.
PS: I've ensured that GPS is enabled and it works on other apps.

Run cordova plugin add cordova-plugin-geolocation with --save option i.e. cordova plugin add cordova-plugin-geolocation --save so that the plugin gets added to config.xml.
Alt: adding "cordova-plugin-geolocation" to "cordovaPlugins" in package.json also solves the issue but has been deprecated.

Related

Ionic v5 web media capture with capacitor - cordova_not_available

I am building an app with Ionic 5, Capacitor 2 and Angular 11.
I need to capture video and audio using the media capture cordova plugin.
I installed the following modules:
npm install cordova-plugin-media-capture
npm install #ionic-native/media-capture
And added MediaCapture to the providers of my app module.
Then I call mediaCapture.captureVideo() to retrieve a video ; unfortunately an exception is thrown when testing on a browser: cordova_not_available
The github repo states this plugin is web-compatible, and its sources have a browser implementation. However the window.navigator.device.capture is missing to make this plugin work.
Is it a bad configuration from my side? Or this cordova plugin wouldn't be compatible with capacitor?
I made a repro : https://stackblitz.com/edit/ionic-v5-media-capture-capacitor?file=src/app/app.component.ts
Thank you for your help
I wrote a regular Angular version for the web, if anyone need it:
async browserCapture() {
const stream: MediaStream = await navigator.mediaDevices.getUserMedia(this.constraints);
const recorder = new MediaRecorder(stream, {mimeType: 'ogg'});
const chunks: Blob[] = [];
recorder.ondataavailable = (event: BlobEvent) => {
if (event.data && event.data.size > 0) {
chunks.push(event.data);
this.zone.run(() => {
this.recordChunks = [...chunks];
this.cd.markForCheck();
});
}
};
this.recorder.onstop = () => {
this.zone.run(() => {
stream.getTracks().forEach(t => t.stop());
if (chunks?.length) {
this.upload(new Blob(chunks, {type: 'ogg'})); // use the blob result
}
});
};
recorder.start(500);
}

Ionic native Transfer plugin's `file.dataDirectory` shows error

I'm going to use the Ionic native Transfer plugin as shown below.
Problem is here this.file.dataDirectory.It shows error like [ts] Property 'dataDirectory' does not exist on type 'File'..Can you tell me what is the solution for this?
download() {
const fileTransfer: TransferObject = this.transfer.create();
const url = 'http://www.example.com/file.pdf';
fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
}
Oh.. My bad :(
I have to install File plugin too :D
$ ionic cordova plugin add cordova-plugin-file --save
$ npm install --save #ionic-native/file

Trying to save a pdf locally on device with ngCordova

EDIT: Never mind. I fixed it by re-adding platforms:
1) ionic platform rm android
2) ionic platform add android
.......
I'm trying to save a pdf with ngcordova plugin $cordovaFile. But I get an error:
Uncaught ReferenceError: $cordovaFile is not defined, http://192.168.149.151:8100/js/invoice.service.js, Line: 16
I installed the plugin, included the script in index.html, getting the same error in browser and on device. am I missing something?
app.js:
var exampleApp = angular.module('starter', ['ionic','pdf','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
});
index.html:
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
service:
angular.module('starter').factory('InvoiceService', ['$q', InvoiceService]);
function InvoiceService($q) {
function createPdf(invoice) {
return $q(function(resolve, reject) {
var dd = createDocumentDefinition(invoice);
var pdf = pdfMake.createPdf(dd);
pdf.getBase64(function (output) {
resolve(base64ToUint8Array(output));
});
pdfMake.createPdf(dd).getBuffer(function (buffer) {
var utf8 = new Uint8Array(buffer); // Convert to UTF-8...
binaryArray = utf8.buffer; // Convert to Binary...
$cordovaFile.writeFile(cordova.file.dataDirectory, "example.pdf", binaryArray, true)
.then(function (success) {
console.log("pdf created");
}, function (error) {
console.log("error");
});
});
});
}
return {
createPdf: createPdf
};
}
plugin list:
ionic plugin list
com.jcjee.plugins.emailcomposer 1.4.6 "Email Composer with Attachments"
cordova-plugin-console 1.0.2 "Console"
cordova-plugin-device 1.1.1 "Device"
cordova-plugin-file 4.1.1 "File"
cordova-plugin-splashscreen 3.2.1 "Splashscreen"
cordova-plugin-statusbar 2.1.2 "StatusBar"
cordova-plugin-whitelist 1.2.1 "Whitelist"
ionic-plugin-keyboard 2.0.1 "Keyboard"
dms-MacBook-Pro:pdf-test dms$ ionic plugin list
com.jcjee.plugins.emailcomposer 1.4.6 "Email Composer with Attachments"
cordova-plugin-console 1.0.2 "Console"
cordova-plugin-device 1.1.1 "Device"
cordova-plugin-file 4.1.1 "File"
cordova-plugin-splashscreen 3.2.1 "Splashscreen"
cordova-plugin-statusbar 2.1.2 "StatusBar"
cordova-plugin-whitelist 1.2.1 "Whitelist"
ionic-plugin-keyboard 2.0.1 "Keyboard"
Never mind. I fixed it by re-adding platforms:
1) ionic platform rm android
2) ionic platform add android
You are using '$cordovaFile' in the factory but you are not injecting that your factory/service module should be like this:
angular.module('starter').factory('InvoiceService', ['$q', InvoiceService, '$cordovaFile', function($q,InvoiceService,$cordovaFile) {}]);
Or
angular.module('starter').factory("InvoiceService", function($q,InvoiceService,$cordovaFile) {});

How to implement OAuth.io using Ionic Framework for LinkedIn?

I have created the LinkedIn app and retrieved the client id and client_secret.
Now inside the integrated api of OAuth.io created an api and have added the keys and permission scope.
I want to run this project using Ionic Framework. What should be done to achieve it.
P.S: I am new to Ionic Framework and OAuth.io. So please don't mind my style of asking the question.
whole index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="js/ng-cordova-oauth.min.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-controller="MainCtrl">
<button class="button" ng-click="linkedInLogin()">Login via LinkedIn</button>
</body>
</html>
whole app.js:
angular.module('starter', ['ionic', 'ngCordova', 'ngCordovaOauth'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller("MainCtrl", function($scope, $cordovaOauth) {
document.addEventListener( "deviceready", onDeviceReady );
function onDeviceReady( event ) {
// on button click code
$scope.linkedInLogin = function(){
OAuth.initialize('07IxSBnzVoGGQL2MpvXjSYakagE')
OAuth.popup('linkedin').done(function(result) {
// Here you will get access token
console.log(result)
result.me().done(function(data) {
// Here you will get basic profile details of user
console.log(data);
})
});
};
}
});
Please go through the steps and below code:
1) create a project from terminal as ionic start linkedinlogin blank
2)cd linkedinlogin project
3)Add the required platform in terminal as ionic add platform ****
4)Add the ng-cordova.min.js file above the cordova.ja file in our project
5)Install ng-cordova-oauth as bower install ng-cordova-oauth -S
6)Then include ng-cordova-oauth.min.js file in index.html
7)Inject 'ngCordova' and 'ngCordovaOauth' as dependency in app.js file
8)In index.html create a button as login via linkedin
9)In app.js create a Controller with below code
10)Please update your cordova platform if the above plugin doesn't work
$cordovaOauth.linkedin(clientId, clientSecret, ['r_basicprofile', 'r_emailaddress']).then(function(success){
//Here you will get the access_token
console.log(JSON.stringify(success));
$http({method:"GET", url:"https://api.linkedin.com/v1/people/~:(email-address,first-name,last-name,picture-url)?format=json&oauth2_access_token="+success.access_token}).success(function(response){
// In response we will get firstname, lastname, emailaddress and picture url
// Note: If image is not uploaded in linkedIn account, we can't get image url
console.log(response);
}, function(error){
console.log(error);
})
}, function(error){
console.log(error);
})
I thing you read the ngCordova plugins.
Using oauth.io i have implemented login via linkedin:
Please follow the steps:
1. Create a app in oauth.io and get public key.
2. Click on the Integrated APIs menu from the left side bar.
3. Now click on ADD APIs green button on the right top corner.
4. Now Search and select LinkedIn.
5. Now add the Client id and Client Secret in keys and permission scope.
6. use below command to add plugin to project:
cordova plugin add https://github.com/oauth-io/oauth-phonegap
7. For controller code check below code.
document.addEventListener( "deviceready", onDeviceReady );
function onDeviceReady( event ) {
// on button click code
$scope.linkedInLogin = function(){
OAuth.initialize('your public key')
OAuth.popup('linkedin').done(function(result) {
// Here you will get access token
console.log(result)
result.me().done(function(data) {
// Here you will get basic profile details of user
console.log(data);
})
});
};
}
Hope it may be help you..

Ionic 2 App - Not making any Ajax calls via IOS Simulator

I have been trying to run this app through simulator.
When I run ionic emulate ios, this app will not make any Ajax Calls
When I run ionic emulate ios -c -l this app works perfectly
This is my provider class which I copied pretty much exactly from the Ionic Conference App
import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import 'rxjs/add/operator/map';
import {Storage,SqlStorage} from 'ionic-framework/ionic';
/*
Generated class for the RafitoData provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class RafitoData {
static get parameters() {
return [[Http]];
}
constructor(http) {
this.http = http;
this.districts = null;
this.storage = new Storage(SqlStorage);
}
addCustomer(customer) {
// don't have the data yet
return new Promise(resolve => {
var headers = new Headers();
headers.append('Content-Type','application/json');
var partialURL = '/rafitows/userInfo/create';
var body = JSON.stringify(customer);
// We're using Angular Http provider to request the data,
// then on the response it'll map the JSON data to a parsed JS object.
// Next we process the data and resolve the promise with the new data.
this.http.post(partialURL,body,{headers:headers})
.map(res => res.json())
.subscribe(data => {
resolve(data.status);
}, err=> {console.log(err)});
});
}
}
I am not sure what am I doing wrong. I have the cordova whitelist plugin.
This is my ionic information:
Cordova CLI: 5.4.0
Ionic Version: 2.0.0-beta.1
Ionic CLI Version: 2.0.0-beta.17
Ionic App Lib Version: 2.0.0-beta.8
ios-deploy version: Not installed
ios-sim version: 5.0.6
OS: Mac OS X El Capitan
Node Version: v5.3.0
Xcode version: Xcode 7.2.1 Build version 7C1002
I have uploaded the whole project on gitHub
https://github.com/alyn000r/testAjax/tree/master/testAjax
Please add the below line to your config.xml
<allow-navigation href="*" />
Also have a look here.
Hope this helps you. Thanks.