【问题标题】:Phonegap & iOS simulator - cannot save downloaded filePhonegap & iOS 模拟器 - 无法保存下载的文件
【发布时间】:2015-04-19 09:47:07
【问题描述】:

我正在使用 Phonegap/cordova 并编写一个 Android/iOS 应用程序,该应用程序将从我的服务器下载 json 数据并本地存储在设备上以供离线使用。在 android 上,这非常有效。我没有 iOS 设备,因此依赖于 iOS 模拟器,它会抛出“无法创建目标文件”类型错误。

downloadFile:function(path,uri){
  var fileTransfer = new FileTransfer();

  fileTransfer.download(
    encodeURI(path),
    app.getStorageLocation()+"files/"+uri,
    function(entry) {
      console.log("download complete: " + entry.toURL());
      app.progressMove();
    },
    function(error) {
      console.log("download error source " + error.source);
      console.log("download error target " + error.target);
      console.log("upload error code" + error.code);
    },
    false);

}

getStorageLocation 函数为:

getStorageLocation:function(){
    if(device.platform == 'Android'){
        return cordova.file.externalApplicationStorageDirectory;
    }
    else if(device.platform == 'iOS'){
        return cordova.file.documentsDirectory;
    }else{
        throw new Error('Unsupported platform: '+device.platform);
    }
}

在 iOS 模拟器上,它确实返回了 Documents 目录,但上面的内容无法写入。这只是一个模拟器错误还是我做错了什么?

谢谢!

【问题讨论】:

标签: ios cordova


【解决方案1】:

我在文档目录下创建了一个名为 dummy.html 的文件。下面是用于下载文件的工作代码 sn-p。您可以记录路径并查看其指向的位置。使用 safari 开发工具 iOS 模拟器进行检查。我添加了文件和文件传输插件。

function downloadFile() {
window.requestFileSystem(
    LocalFileSystem.PERSISTENT, 0,
    function onFileSystemSuccess(fileSystem) {
        fileSystem.root.getFile(
            "dummy.html", {
                create: true,
                exclusive: false
            },
            function gotFileEntry(fileEntry) {
                console.log(fileEntry);
                var sPath = fileEntry.nativeURL.replace("dummy.html", "");
                console.log(sPath);
                var fileTransfer = new FileTransfer();
                fileEntry.remove();
                fileTransfer.download(
                    "http://developer.android.com/assets/images/home/ics-android.png",
                    sPath + "dummy.png",
                    function(theFile) {
                        console.log("download complete: " + theFile.toURI());
                        showLink(theFile.toURI());
                    },
                    function(error) {
                        console.log("download error source " + error.source);
                        console.log("download error target " + error.target);
                        console.log("upload error code: " + error.code);
                    }
                );
            },
            fail);
    },
    fail);

}

查看截图-

【讨论】:

  • 这只适用于模拟器?在真实设备上这仍然有效吗?
【解决方案2】:

太棒了!让它工作。 另外发现并非所有文件都有问题。 Apple 不喜欢自定义文件类型,也不喜欢其中包含“%20”的文件名。修复上述所有问题都有效!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-09
    • 2018-03-06
    • 2019-04-26
    • 2015-02-14
    • 2015-02-24
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多