iOS 7 UIWebView 304 cache bug, blank pages - ios

I have a problem I have discovered in my app that has a UIWebView. iOS 7 caches a blank body 304 response, resulting in blank pages being shown when the user refreshes the UIWebView. This is not good user expierience and I'm trying to figure out how to solve this on the iOS side, as I do not have control over how Amazon S3 responds to headers (that's who I use for my resource hosting).
More details of this bug were found by these people: http://tech.vg.no/2013/10/02/ios7-bug-shows-white-page-when-getting-304-not-modified-from-server/
I'd appreciate any help offered to how I can solve this on the app side and not the server side.
Thank you.
Update: fixed this bug using the bounty's suggestion as a guideline:
#property (nonatomic, strong) NSString *lastURL;
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([self.webView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"].length < 1)
{
NSLog(#"Reconstructing request...");
NSString *uniqueURL = [NSString stringWithFormat:#"%#?t=%#", self.lastURL, [[NSProcessInfo processInfo] globallyUniqueString]];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:uniqueURL] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:5.0]];
}
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
self.lastURL = [request.URL absoluteString];
return YES;
}

You can implement a NSURLProtocol, and then in +canonicalRequestForRequest: modify the request to override the cache policy.
This will work for all requests made, including for static resources in the web view which are not normally consulted with the public API delegate.
This is very powerful, and yet, rather easy to implement.
Here is more information:
http://nshipster.com/nsurlprotocol/
Reference:
https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSURLProtocol_Class/Reference/Reference.html
Here is an example:
#interface NoCacheProtocol : NSURLProtocol
#end
#implementation NoCacheProtocol
+ (void)load
{
[NSURLProtocol registerClass:[NoCacheProtocol class]];
}
+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest
{
if ([NSURLProtocol propertyForKey:#“ProtocolRequest” inRequest:theRequest] == nil) {
return YES;
}
return NO;
}
+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)theRequest
{
NSMutableURLRequest* request = [theRequest mutableCopy];
[request setCachePolicy: NSURLRequestReloadIgnoringLocalCacheData];
//Prevent infinite recursion:
[NSURLProtocol setProperty:#YES forKey:#"ProtocolRequest" inRequest:request];
return request;
}
- (void)startLoading
{
//This is an example and very simple load..
[NSURLConnection sendAsynchronousRequest:self.request queue:[NSOperationQueue currentQueue] completionHandler:^ (NSURLResponse* response, NSData* data, NSError* error) {
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
}];
}
- (void)stopLoading
{
NSLog(#"something went wrong!");
}
#end

As the other questions are to use the NSURLConnection every time, which seems like a bit of an overhead:
Why don't you execute a small javascript after the page was loaded (complete or incomplete) that can tell you if the page is actually showing? Query for a tag that should be there (say your content div) and give a true/false back using the
[UIWebView stringByEvaluatingJavaScriptFromString:#"document.getElementById('adcHeader')!=null"]
And then, should that return false, you can reload the URL manually using the cache-breaker technique you described yourself:
NSString *uniqueURL = [NSString stringWithFormat:#"%#?t=%d", self.url, [[NSDate date] timeIntervalSince1970]];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:uniqueURL] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:5.0]];
[edit]
based on the discussion in the comments and some of the other answers, I think you might have the best solution manually changing the NSURLCache.
From what I gathered, you're mainly trying to solve a reload/reshow scenario. In that case, query the NSURLCache if a correct response is there, and if not delete the storedvalue before reloading the UIWebView.
[edit 2]
based on your new results, try to delete the NSURLCache when it is corrupted:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache]cachedResponseForRequest:request];
if (cachedResponse != nil && [[cachedResponse data] length] > 0)
{
NSLog(#"%#",cachedResponse.response);
} else {
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
}
return YES;
}
We might have to refine the check if the cache is invalid again, but in theory this should do the trick!

NSURL *URL = [NSURL URLWithString:#"http://mywebsite.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30.0];
[myWebView loadRequest: request];
When creating NSURLRequest instance, you can set Cache Policy.
Hope it works!

Related

When I implement the decidePolicyForNavigationAction delegate methond,the Post request will be invalid in WKWebView

my system version is iOS 11.2.6 but i think in higher version have the same appearance.
i post a request in wkwebview like this and it works fine
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
request.HTTPMethod = #"POST";
request.HTTPBody = [postStr dataUsingEncoding:NSUTF8StringEncoding];
WKWebView *webView = [[WKWebView alloc]initWithFrame:rectDown];
webview.frame = self.view.frame;
[webview loadRequest:request];
[self.view addSubview:webview];
but if i implement the decidePolicyForNavigationAction delegate method like down,the nodejs server can't receive any post data
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:
(WKNavigationAction *)navigationAction decisionHandler:(void (^)
(WKNavigationActionPolicy))decisionHandler{
decisionHandler(WKNavigationActionPolicyAllow);
}
and I want to reuse a wkwebview object anyone have a good idea?
additional i found that when i first load the post request and back then reload and back again reload again it's always works right ,but if I reuse the wkwebview load any other url like google then it can't load the post request anymore.if if don't implement the delegate decidePolicyForNavigationAction method ,it will always works fine.
so ,this is a conflict between decidePolicyForNavigationAction and a reuse wkwebview?
I use this code to format the reuse wkwebview when the wkwebview's controller is remove
-(void)webFormat{
if (#available(iOS 9.0,*)) {
NSSet *websiteDataTypes = [NSSet setWithObjects:WKWebsiteDataTypeDiskCache,
WKWebsiteDataTypeOfflineWebApplicationCache,
WKWebsiteDataTypeMemoryCache,
nil];
// NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
}];
}
[self.configuration.userContentController removeScriptMessageHandlerForName:kScriptHandlerName];
[self.configuration.userContentController removeAllUserScripts];
[self stopLoading];
[self loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"about:blank"]]];
self.scrollView.delegate = nil;
[self setUIDelegate:nil];
}
I fix this by add code
self.navigationDelegate = nil
in webFormat function .Even when the function webFormat run ,self.navigationDelegate is nil already;I thought that when the viewController remove,as the navigationDelegate of wkwebview ,left something in the corner and influence the webview's next load.who knows.

iOS xcode Alternative to UIWebview didFinishLoad

I have a webview that when loaded, the user is logged in by a POST request. After they are logged in, I want them to be taken to a webpage. My POST request is a URL as follows:
- (void)viewDidLoad {
[super viewDidLoad];
[_scoreWebView setDelegate:self];
NSMutableURLRequest *detailRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"myrul"]];
[detailRequest setHTTPMethod:#"POST"];
NSString *sendInfo =[NSString stringWithFormat:#"action=login&EMAIL=email&PASSWORD=password", nil];
NSData *infoData = [sendInfo dataUsingEncoding:NSUTF8StringEncoding];
[detailRequest setHTTPBody:infoData];
[_scoreWebView loadRequest:detailRequest];
}
This log in process works fine. However, after I send the user to my webpage it is launching webviewdidfinishload infinitely. I know that it fires each time something is loaded. Is there an alternate solution to redirecting the user to my page after log in? Also, I have three different pages that the user could be redirected to based on their input, this is just one of them for simplicity. This is my finishload method:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//Check here if still webview is loding the content
if (webView.isLoading)
return;
else //finished
NSLog(#"finished loading");
NSLog(#"%# in calendar", _thisScriptUniqueID);
NSString *fullURL=[NSString stringWithFormat:#"myurl/%##score", _thisScriptUniqueID];
NSLog(#"%#", fullURL);
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_scoreWebView loadRequest:requestObj];
}
Is there a different method that could be used to take the user to the page, or would it be possible to include both in the viewDidLoad?
After a lot of research, I decided that the functionality would work a lot better on the server side. I made it so that the same URL logs the user in and brings them to the desired page at the same time.

How to download a file from the webview in os x and save it to a specific location

I have looked everywhere and have not found exactly what I am looking for, so here is my question:
I have a basic app I am playing around with. I have created a webview and would like to be able to download a file from the website that loads in the webview and save the file to say the Downloads folder on the local machine. The site loads fine inside the webview, now how do I download a file, say an .xml file from the site and save it to the Downloads folder on the local machine?
This is what I have so far:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];//<-- example site
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[webView mainFrame] loadRequest:request];
}
I would like to be able to download a file (possible using a delegate) then save it to a location on the local computer. I am pretty new to this so I'd appreciate any help.
The issue has been resolved. I added the following code to make it work:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSURL *url = [NSURL URLWithString:#"http://www.google.com"]; // <-- example website
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.webView.policyDelegate = self;
[self.webView setDownloadDelegate:self];
[[self.webView mainFrame] loadRequest:request];
}
- (void)webView:(WebView *)webView decidePolicyForMIMEType:(NSString *)type
request:(NSURLRequest *)request
frame:(WebFrame *)frame
decisionListener:(id < WebPolicyDecisionListener >)listener
{
if([type isEqualToString:#"application/octet-stream"]) //this is the type I was looking for
{
//figure out how to save file here
[listener download];
NSURLDownload *downLoad = [[NSURLDownload alloc] initWithRequest:request delegate:self];
if(downLoad)
{
[self download:downLoad decideDestinationWithSuggestedFilename:#"filename.ext"];
NSLog(#"File Downloaded Succesfully");
//[webView close];
[self.window close];
}
else
{
NSLog(#"The download failed");
}
}
//just ignore all other types; the default behaviour will be used
}
-(void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename
{
NSString *destinationFileName;
NSString *homeDirectory = NSHomeDirectory();
destinationFileName = [[homeDirectory stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:filename];
[download setDestination:destinationFileName allowOverwrite:NO]; //file is being saved to the Documents folder on the local machine
}
Hope this will be helpful to someone else.

Cached images in UIWebView take longer to load? (NSURLProtocol?)

I'm serving up local images to my UIWebView via NSURLProtocol (which means the image is returned almost immediately), but I'm experiencing an issue where cached images (images being displayed again after their first load) take longer to load. Is there something in my NSURLProtocol causing this?
#implementation URLProtocol
+ (BOOL) canInitWithRequest:(NSURLRequest *)request {
return [request.URL.scheme isEqualToString:#"file"] ||
[request.URL.scheme isEqualToString:#"http"];
}
+ (NSURLRequest*) canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
- (void) startLoading {
id<NSURLProtocolClient> client = self.client;
NSURLRequest* request = self.request;
NSString *fileToLoad = request.URL.absoluteString;
NSURLResponse *response;
if([fileToLoad hasPrefix:#"http://app-fullpath/"]){
fileToLoad = [fileToLoad stringByReplacingOccurrencesOfString:#"http://app-fullpath/" withString:#""];
} else {
fileToLoad = [[NSURL URLWithString:fileToLoad] path];
}
NSData* data = [NSData dataWithContentsOfFile:fileToLoad];
response = [[NSHTTPURLResponse alloc] initWithURL:[request URL] statusCode:200 HTTPVersion:#"HTTP/1.1" headerFields:[NSDictionary dictionary]];
[client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[client URLProtocol:self didLoadData:data];
[client URLProtocolDidFinishLoading:self];
}
- (void) stopLoading { }
#end
Any speed suggestions, javascript/html or iOS?
My problem was that UIWebView gives text a much higher priority than images, so text is laid out first, then images are processed. In order to fix that I created a DOM representation of my HTML & Images, then I replaced all images with images loaded via javascript (new Image()) and they show instantly.

Making a Unified address search bar in ios 5?

Help making a Unified address bar in ios 5 for a Browser App? So here is my address bar.
-(IBAction)url:(id)sender {
NSString *query = [urlBar.text stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#", query]];
NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
[webPage loadRequest:request];
}
Couldn't I add an "else" reference to say if it is not an address then append the google search tag? If so how? And would you know how to use Bing instead of google?
-(IBAction)googleSearch:(id)sender {
NSString *query = [googleSearch.text stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com/search?hl=en&site=&q=%#", query]];
NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
[webPage loadRequest:request];
}
Here are some tips to help you:
use stringByAddingPercentEscapesUsingEncoding: instead of your "+" replacement.
you should check if http:// is not a prefix to the URL string before adding it
you should implement the UIWebViewDelegate protocol to identify when an error occurs when loading an invalid URL
then as a fallback launch your Google search (now you can replace " " by "+")... or Bing, whatever and up to you!
Your code should looks something as follow:
...
webView.delegate = self; // Should appear in your code somewhere
...
-(IBAction)performSearch {
if ([searchBar.text hasPrefix:#"http://"]) {
... // Make NSURL from NSString using stringByAddingPercentEscapesUsingEncoding: among other things
[webView loadRequest:...]
} else if ([self isProbablyURL:searchBar.text]) {
... // Make NSURL from NSString appending http:// and using stringByAddingPercentEscapesUsingEncoding: among other things
[webView loadRequest:...]
} else {
[self performGoogleSearchWithText:searchBar.text]
}
}
- (BOOL)isProbablyURL:(NSString *)text {
... // do something smart and return YES or NO
}
- (void)performGoogleSearchWithText:(NSString *)text {
... // Make a google request from text and mark it as not being "fallbackable" on a google search as it is already a Google Search
[webView loadRequest:...]
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
... // Notify user
if (was not already a Google Search) {
[self performGoogleSearchWithText:searchBar.text]
}
}

Resources