Contact list not accessing all contacts phonegap - ios

I created a project in phonegap in appery.io framework. It is not cordova based project but I installed cordova library manually. I am fetching contacts list using Jquery but it is fetching only device contacts list not the sim contacts list. If i want to install cordova contacts plugin using commands then it is showing current directory is not a cordova based project. if anyone could help me out it would be much appreciated.

Hi use this to save all contacts in sdcard and display. (default Cordova contacts and file plugin)
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
navigator.contacts.find(["*"], function(contacts) {
//alert("contacts.length = " + contacts.length);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile("contacts.json", {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwriteend = function(){
// Success Contacts saved to sdcard as a contacts.json file
// Now get and read the json file
var path = fileSystem.root.getFile("contacts.json", {create:false},gotFileEntry, fail);
// jquery
$.getJSON(path, function (data) {
user = data;
$.each(user, function (index, user) {
var all_item = '<p id="'+user.id+'">'+user.displayName+'</p>';
$('#allcontacts').append(all_item);
});
});
};
writer.write(JSON.stringify(contacts));
}, onError);
}, onError);
}, onError);
}, onError,{"multiple": true});}
function onError(){
alert("Error");
}

Related

Cordova Media Plugin not working

I can't get the cordova media plugin to work, I get error code 1 which signals that the file is not getting loaded. I've tried a number of variations, but can't figure out which path is correct.
Currently my code looks like this:
function onDeviceMediaReady () {
var path = window.cordova.file.applicationDirectory + 'why.mp3';
console.log(path);
narrative = new Media(path, // success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
function(err) {
console.log("playAudio():Audio Error: "+ err.code);
});
}
this gives me a path that's file://var/cotainers/Bundle/Application/[GUID]/Cordova400.app/why.mp3
I don't get why I can't find it. the file is in the telerik appbuilder root directory.
Inside your 'WWW' folder place the file inside 'sound' folder & try following
var srcBookmark = "sound/yes.mp3"; //ios
var iOSPlayOptions = {
numberOfLoops: 1,
playAudioWhenScreenIsLocked : false
}
var media = $cordovaMedia.newMedia(srcBookmark);
//media.play(); //android
media.play(iOSPlayOptions); //ios
$timeout(function(){
media.stop();
media.release()
}, 500);
If you're using appBuilder to test your app te aplication folder is the telerik folder, you must deploy your app as APK and test the folder

ngCordova InAppBrowser plugin freeze app on iOS but no on Android

I am currently using, IONIC v1.0.0, AngularJs and ngCordova v0.1.23-alpha on IOS and Android.
I have come across an issue with my login view freezing up.
It happens after opening InAppBrowser and hitting "back to app" (close button caption used for IOS to get back) is freezes my login view disabling the ability to touch on the whole screen and making me unable to login. It only happens if I call InAppBrowser when starting the app, if I use it during the app life cycle (after login in), it doesn't do it.
Here are some of my code pieces
In app.js:
angular.module('MyApp', ['ionic', 'MyApp', 'ngCordova', 'mainController', 'loginController', 'pascalprecht.translate', 'ngStorage', 'ngSanitize', 'ngAnimate', 'ngTouch', 'ngCookies', 'ngLocale', 'testController'])
In mainController I have Factory:
.factory('customMainFunction', function ($rootScope, $ionicLoading, $ionicScrollDelegate, $ionicPopup,
$timeout, $localStorage, $location, $ionicHistory, $window, $cordovaInAppBrowser) {
var Token = "";
return {
openBrowser: function (link) {
var options = {
location: 'yes',
clearcache: 'yes',
toolbar: 'yes',
closebuttoncaption: 'Back to App'
};
document.addEventListener("deviceready", function () {
$cordovaInAppBrowser.open(link, '_blank', options)
.then(function (event) {
// success
})
.catch(function (event) {
// error
});
}, false);
$rootScope.$on('$cordovaInAppBrowser:loadstart', function (e, event) {
//console.log(event);
var url = "";
var positionNumber;
var res;
url = event.url;
positionNumber = url.search("ssoToken=");
res = url.substr(Number(positionNumber)+9);
/*positionNumber = url.search("module=");
res = url.substr(Number(positionNumber)+6);*/
if(url !== "" && positionNumber >= 0 && res.length > 0) {
$rootScope.$broadcast('ssoToken', { token: res });
$cordovaInAppBrowser.close();
}
});
$rootScope.$on('$cordovaInAppBrowser:loadstop', function (e, event) {
console.log("loadstop");
//console.log(event);
// insert CSS via code / file
//$cordovaInAppBrowser.insertCSS({
// code: ''
//});
// insert Javascript via code / file
//$cordovaInAppBrowser.executeScript({
// file: ''
//});
});
$rootScope.$on('$cordovaInAppBrowser:loaderror', function (e, event) {
});
$rootScope.$on('$cordovaInAppBrowser:exit', function (e, event) {
});
}
}
})
If anybody has encounter such issue please let me know what can be done to resolve it. Any question or clarifications let me know. Thanks in advance.
Found the issue of my own problem. Basically the problem is related to Threading. Look for Threading. How did I find out about it? On XCode I was able to see a message saying:
THREAD WARNING: ['InAppBrowser'] took '108.12' ms. Plugin should use a
background thread
There are two ways to solve this (I believe):
1- Using background threading (just like the message states). Please refer to:
How to run cordova plugins in the background?
2- Wrap the openBrowser function call (in my case) in a setTimeout. That will delay the call until the thread is done and UI won't be blocked. Once done (in my case) it opened the inAppBrowser and when I hit "Back to app" UI was not block at all.
Hope this helps someone out there.

