I am migrating from UIWebView to WKWebView and facing problem in cookies management. As app need to support iOS 10 I am not adding cookies through WKHTTPCookieStore instead, I am following the below code:
- (void)loadURL:(NSString *)url
{
NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* cookies = [storage cookiesForURL:[NSURL URLWithString:url]];
NSMutableString *cookieStr = [NSMutableString string];
for (NSHTTPCookie *cookie in cookies) {
if (cookieStr.length) {
[cookieStr appendString:#"; "];
}
[cookieStr appendFormat:#"%#=%#", cookie.name, cookie.value];
}
NSLog(#"Cookie: %#",cookieStr);
[req addValue:cookieStr forHTTPHeaderField:#"Cookie"];
NSMutableString *cookieStrAfterDocLoad = [NSMutableString string];
for (NSHTTPCookie *cookie in cookies) {
[cookieStrAfterDocLoad appendFormat:#"document.cookie = '%#=%#';", cookie.name, cookie.value];
}
WKUserScript *userScript = [[WKUserScript alloc] initWithSource: cookieStrAfterDocLoad
injectionTime: WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[self.wkWebView.configuration.userContentController addUserScript:userScript];
[self.wkWebView loadRequest:req];
}
I need to add the cookies after the document load to maintain the session for internal navigation.
This is not the correct way as the new cookies may be added or old may be modified at the time of page load. This needs to be done in many other controllers.
My question is how can I know if the cookies were added at every for loadRequst in UIWebview, or is there any other correct way to handle this situation in WKWebview as some webpage load might not need the cookies?
Is this the correct way to add cookies for every loadRequest?
how I can enable caching in an UIWebView?
It's frustrating. I'm looking for hours but no mentioned solutions in many other posts doesn't helped me.
I tried many solutions like https://stackoverflow.com/a/26174438, https://stackoverflow.com/a/1424301, http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/, https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Concepts/CachePolicies.html, iOS Cache a UIWebView, etc.
My code looks like
[self setUrl:[[NSString alloc] initWithFormat:#"http://example.com"]];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[self setLoadUrl: [NSURL URLWithString:[self url]]];
[self setRequestObj:[NSURLRequest requestWithURL:[self loadUrl]]];
if cachingis disabled. If it's turned on I have
if([[self cache] isEqualToNumber:[[NSNumber alloc] initWithInt:1]])
{
[[NSURLCache sharedURLCache] setDiskCapacity:4 * 1024 * 1024];
[[NSURLCache sharedURLCache] setMemoryCapacity:32 * 1024 * 1024];
[self setRequestObj:[NSURLRequest requestWithURL:loadUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]];
}
How
#Premox I think you can choose a different way. After your uiwebview loaded page you can get a response html convert to NSString class and save it to cache or serialize as you wanna
I'm making a series of requests with UIWebView and I need to keep UIWebView's cache clear so that I could start each new request from scratch. So before performing every request I'm doing the following:
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
But unfortunately it doesn't help. Every time the first request takes approximately 4 seconds while every following request about 1.5 seconds, so obviously the loaded data is being cached somewhere.
I also tried set caching policy for the request explicitly, like this:
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
[self.webView loadRequest:request];
but it doesn't help as well. The very first request takes significantly longer time than the following ones. Just like without setting caching policy for the request at all.
Any ideas, guys?
Try this code:
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *each in cookieStorage.cookies)
{
[cookieStorage deleteCookie:each];
}
Try using NSURLCacheStorageNotAllowed. This specifies that storage in NSURLCache is not allowed in any fashion, either in memory or on disk.
↳ Foundation Framework Reference > NSCachedURLResponse Class Reference
I am loading URL in UIWebview and it is working fine.But during loading of web request it is consuming memory too much.Whenever i load some URL in UIWebview memory is increased from 30mb to 95mb and based on each link clicked in UIWebview it is still increasing and reach to 180mb and so on.I used some code to remove memoryin UIWebview.But there is no benefit.I have done memory management by Analyze in Xcode but there are no leaks and i also check allocations and leaks.It is just creating one instance of UIWebview.
This is my code:
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
int cacheSizeMemory = 4*1024*1024; // 4MB
int cacheSizeDisk = 32*1024*1024; // 32MB
NSURLCache *sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:#"nsurlcache"] autorelease];
[NSURLCache setSharedURLCache:sharedCache];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
ViewController.h
#property(nonatomic,strong)UIWebview *webview;
ViewController.m
#synthesize webview;
-(void)viewdidLoad
{
NSString *urlString = #"some url";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webview=[uiwebview alloc]init];
[self.webview loadRequest:request];
}
/*webview delegates
-(void)viewWillDisappear:(Bool)animated
{
self.webview=nil;
[self.webview removefromSuperView]
[self.webview loadHtmlString:#"" baseUrl:nil]
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:NSURLRequest];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
if([[cookie domain] isEqualToString:someNSStringUrlDomain]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
I am facing this issue for few days.Please give me some alternative or method to remove UIWebviewmemory.
In viewWillDisapear You are setting your WebView reference to nil so the removing in the next line fails.
Try setting your reference to nil after you completed all cleanup around the WebView, i.e. in the last line of the method.
You probably also need to remove the delegate of the WebView (before nilling).
As dogsgod is pointed out the way OP release memory is not proper, but
there are other things which should mention for this type of question.
If you are developing new application I suggest you to use ARC for your project
If its not possible to implement ARC then follow below advice
In viewdidLoad() you are allocating object that's good but its better if you first check that is object is already allocated of not (as it may change that it is allocated before pushing it into navigation).
Sample Code
if(self.webview!=nil)
{
self.webview = nil; // release memory
}
// Code for allocating memory.
If you alloc object in viewDidLoad() then must be deallco in dealloc() method.
NOTE:
When you assign any object nil, it means now object is not point to the old location and you have no control over that object, so calling some method like [self.webview removefromSuperView] after assigning nil to webview it have no effect.
Extra note:
Please read this document for knowledge about methods like viewDidload,viewWillAppear ... etc.
I have used UIWebview to load a web page using loadRequest: method, when I leave that scene I call [self.webView stopLoading]; and release the webView.
In activity monitor on first launch i have seen that the real memory increased by 4MB, and on multiple launches/loading the real memory doesn't increase. It is increasing only once.
I have checked the retain count of webview. It is proper i.e., 0. I think UIWebView is caching some data. How do I avoid caching or remove cached data? Or is there another reason for this?
I actually think it may retain cached information when you close out the UIWebView. I've tried removing a UIWebView from my UIViewController, releasing it, then creating a new one. The new one remembered exactly where I was at when I went back to an address without having to reload everything (it remembered my previous UIWebView was logged in).
So a couple of suggestions:
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:NSURLRequest];
This would remove a cached response for a specific request. There is also a call that will remove all cached responses for all requests ran on the UIWebView:
[[NSURLCache sharedURLCache] removeAllCachedResponses];
After that, you can try deleting any associated cookies with the UIWebView:
for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
if([[cookie domain] isEqualToString:someNSStringUrlDomain]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
Swift 3:
// Remove all cache
URLCache.shared.removeAllCachedResponses()
// Delete any associated cookies
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
Don't disable caching completely, it'll hurt your app performance and it's unnecessary. The important thing is to explicitly configure the cache at app startup and purge it when necessary.
So in application:DidFinishLaunchingWithOptions: configure the cache limits as follows:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
int cacheSizeMemory = 4*1024*1024; // 4MB
int cacheSizeDisk = 32*1024*1024; // 32MB
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:#"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];
// ... other launching code
}
Once you have it properly configured, then when you need to purge the cache (for example in applicationDidReceiveMemoryWarning or when you close a UIWebView) just do:
[[NSURLCache sharedURLCache] removeAllCachedResponses];
and you'll see the memory is recovered. I blogged about this issue here: http://twobitlabs.com/2012/01/ios-ipad-iphone-nsurlcache-uiwebview-memory-utilization/
You can disable the caching by doing the following:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];
ARC:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
Swift 3.
// Remove all cache
URLCache.shared.removeAllCachedResponses()
// Delete any associated cookies
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
I could not change the code, so I needed command line for testing purpose and figured this could help someone:
Application specific caches are stored in ~/Library/Caches/<bundle-identifier-of-your-app>, so simply remove as below and re-open your application
rm -rf ~/Library/Caches/com.mycompany.appname/
My educated guess is that the memory use you are seeing is not from the page content, but rather from loading UIWebView and all of it's supporting WebKit libraries. I love the UIWebView control, but it is a 'heavy' control that pulls in a very large block of code.
This code is a large sub-set of the iOS Safari browser, and likely initializes a large body of static structures.
After various attempt, only this works well for me (under ios 8):
NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:1 diskCapacity:1 diskPath:nil];
[NSURLCache setSharedURLCache:cache];
For swift 2.0:
let cacheSizeMemory = 4*1024*1024; // 4MB
let cacheSizeDisk = 32*1024*1024; // 32MB
let sharedCache = NSURLCache(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: "nsurlcache")
NSURLCache.setSharedURLCache(sharedCache)
I am loading html pages from Documents and if they have the same name of css file UIWebView it seem it does not throw the previous css rules. Maybe because they have the same URL or something.
I tried this:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];
I tried this :
[[NSURLCache sharedURLCache] removeAllCachedResponses];
I am loading the initial page with:
NSURLRequest *appReq = [NSURLRequest requestWithURL:appURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
It refuses to throw its cached data! Frustrating!
I am doing this inside a PhoneGap (Cordova) application. I have not tried it in isolated UIWebView.
Update1: I have found this.
Changing the html files, though seems very messy.