如何使用UIWebView删除内存泄漏?

时间:2016-12-26 06:39:40

标签: ios swift http memory-leaks uiwebview

我有一个UIWebView,里面我必须加载一个网址。

问题是打开webView内存后发生泄漏。 我的意思是我无法消除内存泄漏。

以下是我的代码: -

import UIKit
import Toast_Swift


class WebViewController: UIViewController,UIWebViewDelegate {

//WebView
@IBOutlet weak var webView: UIWebView!

//URL
var strUrl : String? = nil

//Tag
var tag : Int! = 0

//ViewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()

    //Delegate of web view
    webView.delegate = self
    //webView.stringByEvaluatingJavaScript(from: "localStorage.clear();")
    self.webView.loadRequest(URLRequest(url: URL(string: self.strUrl!)!))

    //Loading View
    self.view.makeToastActivity(.center)
}

//MARK :- Web view delegate.
func webViewDidFinishLoad(_ webView: UIWebView) {

    //ToastManager.shared.tapToDismissEnabled = true
    self.view.hideToastActivity()
}

//Button Back Action
@IBAction func btnBack(_ sender: Any) {


    if (tag == 1) {
        webView.delegate = nil
        self.strUrl = ""
        webView.removeCache()
        let gotoCreateView = self.storyboard?.instantiateViewController(withIdentifier: "CreateAccountView") as! CreateAccountView

        self.present(gotoCreateView, animated: true, completion: nil)

    } else {

        webView.delegate = nil
        self.strUrl = ""
        webView.removeCache()
        let gotoAboutUsView = self.storyboard?.instantiateViewController(withIdentifier: "AboutUsView") as! AboutUsView

        self.present(gotoAboutUsView, animated: true, completion: nil)
    }


    /*if (1 == tag)
    {
        webView.delegate = nil
        webView.removeCache()
        let gotoCreateView = self.storyboard?.instantiateViewController(withIdentifier: "CreateAccountView") as! CreateAccountView

        self.present(gotoCreateView, animated: true, completion: nil)

    }

    else
    {
        webView.delegate = nil
        webView.removeCache()
        let gotoAboutUsView = self.storyboard?.instantiateViewController(withIdentifier: "AboutUsView") as! AboutUsView

        self.present(gotoAboutUsView, animated: true, completion: nil)
    }*/
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    webView.delegate = nil
    webView.removeCache()
    webView.delegate = self
    self.webView.reload()
 }
}

extension UIWebView
{
 func removeCache()
 {
    URLCache.shared.removeAllCachedResponses()
    URLCache.shared.diskCapacity = 0
    URLCache.shared.memoryCapacity = 0

    if let cookies = HTTPCookieStorage.shared.cookies {
        for cookie in cookies {
            HTTPCookieStorage.shared.deleteCookie(cookie)
        }
    }
  }
}

如何消除内存泄漏?

由于

1 个答案:

答案 0 :(得分:2)

除了您的代码,您还需要获得以下几点:

  1. 第一件事是尝试不在主视图中添加webView,而不是这样你可以设置alpha或hidden属性。如果您正在使用隐藏属性,那么在取消隐藏时将其委托设置为nil并尝试管理WebView在隐藏时无法在后台运行。

  2. 如果您在新的ViewController中显示,那么当我们推送WebView时,请设置其委托并重新加载请求。现在,当你试图从那个视图回来。在弹出之前,将其委托设置为nil,将nil设置为其中使用的所有局部变量。

  3. 例如:

    在ViewDidLoad上:你正在设置委托, 现在当你弹出时,意味着移动到上一个屏幕使用这些代码行:

    DispatchQueue.main.async(execute: {
    
          if self.presentedViewController == nil {
               print("Alert comes up with the intended ViewController")
               var inputTextField = UITextField()
    
               let textPrompt = UIAlertController(title: "Test", message: "Testing", preferredStyle: .alert)
    
               textPrompt.addAction(UIAlertAction(title: "Continue", style: .default, handler: {
                   (action) -> Void in
                   // if the input matches the required text
    
                   let str = inputTextField.text
                   if str == requireTextInput {
                        print("right")
                   } else {
                        print("wrong")
                   }
    
               }))
    
               textPrompt.addTextField(configurationHandler: {(textField: UITextField!) in
                    textField.placeholder = ""
                    inputTextField = textField
    
                })
                weakSelf?.present(textPrompt, animated: true, completion: nil)
          } else {
                // either the Alert is already presented, or any other view controller
                // is active (e.g. a PopOver)
                // ...
                let thePresentedVC : UIViewController? = self.presentedViewController as UIViewController?
                if thePresentedVC != nil {
                     if let _ : UIAlertController = thePresentedVC as? UIAlertController {
                          print("Alert not necessary, already on the screen !")
    
                  } else {
    
                          print("Alert comes up via another presented VC, e.g. a PopOver")
                  }
                }
           }
    })
    

      webView.delegate = nil
      webView.removeCache()
    

    在后退按钮上:

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        webView.delegate = nil
        webView.removeCache() 
        webView.delegate = self
        self.webView.reload()
     }
    
    }