保持下载文件(缓存)以便下次打开应用程序

时间:2016-09-04 10:23:42

标签: ios pdf alamofire nsurlsession afnetworking-2

我使用这种Alamofire方式下载外部pdf文件。

问题是,我想在下次用户打开应用时保留它。因此用户无需再次下载pdf。

我使用以下方法下载

    let destination =
        Alamofire.Request.suggestedDownloadDestination(directory: .CachesDirectory,
                                                       domain: .UserDomainMask);

    Alamofire.download(.GET, urlString, destination: destination)
        .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in

        }
        .response { request, response, _, error in

            print("Downloaded to \(destination(NSURL(string: "")!, response!))");

    }

downloadedFilePath就是这样的。

file:///var/mobile/Containers/Data/Application/4957AD15-947A-47D6-A126-EA06A5BCB099/Library/Caches/RewardMe-Presentation-at-NVIDIA-Auditorium.pdf

下次启动应用时如何保留文件?

我在下次启动应用程序时将该路径保存到NSUserDefaults中,但该文件已经消失。

2 个答案:

答案 0 :(得分:0)

有几个函数会将它们添加到您的代码中并调用 copyFile ,您将在其中显示路径或之后。

let filePath: String = getPath("testFile.pdf")
        let fileManager = NSFileManager.defaultManager()
        if fileManager.fileExistsAtPath(dPath) {
      //Code for using the file data
         }
else {
//Download code for the file
}

copyFile 两个参数一个是您要保存的文件的文件名,第二个是文件所在的位置。

用于检查下次应用程序打开时的操作。首先获取文件路径并检查文件是否存在。如果存在,则不下载文件,否则下载文件。

cropNum(1);
cropNum(1.241241);
cropNum(5.2133213);

function cropNum(n) {
  if (Number(n) === n && n % 1 !== 0) {
    return parseFloat(Math.round(n * 100) / 100).toFixed(1)
  }

  return n;
}

// returns:
// 1
// 1.2
// 5.2

希望有所帮助:)

答案 1 :(得分:0)

HTTP已经有了缓存机制,您可以考虑使用它。不要重新发明轮子。 Here是一种方法。