【问题标题】:Keep Downloaded File (Cache) For The Next Time Application Open保持下载的文件(缓存)以供下次应用程序打开
【发布时间】:2016-09-04 10:23:41
【问题描述】:

我使用这种 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!))");

    }

下载的文件路径是这样的。

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

如何在我的应用下次启动时保留该文件?

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

【问题讨论】:

  • 简单地将文件保存在 NSDocumentDirectory 或 NSBundle 中,然后从那里获取它
  • 我如何做到这一点? @AbdulRehmanWarraich

标签: ios pdf alamofire nsurlsession afnetworking-2


【解决方案1】:

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

func getPath(fileName: String) -> String {

        let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
        let fileURL = documentsURL.URLByAppendingPathComponent(fileName)


         print("File Path Is : \(fileURL)")

        return fileURL.path!
    }

 func copyFile(fileName: NSString , filePath : NSString) {
        let dPath: String = getPath(fileName as String)
        let fileManager = NSFileManager.defaultManager()
        if !fileManager.fileExistsAtPath(dPath) {



            let fromPath : NSURL = NSURL.fileURLWithPath(filePath);            
            var error : NSError?
            do {
                try fileManager.copyItemAtPath(fromPath.path!, toPath: dPath)
            } catch let error1 as NSError {
                error = error1
            }
            let alert: UIAlertView = UIAlertView()
            if (error != nil) {
                alert.title = "Error Occured"
                alert.message = error?.localizedDescription
            } else {
                alert.title = "Successfully Copy"
                alert.message = "Your File copy successfully"
            }
            alert.delegate = nil
            alert.addButtonWithTitle("Ok")
            alert.show()
        }
    }

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
}

希望对你有帮助:)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      最近更新 更多