使用webworks和cordova 2.9在黑莓中同时下载多个文件

时间:2013-11-20 17:06:26

标签: javascript cordova blackberry-10 blackberry-webworks

我正在开发一个应用程序,它需要从网络服务器下载一些文件并将它们存储在设备上,以便脱机使用。我使用的代码在Android和iOS中运行良好,但是我在Blackberry 10上下载多个文件时遇到了困难。

从查看Web控制台看,成功回调是针对第一个文件成功执行的,但对于任何后续文件都没有。不会为后续文件调用失败回调。

我正在使用cordova 2.9,并且我已经包含了所有必需的webworks插件。我已在config.xml中设置了对我的域的访问权限,并设置了access_shared权限。

我还编辑了cordova FileTransfer.download函数来调用webworks下载api“blackberry.io.filetransfer.download”。

以下是我编写的JavaScript代码。

// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// device APIs are available
//
function onDeviceReady() {
    //replace list with your files you wish to download
    var files = ["files/file1.txt", "files/file2.txt", "files/dir1/file3.txt"];
    initiateDownload(files);
    //getFSRoot(files);
}

var filesToDownload = 0;
var fileList = new Array();
var failedFileList;
var numFailedFiles = 0;
var currentFileIndex;
var retryCount = 0;
var root;

function isOnline(){
    var bIsOnline = false;

    if (navigator.connection.type != Connection.NONE && navigator.connection.type != Connection.UNKNOWN)
    {
        bIsOnline = true;
    }

    return bIsOnline;
}

function initiateDownload(files){
    alert("initiate download");

    failedFileList = new Array();
    filesToDownload = files.length;

    blackberry.io.sandbox = false;
    for (i = 0; i < files.length; i++)
    {
        currentFileIndex = i;
        console.log("initiate download of file index " + i + " File Name: " + files[i]);
        getFile(files[i]);
    }

}


function getFile(filePath)
{
    //TODO: Do we need to make this function recursive to serialize asynchronous downloads?
    console.log("START of function getFile() for " + filePath);

    window.requestFileSystem(
        LocalFileSystem.PERSISTENT, 0,
        function onFileSystemSuccess(fileSystem)
        {
            console.log("Success getting filesystem for filePath: " + filePath);
            createDirs(fileSystem.root, filePath, -1);
        },
        function(error){
            console.log("Failed to get the filesystem for filePath: " + filePath);
        }
    );
}

function createDirs(parentDir, filePath, index)
{
    console.log("createDirs params ===> parentDir=" + parentDir.toURL() + " filePath=" + filePath + " index=" + index); 
    arrDirs = filePath.split("/");

    if (index >= (arrDirs.length - 1))
    {
        createFile(arrDirs[index], parentDir, filePath);
    }
    else
    {
        dirName = "myapp";

        if (index >= 0)
        {
            dirName = arrDirs[index];
        }

        //if device is Blackberry, build up a full directory path as we are trying to install outside of sandbox
        var path, dirToCreate = ""
        if(device.platform = "BlackBerry"){

            path = "myapp/";
            console.log("JHPaths ======> arrDirs = " + arrDirs + " index = " +index);
            for (i = 0; i <= index; i++){
                path += arrDirs[i] + "/";
                console.log("path = " + path + " i = " + i + " index = " +  index);
            }

            dirToCreate = blackberry.io.home + "/" + path;
            dirToCreate = dirToCreate.substring(0, dirToCreate.length - 1);
            console.log("JHPaths Trying to create " + dirToCreate);
            dirName = dirToCreate;
        }

        parentDir.getDirectory(dirName, {create: true, exclusive: false},
                               function (directoryEntry) {
                                    console.log("Got directory " + directoryEntry.fullPath);
                                    createDirs(directoryEntry, filePath, index + 1);
                               },
                               function (error) {console.log("Failed to get directory " + dirName + " Error code : " + error.code);});
    }
}

function createFile(fileName, parentDir, filePath)
{   
    parentDir.getFile(
        fileName, {create: true, exclusive: false},
        function gotFileEntry(fileEntry)
        {
            localPath = fileEntry.fullPath;

            if (isOnline())
            {
                console.log("Before remove");
                fileEntry.remove(
                    function(){
                        console.log("FileEntry remove() was successful");
                    },
                    function(){
                        console.log("FileEntry remove() was failed");
                    }
                );
                console.log("After remove");
                var fileTransfer = new FileTransfer();
                //replace URL with the URL code you wish to download from
                var baseURL = "http://<ip-address>/WebFolder/";

                var uri = encodeURI(baseURL + filePath);
                fullFilePath = blackberry.io.home + "/myapp/" + filePath;
                fileTransfer.download(
                    uri,
                    /*localPath,*/
                    fullFilePath,
                    function(entry) {
                        console.log("download complete: " + entry.fullPath);
                        /*if(currentFileIndex < fileList.length){
                            currentFileIndex++;
                        }*/
                        if (device.platform == "iOS")
                        {
                            console.log("Setting file metadata");
                            parentDir.getFile(
                                fileName, {create:false, exclusive: false},
                                function gotFileEntry(fileEntry)
                                {
                                    fileEntry.setMetaData(
                                        function(){console.log("Set metadata for " + fileEntry.fullPath)},
                                        function(){console.log("Set metadata failed for " + fileEntry.fullPath)},
                                        {"com.apple.MobileBackup": 1}
                                    );
                                },
                                function getFileFailed(fileError)
                                {
                                    console.log("Get file failed:" + fileError.code);
                                }
                            );
                        }

                        filesToDownload--;

                        if (filesToDownload == 0 && failedFileList.length == 0)
                        {
                            //Call to retry failed Files
                                                        }   
                        else if(failedFileList.length > 0){
                            if(retryCount < 1){
                                retryFailedFiles();
                            }
                            else{
                                                                }
                        }
                    },
                    function(error) {
                        console.log("Cache file download error source " + error.source);
                        console.log("Cache file download error target " + error.target);
                        console.log("Cache file download error code " + error.code);

                        //failedFileList[numFailedFiles++] = filePath;
                        failedFileList[numFailedFiles++] = filePath;
                        filesToDownload--;

                        if (filesToDownload == 0 && failedFileList.length == 0)
                        {

                        }
                        else if(failedFileList.length > 0){
                            if(retryCount < 1){
                                retryFailedFiles();
                            }
                            else{

                            }
                        }
                    }
                );
            }
        },
        function getFileFailed(fileError)
        {
            console.log("Create file failed:" + fileError.code);

            filesToDownload--;

            /*if (filesToDownload == 0)
            {
                callbackDeferred.resolve();
            }*/
        }
    );
}

function retryFailedFiles(){
    console.log("Retrying failed files");
    retryCount++;
    initiateDownload(failedFileList);
}   

0 个答案:

没有答案