Reputation: 501
In my app, a button segues (with url link) to a new UIViewController
which contains a webView
. This works, fine. But the problem is once the users starts clicking on multiple links inside the webView
, the memory usage starts to increase and on continues growing it reaches a point where it exceed more than 300mb and my app crashes.
I am trying to figure out how to deal with this? Is there a better way to deal with memory issues in webView? Or is there a way I can open the link in safari browser and have a small return button at the top that takes back to my app? Will this solve the memory issue of my app? If yes, how do I code this?
Currently I am using standard code inside the UIViewController
which contains the webView
as below:
var productUrl: String? // Received from previous ViewController segue
Override func viewDidLoad() {
// Enable zoomIn/Out option for users
webView.scalesPageToFit = true
webView.delegate = self
// Validate URL
NSURL.validateUrl(productUrl!, completion: { (success, urlString, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if (success) {
print("Success")
self.url = NSURL (string: urlString!)
let requestObj = NSURLRequest(URL: self.url!);
self.webView.loadRequest(requestObj);
}
else {
print("Fail")
}
})
})
}
func webViewDidStartLoad(webView: UIWebView) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
activityIndicator.startAnimating()
funcToCallWhenStartLoadingYourWebview()
}
func webViewDidFinishLoad(webView: UIWebView) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
activityIndicator.stopAnimating()
funcToCallCalledWhenUIWebViewFinishesLoading()
}
Upvotes: 0
Views: 402
Reputation: 838
There are few tutorials which will help you solve this. Try looking at a very nice WebKit tutorial from Joyce Echessa on appcoda
. This will help you solve your problem.
The other thing that you have to deal with in Joyce Echessa's tutorial is that when you switch back from your webKit view to other view, you will get a crash as the tutorial does not include a way to remove the registered observer. But this can be solved by using the following code below (which removes the "loading" and "estimatedProgress" keypaths. I am not including the description here as it would be injustice for Joyce Echessa who might have worked hard on it. So you will get a better idea once you look at the tutorial as it is well documented.
Once you test the tutorial and experience a crash, try putting the following code to remove created observers in viewDidDissapear block.
override func viewWillDisappear(animated: Bool) {
if (webView.loading) {
webView.stopLoading()
}
progressView.setProgress(0.0, animated: false)
webView.removeObserver(self, forKeyPath: "estimatedProgress")
webView.removeObserver(self, forKeyPath: "loading")
webView.navigationDelegate = nil
webView.UIDelegate = nil
}
Upvotes: 1