webView快取

weixin_34208283發表於2016-12-30
1.快取策略詳見API
public enum NSURLRequestCachePolicy : UInt {
    //快取策略定義在 web 協議實現中,用於請求特定的URL。是預設的URL快取策略
    case UseProtocolCachePolicy

    //從服務端獲取資料,忽略本地快取
    case ReloadIgnoringLocalCacheData

    //不僅忽略本地的快取資料,還忽略中間網路媒介(如代理伺服器)忽略快取。直接從最原始的伺服器拿取
    case ReloadIgnoringLocalAndRemoteCacheData // Unimplemented

    //被NSURLRequestReloadIgnoringLocalCacheData替換了
Replaced by NSURLRequestReloadIgnoringLocalCacheData.
    public static var ReloadIgnoringCacheData: NSURLRequestCachePolicy { get }

    //已經存在的快取資料用於請求返回,不管它的過期日期和已經存在了多久。如果沒有請求對應的快取資料,從資料來源讀取
    case ReturnCacheDataElseLoad

    //已經存在的快取資料用於請求返回,不管它的過期日期和已經存在了多久。如果沒有請求對應的快取資料,不要去資料來源讀取,該請求被設定為失敗,這種情況多用於離線模式
    case ReturnCacheDataDontLoad

     //已經存在的快取資料先去資料來源驗證有效性,如果無效,將從資料來源獲取
    case ReloadRevalidatingCacheData // Unimplemented
}
2.上部分關鍵程式碼
class BaseWebViewController: UIViewController,UIWebViewDelegate {
     /// UIWebView
    lazy var webView:UIWebView
        = {
            let web = UIWebView(frame: CGRectZero).then({
                let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(self.requestURL!)
                var request = NSMutableURLRequest(URL: self.requestURL!)
                //判斷請求方式
                if self.requestURL?.absoluteString.containsString(API_shoppingCart) == true {
                  request.HTTPMethod = "POST"
                }else{
                  request.HTTPMethod = "GET"
                }
                //快取策略定義在 web 協議實現中,用於請求特定的URL。是預設的URL快取策略
                request.cachePolicy = .UseProtocolCachePolicy
                //物件代表一個HTTP cookie。 這是一個不可改變的物件,從一個包含cookie的屬性的字典初始化,這個類可以用來手動建立cookie的Properties 。
                request.HTTPShouldHandleCookies = true
                request.allHTTPHeaderFields = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
                $0.loadRequest(request)
            })
            return web
    }()


     func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
          //判斷是否為購物車URL
          if request.URL?.absoluteString == API_shoppingCart {

            //獲取session_id
            let session_id = (NSUserDefaults.standardUserDefaults().valueForKey("session_id") as? String) ?? ""

            var shoppingCart = ""

            //判斷登入狀態 1為未登入,然後相應根據session_id拼接URL
            if   let user_id = HLCheckUserID(true) == 1 {
                shoppingCart = API_shoppingCart + "&session_id=\(session_id.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!)" + "&user_id="
            }else{
                shoppingCart = API_shoppingCart + "&session_id=\(session_id.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!)" + "&user_id=\(HLCheckUserID(true))"
            }
    
            let newRequest = NSMutableURLRequest(URL: NSURL(string: shoppingCart)!)
            
            let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(NSURL(string: shoppingCart)!)
            newRequest.HTTPMethod = "POST"
            newRequest.cachePolicy = .UseProtocolCachePolicy
            newRequest.HTTPShouldHandleCookies = true
            newRequest.allHTTPHeaderFields = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
            webView.loadRequest(newRequest)
            return false
        }
       return true
  }

    func webViewDidFinishLoad(webView: UIWebView){ 
        //對cookie進行快取處理
        saveSessionIDCookie()

   }

//對cookie進行快取處理
    func saveSessionIDCookie() {
        let cookiesToSet = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(requestURL!)!
        var tempCookies: [NSHTTPCookie] = []
        for cookie in cookiesToSet {
            
            let params = [NSHTTPCookieValue: cookie.value, NSHTTPCookieName: cookie.name, NSHTTPCookiePath: cookie.path, NSHTTPCookieDomain: cookie.domain, NSHTTPCookieExpires: NSDate(timeIntervalSinceNow: 3600*24*30)]
            let tempCookie = NSHTTPCookie(properties: params)
            tempCookies.append(tempCookie!)
        }
        NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(tempCookies, forURL: requestURL!, mainDocumentURL: nil)
    }
    

}

相關文章