How to download picture with Phonegap Filetransfer to image gallery in iOS

This has been asked several times, but most of these questions are unanswered
I'm downloading a file like below, and it seems to work fine. However .. it does not show up in the iOS, ehm, gallery. That is, in the 'photos' application.
var fileTransfer = new FileTransfer();
var encurl = encodeURI(url);
var filename = url.split('/').slice(-1)[0];
var filepath = "foo/"+filename;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
var syspath = fileSystem.root.toURL() + '/' + filepath;
var fileTransfer = new FileTransfer();
fileTransfer.download(
encurl,
syspath,
function (entry) {
foo.debug("Download success "+syspath);
},
function (error) {
foo.error("Download failed with error "+error.code+' '+syspath);
}
);
}, function (evt) {
foo.error("Filesystem failed with error "+evt.target.error.code);
});
and the result is
[Log] Download success file:///var/mobile/Applications/68DE0AD9-FBD2-4D82-92C0-2B7634B218D5/Documents//foo/20141030-153810-editor.jpg (console-via-logger.js, line 173)
hurray. now, how do you open the download, using just your fingers, on ios ?
I would mark this as a duplicate of Phonegap - Save image from url into device photo gallery
I was happy with the answer by M165437 and my comments. That answered my question.
Try to download by using https://www.npmjs.com/package/com-cordova-image-save-to-gallery plugin. It will download a picture from a given URL and save it to IOS Photo Gallery.
Cordova plugin add https://github.com/valwinjose007/cordova-image-save-to-gallery.git
How to use:
declare var CordovaImageSaveToGallery: any;
CordovaImageSaveToGallery.downloadFromUrl('https://picsum.photos/200/300',(res)=>{
//download success
},(err)=>{
//error on download
});

Set folder metadata doesn't work on Phonegap 3.3.0 / iOS

I'm trying to use the method setMetadata, using the File plugin, but it seems does not work.
No Success or Fail callback is executed. When I use console.log(entry.setMetadata), it prints the correct method. I use the File plugin to access, create and delete files and folders without problems. Only the setMetadata doesn't work.
Example:
localFileSystem = LocalFileSystem.PERSISTENT;
subFolder = "Backups";
metadataKey = "com.apple.MobileBackup";
metadataValue = 1;
window.requestFileSystem(localFileSystem, 0, function(fileSystem) {
fileSystem.root.getDirectory(subFolder, {create: true, exclusive: false}, function(parent) {
var data = {};
data[metadataKey] = metadataValue;
console.log(data); // OK
console.log(parent); // OK
parent.setMetadata(function() {
console.log("success setting metadata"); // Nothing
}, function() {
console.log("error setting metadata"); // Nothing
}, data);
}, function() {
console.log("error getting dir"); // Nothing, directory is OK
});
}, function(error) {
console.log(error.code); // No error here
});
It was a bug on the File plugin. I checked with the developers on Github:
https://github.com/apache/cordova-plugin-file/pull/39
Just waiting for changes on the Phonegap site.

Cordova iOS File API - Move Photo to a persistent storage

I've a problem with moving a camera photo to the persistent storage under iOS 7 (Cordova 3.4.0-0.1.3 - File API 1.0.1).
I can capture the photo and when I move the file to the persistent storage it seems that there is no error, I also receive a file path with new_entry.fullPath like /my_folder/12345678.jpg.
But when I append the new image to the body with that url it seems that there is no image (blank image will be added). I've tried it also with "file://" in the url, but this makes no difference.
I'm also a little bit confused, because the new_entry.toURL() method returned an url containing a folder named "temporary" (e.g. cdvfile://localhost/temporary/my_folder/12345678.jpg), but I use the persistent storage. Is that correct under iOS?
This is my relevant code for that function:
var app = {
capturePhoto: function () {
if (!navigator.camera) {
alert('Camera API not supported');
}
navigator.camera.getPicture( app.cameraSuccess, app.cameraError, {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI
});
},
cameraSuccess: function (imageData) {
console.log('cameraSuccess: '+imageData);
app.movePhoto( imageData );
},
movePhoto: function (file){
alert(file);
window.resolveLocalFileSystemURI( file , app.resolveOnSuccess, app.resOnError);
},
resolveOnSuccess: function (entry){
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpg";
var myFolderApp = "my_folder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory( myFolderApp,
{create:true},
function(directory) {
entry.moveTo(directory, newFileName, function(new_entry){
path = new_entry.fullPath;
url = new_entry.toURL();
console.log(path+"\n"+url);
alert( path+"\n"+url );
jQuery('body').append('<img src="'+path+'" />');
}, app.resOnError);
},
app.resOnError);
},
app.resOnError);
},
resOnError: function(error) {
alert('Error '+error.code+': '+error.message);
},
}
27/5/2014 UPDATE: Version 1.1.0 was released since than, therefore no need to use dev branch anymore.
It's a bug in cordova: https://issues.apache.org/jira/browse/CB-6148
It's already fixed in dev branch. You can update to dev branch with those steps:
remove the plugin:
cordova plugin rm org.apache.cordova.file
install the plugin (we have to use the git syntax in this case):
cordova plugin add https://github.com/apache/cordova-plugin-file.git#dev
check the iOS build > Targets > Your app target > Build phases > Compile Sources
add (if not added)
CDVFile.m
CDVLocalFilesystem.m
CDVAssetLibraryFilesystem.m

Resources