在iOS Phonegap应用程序上序列化文件传输

时间:2012-10-04 19:32:02

标签: ios cordova serialization file-transfer

我有一个适用于iOS的phonegap应用程序,可以从服务器下载图像和pdf文件,因为它们必须在本地可用。

我使用jQuery解析我需要下载的资产列表,然后使用Phonegap API启动FileTransfer,如下所示:

// assets is an array that has all pdf and image urls to be downloaded.
assets.map(downloadFile);

function downloadFile(file_url){
    console.log('Downloading file:'+file_url);
    var fileTransfer = new FileTransfer();

    fileTransfer.download(
        file_url,
        get_local_file_path(file_url),
        download_success,
        function(error) {
            stopspin();
            console.log('ERROR downloading: '+ error.source);
            $('#notify-user').html('Downloading failed. <a href="#" onclick="checkLatestIssue()">Try again?</a>')
        }
    );
}

现在,每次资产最多可达50个。我可以看到所有的文件传输请求都是立即发送的,有时,一些文件传输请求会超时,从而导致下载不完整,我可以通过本地资产进行渲染。

有没有办法可以通过大约5次并行下载来连续下载所有这些问题?

1 个答案:

答案 0 :(得分:2)

我在我的应用程序上做的是创建一个我需要下载的全局文件数组,然后启动代码,从代码前面抓取第一个元素并下载它。完成后,它会检查数组中是否还有另一个要处理的项目,如果是,则再次启动该过程。如果没有,它会完成下载并继续处理下一个应用程序需要做的事情。

为我们要下载的文件创建一个空白数组 data_to_process = [];

将图像和视频添加到从API

返回的数组“结果”中
// add images to array
$.each( result.images_to_download, function( index, value ) {

    index = index + 1;
    data_to_process.push(
        {
            "type":     "images",
            "filename": value,
            "msg":      "Downloading image "+index+" of "+result.images_to_download.length+"..."
        }
    );
});

// add videos to array
$.each( result.videos_to_download, function( index, value ) {

index = index + 1;
data_to_process.push(
    {
        "type":     "videos",
        "filename": value,
        "msg":      "Downloading video "+index+" of "+result.videos_to_download.length+"..."
    }
);
});

这是处理文件的代码 注意:这里有一些不需要的代码,用于根据文件将文件放在某些目录中,更新下载进度的百分比指示符等:

// values for percentages
start_data_length = data_to_process.length;
current_iteration = 0;

// set writing to false
writing = false;

// what we do after each iteration in the data array
var finish_processing = function() {

    // increment iteration count
    current_iteration++;

    // set percent value
    var percent = current_iteration / start_data_length * 100;
    percent = Math.round( percent );
    $('#update_percent').html( percent );

    // remove from array after process
    data_to_process.splice( 0, 1 );

    // set writing back to false so we can start another iteration
    writing = false;
}

// checks if we need to process the next part of the array or not
var check_to_process = function() {

    // console.log('checking if we need to process');

    // if we still have items in the array to process
    if ( data_to_process.length > 0 ) {

        // if we're currently not working on an item
        if ( writing === false ) {

            // process next item in array
            process_download_data();

        } else {

            // not ready yet, wait .5 seconds and check again
            // console.log('busy - waiting to process');
            setTimeout( check_to_process, 500 );
        }

    } else {

        // console.log('nothing left to process');
    }
}

// processes the downloaded data
var process_download_data = function() {

    // set writing to true
    writing = true;

    // current item to process is first item in array
    var current_item = data_to_process[0];

    if ( current_item.msg ) {
        $('#update_item').html(current_item.msg);
    } else {
        $('#update_item').html('Processing update data...');
    }
    // console.log( 'processing this: '+ current_item.filename );

    // if something didn't work right..
    var broke = function(error) {

        // console.log( 'error' );
        // console.log( error );

        // cycle to next item in array
        finish_processing();
    }

    // get the directory of current item's "type"
    var get_directory = function( fileSystem ) { 
        fileSystem.root.getDirectory( current_item.type, {create:true,exclusive:false}, get_file, broke ); 
    } 

    // get the file
    var get_file = function( dirEntry ){

        // if texts
        if ( current_item.type == 'texts' ) {

            dirEntry.getFile( current_item.filename+".txt", {create: true, exclusive: false}, create_text_writer, broke); 

        // if images
        } else if ( current_item.type == 'images' ) {

            var localFileName = current_item.filename.substring(current_item.filename.lastIndexOf('/')+1);

            dirEntry.getFile( localFileName, {create: true, exclusive: false}, create_file_writer, broke);

        // if videos
        } else if ( current_item.type == 'videos' ) {

            var localFileName = current_item.filename.substring(current_item.filename.lastIndexOf('/')+1);

            dirEntry.getFile( localFileName, {create: true, exclusive: false}, create_file_writer, broke);

        // if audios
        } else if ( current_item.type == 'resources' ) {

            var localFileName = current_item.filename.substring(current_item.filename.lastIndexOf('/')+1);

            dirEntry.getFile( localFileName, {create: true, exclusive: false}, create_file_writer, broke);

        // if audios
        } else if ( current_item.type == 'audios' ) {

            var localFileName = current_item.filename.substring(current_item.filename.lastIndexOf('/')+1);

            dirEntry.getFile( localFileName, {create: true, exclusive: false}, create_file_writer, broke);
        }
    } 

    // write to file using filetransfer
    var create_file_writer = function( fileEntry ) {

        if ( current_item.remove === true ) {

            fileEntry.remove( function(entry) {

                // what to do when image is deleted
                finish_processing();

            },broke);

        } else {

            var localPath = fileEntry.fullPath;

            // console.log('Writing to: '+localPath+' from: '+current_item.filename);

            var ft = new FileTransfer();

            ft.download( current_item.filename, localPath, function(entry) {

                // what to do when image is downloaded
                finish_processing();

            },broke);
        }
    }

    // create writer for "texts" type
    var create_text_writer = function( fileEntry ) { 
        fileEntry.createWriter( write_text_file, broke ); 
    } 

    // write to file for "texts" type
    var write_text_file = function( writer ) {

        // write new contents
        writer.write( current_item.data );

        // add item where it needs to be in the document
        if ( current_item.append === true ) {

            $('#'+current_item.marker).nextAll().remove();

            // appending
            // console.log('Appending data to: #'+current_item.id);
            $('#'+current_item.id).append( current_item.data );

        } else {

            // adding
            // console.log('Adding data to: #'+current_item.id);
            $('#'+current_item.id).html( current_item.data );
        }

        // console.log('finished writing: '+current_item.filename);

        finish_processing();
    }

    // request persistent filesystem
    window.requestFileSystem( LocalFileSystem.PERSISTENT, 0, get_directory, broke );

    // check if we need to process the next item yet
    check_to_process();
}

// process data from the update
process_download_data();