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

Posted

技术标签:

【中文标题】在 iOS Phonegap 应用程序上序列化文件传输【英文标题】:Serialising file transfers on iOS Phonegap application 【发布时间】:2012-10-04 19:32:01 【问题描述】:

我有一个适用于 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】:

我在我的应用程序上所做的是创建一个需要下载的文件的全局数组,然后启动从数组前面抓取第一个元素并下载它的代码。完成后,它会检查数组中是否还有要处理的项目,如果是,则重新开始该过程。如果没有,它会完成下载并继续执行应用程序接下来需要执行的任何操作。

为我们的文件创建一个空白数组以供下载 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();

【讨论】:

以上是关于在 iOS Phonegap 应用程序上序列化文件传输的主要内容,如果未能解决你的问题,请参考以下文章

iOS 上 Phonegap 应用中的 Pdf / Docx 预览

PhoneGap 文件下载在 IOS 设备上无法正常工作

phonegap 插件barcodescanner 在iOS 上不起作用

Phonegap 3.4 文件传输错误 (iOS)

Phonegap混合iOS应用程序中加载的远程网页可以将数据保存到iOS文件系统吗?

在 iOS 上使用 Cordova / Phonegap 1.6.1 一次写入多个文件