如何在swift中正确缓存NSURLRequest?

时间:2015-09-15 03:15:15

标签: ios xcode swift caching uiwebview

原谅如果有人问这个问题,但是我已经进行了大量的搜索,而且似乎找不到我正在迅速寻找的答案。我有str1 = ("S8 10 -945 1689 -950 230 -25 1 1e-13") print(str1[0,1].split(' ')) 加载PDF文件,如果用户退出WebView并返回,我不希望用户再次经历繁琐的加载过程,那么如何缓存请求以进行加载更快?

这是我的代码:

UIWebView

更新

我想要完成的事情可以在this video

中看到

这是dropbox的iOS应用程序的一个示例。当其中一个文件已经加载时,每次进入该文件(在本例中为PDF)都会快速而简单。这种方法正是我想要复制的方法。

有什么建议吗?

2 个答案:

答案 0 :(得分:4)

GIF

  1. 第一次进入此ViewController时,您可以看到下载进度
  2. 然后第二次,它只是加载本地文件。所以它很快
  3. 和代码

    class ViewController: UIViewController,NSURLSessionDownloadDelegate{
    var sesson:NSURLSession!
    var webview:UIWebView!
    var progressView:UIProgressView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.sesson =   NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
        self.webview = UIWebView(frame: self.view.frame)
        self.view.addSubview(webview)
        let documentDir = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first as! NSURL
        let pdfFilePath = documentDir.URLByAppendingPathComponent("Test.pdf");
        if NSFileManager.defaultManager().fileExistsAtPath(pdfFilePath.path!){
            let request = NSURLRequest(URL: pdfFilePath)
            webview.loadRequest(request)
        }else{
            progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.Default);
            progressView.frame = CGRectMake(0, 0,200, 4)
            progressView.progress = 0
            progressView.progressTintColor = UIColor.blueColor()
            progressView.center = self.view.center
            self.view.addSubview(progressView)
            let remoteURL = "https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.pdf"
            let request = NSURLRequest(URL: NSURL(string: remoteURL)!)
            let downloadTask = self.sesson.downloadTaskWithRequest(request)
            downloadTask.resume()
        }
        // Do any additional setup after loading the view, typically from a nib.
    }
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        if progressView != nil{
            progressView.removeFromSuperview()
        }
        let documentDir = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first as! NSURL
        let pdfFilePath = documentDir.URLByAppendingPathComponent("Test.pdf");
        NSFileManager.defaultManager().moveItemAtURL(location, toURL: pdfFilePath, error: nil)
        let request = NSURLRequest(URL: pdfFilePath)
        self.webview.loadRequest(request)
    }
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        var curprogress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
        progressView.progress = curprogress
    }
    }
    

答案 1 :(得分:1)

NSURLConnection(和NSURLSession的共享会话)使用共享缓存。您可以将该缓存的策略配置为使用磁盘存储,但我的模糊回忆是iOS默认情况下仅使用内存缓存。看看NSURLCache类,并使用Swift等效的:

NSString *myPath = ... // some subdirectory in your app's caches directory
NSURLCache *cache = [[NSURLCache alloc] initWithCapacity:2048576 /* 2M */
                                            diskCapacity: 134217728 /* 128M */
                                                    path:myPath];
[NSURLCache setSharedURLCache:cache];

或者其他什么,你可能会有更好的运气。

请注意,iOS中的磁盘缓存仍然是临时的,可以由操作系统删除,但仅限于您的应用未运行时(假设最近没有更改)。

这样的东西
let cacheDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as String
var dir = cacheDir.stringByAppendingFormat("/urlCache/")
var cache = NSURLCache(memoryCapacity: 2048576,
   diskCapacity: 134217728,
   path: dir)
NSURLCache.setSharedURLCache(cache)

但我并不熟悉Swift,所以我的语法错误。