我想缓存我的webview内容以加快SWIFT3加载速度

时间:2017-03-18 07:29:06

标签: ios swift3

到目前为止,我尝试了这个,但是我发现了连接超时错误。如何通过缓存更快地加载Web视图可以有人帮忙吗?(swift3)

这是我的代码

import UIKit

class test:UIViewController, NSURLConnectionDelegate{
var response: URLResponse?
var error: NSError?
var NSURLRequestReturnCacheDataElseLoad = 2
var sesson:URLSession!
var progressView:UIProgressView!
var urlData: Data?
var baseURLString: String = "https://google.com"

@IBOutlet weak var SubscribeWeb: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    var urlString: String = URL(fileURLWithPath: baseURLString).appendingPathComponent("/").absoluteString

    print("connection urlString = \(urlString)")
    let request = URLRequest(url: URL(string : urlString)!,
                             cachePolicy:NSURLRequest.CachePolicy.returnCacheDataElseLoad,
                             timeoutInterval: 100.0)
    print("connection request = \(request)")
    // var request = URLRequest(url: URL(string: urlString), cachePolicy: URLRequestReturnCacheDataElseLoad, timeoutInterval: 10.0)
    var connection = NSURLConnection(request: request, delegate: nil)
    print("connection = \(connection)")
    if (connection != nil) {

        do
        {

            try self.urlData = NSURLConnection.sendSynchronousRequest(request, returning: &response)//
            print("self.urlData = \(self.urlData)")
        }
        catch (let e) {
            print("error = \(e)")
        }



        let htmlString = String(data: urlData!, encoding: String.Encoding.utf8)
        //String(urlData,encode(with: String.Encoding.utf8))
        //  var htmlString = String(urlData, encoding: String.Encoding.utf8)

        let fileUrl = Foundation.URL(string: baseURLString)


        SubscribeWeb.loadHTMLString(htmlString!, baseURL: fileUrl)
        //SubscribeWeb.loadHTMLString(<#T##string: String##String#>, baseURL: <#T##URL?#>)
    }
    //ara test
    //        let url = NSURL (string: "https://google.com/")
    //        let requestObj = URLRequest(url: url! as URL,
    //                                         cachePolicy:NSURLRequest.CachePolicy.returnCacheDataElseLoad,
    //                                         timeoutInterval: 10.0)
    //       // let requestObj = URLRequest(url: url! as URL)
    //        SubscribeWeb.loadRequest(requestObj)
    // Do any additional setup after loading the view, typically from a nib.
}    //ara test

1 个答案:

答案 0 :(得分:0)

不确定,但您已在本地创建.html文件,并通过URL在此文件中写入数据。可能是工作。