Can't play local videos in IOS 9 with Phonegap app - ios

I made an IOS 9 app using Phonegap 6.2.0. I need to play videos with no connection, so I download it using cordova FileTransfer plugin:
var uri = encodeURI(file.url);
var fileTransfer = new FileTransfer();
// var fileLocation = cordova.file.applicationStorageDirectory +
// '/Documents/' + file.folder + '/' + file.fileName;
var fileLocation = cordova.file.dataDirectory + file.fileName;
var deferred = $q.defer();
fileTransfer.headers = {
Connection: "close"
};
fileTransfer.download(uri, fileLocation, function(result) {
console.log("Fichero descargado: " + JSON.stringify(result));
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
I've tried different file locations to download it (https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/)
Then, I return the file path using resolveLocalFileSystemURL:
var deferred = $q.defer();
var nativePath = cordova.file.dataDirectory + nombreFichero + "." + extension;
resolveLocalFileSystemURL(nativePath, function(entry) {
//deferred.resolve(entry.nativeURL);
console.log("Fichero native: " + entry.toNativeURL());
console.log("Fichero fullPath: " + entry.fullPath);
console.log("Fichero toUrl: " + entry.toURL());
console.log("Fichero toInternalURL: " + entry.toInternalURL());
deferred.resolve(entry.toURL());
}, function(error) {
console.log("Error al leer el fichero: " + JSON.stringify(error));
deferred.reject(error);
});
return deferred.promise;
I've tried all file formats but none of them worked:
cdvfile://localhost/library-nosync/97a7d50f-05d1-4642-96e9-b0b26ea41897.mp4
file:///var/mobile/Containers/Data/Application/6CD24D7A-7A39-4AFE-A43B-788FCDFCEB5A/Library/NoCloud/a88d38b8-85e8-4b9b-b57e-a8eb2731eb0d.mp4
http://localhost/library-nosync/97a7d50f-05d1-4642-96e9-b0b26ea41897.mp4 and using port 12344
Some formats do nothing, some show the button play strikethrough...
In all answers I had read they recommend to use .toNativeUrl() but it doesn't work for me...
I also tried cordova-plugin-streaming-media (I can't post more links), but it does not work (no play video, no errors...)
Any idea?

Solved.
My code works good and play videos. The problem was in the URL to download the video, it gets a string with the url and not the video (therefore download and open file method didin't throw error)
Summarizing, toUrl() works.
Thanks #Gandhi for your replies.

Related

Cordova / Ionic - Download file from InAppBrowser

The scenario goes like this: I open a website in InAppBrowser, after the user ends with the work over there, the site generates a .pdf for the user to download, the problem is that the pdf does not download, it opens it in the browser.
Is there a way to make it download from the InAppBrowser? I'm currently working on an iOS app, so the solution would be better for iOS.
Thanks in advance.
Following #jcesarmobile advices this is what I came up with:
First I had to install the cordova-plugin-file-transfer
Open URL
var url = "http://mi-fancy-url.com";
var windowref = window.open(url, '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
Create a listener on that windowref for a loadstart event and check if what's being loaded is a pdf (that's my case).
windowref.addEventListener('loadstart', function(e) {
var url = e.url;
var extension = url.substr(url.length - 4);
if (extension == '.pdf') {
var targetPath = cordova.file.documentsDirectory + "receipt.pdf";
var options = {};
var args = {
url: url,
targetPath: targetPath,
options: options
};
windowref.close(); // close window or you get exception
document.addEventListener('deviceready', function () {
setTimeout(function() {
downloadReceipt(args); // call the function which will download the file 1s after the window is closed, just in case..
}, 1000);
});
}
});
Create the function that will handle the file download and then open it:
function downloadReceipt(args) {
var fileTransfer = new FileTransfer();
var uri = encodeURI(args.url);
fileTransfer.download(
uri, // file's uri
args.targetPath, // where will be saved
function(entry) {
console.log("download complete: " + entry.toURL());
window.open(entry.toURL(), '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
true,
args.options
);
}
The problem i'm facing now is the path where it downloads, I just can't open it. But well, at least file is now downloaded. I will have to create a localStorage item to save the paths for different files.
Many validations are missing in this steps, this was just an example I made quickly to check if it works. Further validations are needed.
Open you window using IAB plugin and add an event listener
ref = window.open(url, "_blank");
ref.addEventListener('loadstop', loadStopCallBack);
In the InAppBrowser window call the action using https://xxx.pdf">documentName
Implement the loadStopCallBack function
function loadStopCallBack(refTemp) {
if(refTemp.url.includes('downloadDoc')) {
rtaParam = getURLParams('downloadDoc', refTemp.url);
if(rtaParam != null)
downloadFileFromServer(rtaParam);
return;
}
}
function getURLParams( name, url ) {
try {
if (!url)
url = location.href;
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
return results == null ? null : results[1];
} catch (e) {
showSMS(e);
return null;
}
}
After create a download method
function downloadFileFromServer(fileServerURL){
try {
var Downloader = window.plugins.Downloader;
var fileName = fileServerURL.substring(fileServerURL.lastIndexOf("/") + 1);
var downloadSuccessCallback = function(result) {
console.log(result.path);
};
var downloadErrorCallback = function(error) {
// error: string
console.log(error);
};
//TODO cordova.file.documentsDirectory for iOS
var options = {
title: 'Descarga de '+ fileName, // Download Notification Title
url: fileServerURL, // File Url
path: fileName, // The File Name with extension
description: 'La descarga del archivo esta lista', // Download description Notification String
visible: true, // This download is visible and shows in the notifications while in progress and after completion.
folder: "Download" // Folder to save the downloaded file, if not exist it will be created
};
Downloader.download(options, downloadSuccessCallback, downloadErrorCallback);
} catch (e) {
console.log(e);
}
}
you can get the plugin here https://github.com/ogarzonm85/cordova-plugin-downloader
it Works and was too easy

Phonegap iOS Download files from online to local file system not working

Using phonegap build for iOS platform, the download procedure is not working!
Could someone tell me why the code below returned errors messages:
("download error source " + error.source);
could not download the image from online
// e.g: http://www.sushikoapp.com/img/branches/thumbs/big_sushiko-bchamoun.jpg
("upload error code" + error.code); sometimes 1 and sometimes 3
The code is below:
var ios_directoryEntry = fileSystem.root;
ios_directoryEntry.getDirectory("branches", { create: true, exclusive: false }, onDirectorySuccessiOS, onDirectoryFailiOS);
var ios_rootdir = fileSystem.root;
//var ios_fp = ios_rootdir.fullPath;
var ios_fp = ios_rootdir.toURL();
ios_fp = ios_fp + "branches/" ;
//ios_fp = "cdvfile://localhost/persistent/branches/";
var fileTransfer = new FileTransfer();
fileTransfer.download(encodeURI(imgURL + "branches/thumbs/big_sushiko-bchamoun.jpg" ), ios_fp + "big_big_sushiko-bchamoun.jpg",
function (entry) {
alert("download complete: " + entry.fullPath);
}
},
function (error) {
//Download abort errors or download failed errors
alert("download error source " + error.source);
alert("upload error code" + error.code);
}
);
Thank you for your suggestion...
The problem is you're treating the file API operations as synchronous, when they're actually asynchronous.
You can use cordova.file to reference the target folder on the filesystem (see here: https://github.com/apache/cordova-plugin-file/blob/master/doc/index.md).
So try something like this:
resolveLocalFileSystemURL(cordova.file.documentsDirectory, onGetDocuments, function(error) {
console.error("Error getting Documents directory: "+error.code);
});
function onGetDocuments(entry) {
console.log("Got Documents directory");
entry.getDirectory("branches", { create: true, exclusive: false }, onGetBranches, function(error) {
console.error("Error creating/getting branches directory: "+error.code);
});
}
function onGetBranches(entry){
console.log("Got branches directory");
doFileTransfer(entry.toURL());
}
function doFileTransfer(ios_fp){
var fileTransfer = new FileTransfer();
fileTransfer.download(encodeURI(imgURL + "branches/thumbs/big_sushiko-bchamoun.jpg" ), ios_fp + "big_big_sushiko-bchamoun.jpg",
function (entry) {
alert("download complete: " + entry.fullPath);
}
},
function (error) {
//Download abort errors or download failed errors
alert("download error source " + error.source);
alert("upload error code" + error.code);
}
);
}
You are trying to write a file to the iOS root File system, this is not possible since all app in iOS are sandboxed and can only access their own sandbox.
So don't use fileSystem.root but fileSystem.documents.

How to upload powerpoint file to server phonegap?

Hello I Want to upload a powerpoint file using phonegap file transfer protocol to my local java server thru ios simulator, the location of the file on the phone is passed to the handleOpenURL function when the user selects to open a powerpoint with my app. The problem is that nothing is happening although im sure this method is executing??!! can anyone help please?
function handleOpenURL(url)
{
setTimeout(function() {
alert(url);
jQuery.get( "http://192.168.1.100:8080/PpServer/getnumberofslides" , function( data ) {
numberofslides=data;
alert( "Load was performed." + data );
});
fileURL = url;
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// processapplication();
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var uri = encodeURI("http://192.168.1.100:8080/NewServerlet");
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType="multipart/form-data";
options.httpMethod="Post"
// options.params = {"file"};
var headers={'headerParam':'file'};
// options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
} else {
loadingStatus.increment();
}
};
ft.upload(fileURL, uri, win, fail, options);
}, 0);
//
}

PhoneGap file download not working properly on IOS devices

I am using PhoneGap version 2.9.0 to download file from URL to specific folder. Which is working fine for me in android, as file get download in specific folder, but in case of IOS devices file is not download fully.
Ex. IF file size = 2.3mb
and download file size = 111 bytes
My code -
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
function fileSystemSuccess(fileSystem) {
var uri = $("#URL").val(); // Get URL
var download_link = encodeURI(uri);
var path = download_link,
ext = path.substr(path.lastIndexOf('.') + 1); //Get extension of URL
var folder_name = $("#folder").val(); // Get folder name
var file_name = $("#filename").val(); //Get file name
var directoryEntry = fileSystem.root; // to get root path to directory
directoryEntry.getDirectory(folder_name, { create: true, exclusive: false }, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
var rootdir = fileSystem.root;
var fp = rootdir.fullPath;
fp = fp + "/" + folder_name + "/" + file_name + "." + ext; // fullpath and name of the file which we want to give
// download function call
var fileTransfer = new FileTransfer();
//File download function with URL and local path
fileTransfer.download(download_link, fp,
function (entry) {
alert("download complete: " + entry.fullPath);
},
function (error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
}
);
}
function onDirectorySuccess(parent) {
//alert(parent);
}
function onDirectoryFail(error) {
//Error while creating directory
alert("Unable to create new directory: " + error.code);
}
function fileSystemFail(evt) {
alert(evt.target.error.code);
}
Folder is creating in IOS, issue is only download file size. I am stuck with this IOS issue. Help me out.
Finally I got my solution.
<access origin="*" />
Above my code is working fine for download from URL in both android and IOS. Creating folder and download in it.

Geo Location not works in BlackBerry

I have developed an application using phonegap to retrieve Geo Location.
function getLoc() {
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
}
// onSuccess Geolocation
function onSuccess(position) {
var locInfo = new Object();
locInfo.Latitude = position.coords.latitude;
locInfo.Longitude = position.coords.longitude;
locInfo.Altitude = position.coords.altitude;
locInfo.Accuracy = position.coords.accuracy;
locInfo.AltitudeAccuracy = position.coords.altitudeAccuracy;
locInfo.Heading = position.coords.heading;
locInfo.Speed = position.coords.speed;
alert(locInfo.Latitude + " " + locInfo.Longitude);
}
// onError Callback receives a PositionError object
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
above code is working fine in Android, iPhone and BlackBerry Simulator, but not in BlackBerry device. I'm using BlackBerry Torch for testing.
what could be the issue. pls reply.
Thanks :)
Try to set timeout for getCurrentPosition.

Resources