UIWebView加载网址并在iOS swift 3中为离线问题保存缓存?

时间:2017-10-14 03:30:38

标签: ios swift uiwebview

更新

我正在尝试在swift中实现Web缓存技术。它将加载url并显示一些数据并在缓存后保存一些数据。在使用coredata保存后,我的数据已存在于我的日志中,但我无法使用这些额外数据更新现有的webview。

我关注的例子来自: https://www.raywenderlich.com/76735/using-nsurlprotocol-swift

首次访问webview:

enter image description here

当点击加载表详细信息时,我在MyURLProtocol.swift类中调用了func连接中的startLoading()方法(_ connection:NSURLConnection!,didFailWithError错误:NSError!)。

如何使用此数据将我当前的网页内容更新为webview?

实现方式:BrowserViewController.swift

import UIKit

class BrowserViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet var textField: UITextField!
  @IBOutlet var webView: UIWebView!

  //MARK: IBAction

  @IBAction func buttonGoClicked(_ sender: UIButton) {
    if self.textField.isFirstResponder {
      self.textField.resignFirstResponder()
    }

    self.sendRequest()
  }

  //MARK: UITextFieldDelegate

  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()

    self.sendRequest()

    return true
  }

  //MARK: Private

  func sendRequest() {
    if let text = self.textField.text {
      //  MyURLProtocol.startLoading()
      // return
      let sampleUrl="https://apple.com"

      let url = URL(string:sampleUrl)
      let request = URLRequest(url:url!)
      self.webView.loadRequest(request)
    }
  }
}

在MyURLProtocol.swift中,我调用了self.startLoading()   func连接(_连接:NSURLConnection!,didFailWithError错误:NSError!)

方法如下:

override func startLoading() {

 print("startLoading url \(self.request)")

// 1
let possibleCachedResponse = self.cachedResponseForCurrentRequest()
if let cachedResponse = possibleCachedResponse {
  print("Serving response from cache")



  // 2
  let data = cachedResponse.value(forKey: "data") as! Data!
  let mimeType = cachedResponse.value(forKey: "mimeType") as! String!
  let encoding = cachedResponse.value(forKey: "encoding") as! String!
  let jsonData = cachedResponse.value(forKey: "jsonData") as! String!

  let response = URLResponse(url: self.request.url!, mimeType: mimeType, expectedContentLength: (data?.count)!, textEncodingName: encoding)

  // 4
  self.client!.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
  self.client!.urlProtocol(self, didLoad: data!)
  self.client!.urlProtocolDidFinishLoading(self)


  print("cache binaryData \(jsonData)")

} else {
  // 5
  print("Serving response from NSURLConnection")

  let newRequest = (self.request as NSURLRequest).mutableCopy() as! NSMutableURLRequest
  URLProtocol.setProperty(true, forKey: "MyURLProtocolHandledKey", in: newRequest)
  self.connection = NSURLConnection(request: newRequest as URLRequest, delegate: self)
}
}

我的数据在jsondata中,我需要在我的webview中根据保存的数据显示。

0 个答案:

没有答案