Giter VIP home page Giter VIP logo

wkwebviewtips's Introduction

This is what I learned about WKWebView, Apple's new WebKit API debuted on iOS 8.

As of this writing, the latest iOS version is iOS 8.1.3.

file:/// doesn't work without tmp directory

Only the tmp directory access can be accessed with the file: scheme, as of iOS 8.0.2.

You can see what directory access is allowed on the shazron / WKWebViewFIleUrlTest GitHut repo.

Note: On iOS 9.0.0 (beta), you can use the below method to load files from Documents, Library and tmp folders. But App Bundle cannot. - (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL NS_AVAILABLE(10_11, 9_0);

Can't handle in Storyboard and Interface Builder

You need to set WKWebView and any NSLayoutConstraints programmatically.

HTML <a> tag with target="_blank" won't respond

See Stack Overflow: Why is WKWebView not opening links with target=“_blank”

URL Scheme and App Store links won't work

Example

// Using [bendytree/Objective-C-RegEx-Categories](https://github.com/bendytree/Objective-C-RegEx-Categories) to check URL String
#import "RegExCategories.h"

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *url = navigationAction.request.URL;
    NSString *urlString = (url) ? url.absoluteString : @"";

    // iTunes: App Store link
    if ([urlString isMatch:RX(@"\\/\\/itunes\\.apple\\.com\\/")]) {
        [[UIApplication sharedApplication] openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    // Protocol/URL-Scheme without http(s)
    else if (![urlString isMatch:[@"^https?:\\/\\/." toRxIgnoreCase:YES]]) {
        [[UIApplication sharedApplication] openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

alert, confirm, prompt from JavaScript needs to set WKUIDelegate methods

If you want to show dialog boxes, you have to implement the following methods:

webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler: webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler: webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:

Here is how to set those.

Basic/Digest/etc authentication input dialog boxes need to set a WKNavigationDelegate method

If you want to present an authentication challenge to user, you have to implement the method below:

webView:didReceiveAuthenticationChallenge:completionHandler:

Example:

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
    NSString *hostName = webView.URL.host;
    
    NSString *authenticationMethod = [[challenge protectionSpace] authenticationMethod];
    if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodDefault]
        || [authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]
        || [authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPDigest]) {
        
        NSString *title = @"Authentication Challenge";
        NSString *message = [NSString stringWithFormat:@"%@ requires user name and password", hostName];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            textField.placeholder = @"User";
            //textField.secureTextEntry = YES;
        }];
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            textField.placeholder = @"Password";
            textField.secureTextEntry = YES;
        }];
        [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            NSString *userName = ((UITextField *)alertController.textFields[0]).text;
            NSString *password = ((UITextField *)alertController.textFields[1]).text;
            
            NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:userName password:password persistence:NSURLCredentialPersistenceNone];
            
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self presentViewController:alertController animated:YES completion:^{}];
        });
        
    }
    else if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        // needs this handling on iOS 9
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
        // or, see also http://qiita.com/niwatako/items/9ae602cb173625b4530a#%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB%E3%82%B3%E3%83%BC%E3%83%89
    }
    else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

Cookie sharing between multiple WKWebViews

Use a WKProcessPool to share cookies between web views.

Example:

self.processPool = [[WKProcessPool alloc] init];

WKWebViewConfiguration *configuration1 = [[WKWebViewConfiguration alloc] init];
configuration1.processPool = self.processPool;
WKWebView *webView1 = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration1];
...
WKWebViewConfiguration *configuration2 = [[WKWebViewConfiguration alloc] init];
configuration2.processPool = self.processPool;
WKWebView *webView2 = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration2];
...

See this Stack Overflow question.

Cannot work with NSURLProtocol, NSCachedURLResponse, NSURLProtocol

UIWebView can filter ad URLs and cache to read websites offline using NSURLProtocol, NSURLCache, and NSCachedURLResponse.

But WKWebView cannot work with those APIs.

Cookie, Cache, Credential, WebKit data cannot easily delete

iOS 8

After much trial and error, I've reached the following conclusion:

  1. Use NSURLCache and NSHTTPCookie to delete cookies and caches in the same way as you used to do on UIWebView.
  2. If you use WKProccessPool, re-initialize it.
  3. Delete Cookies, Caches, WebKit subdirectories in the Library directory.
  4. Delete all WKWebViews

iOS 9

//// Optional data
NSSet *websiteDataTypes
= [NSSet setWithArray:@[
                        WKWebsiteDataTypeDiskCache,
                        WKWebsiteDataTypeOfflineWebApplicationCache,
                        WKWebsiteDataTypeMemoryCache,
                        WKWebsiteDataTypeLocalStorage,
                        WKWebsiteDataTypeCookies,
                        WKWebsiteDataTypeSessionStorage,
                        WKWebsiteDataTypeIndexedDBDatabases,
                        WKWebsiteDataTypeWebSQLDatabases
                        ]];
//// All kinds of data
//NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
//// Date from
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
//// Execute
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
   // Done
}];

Stack Overflow How to remove cache in WKWebview?

Scroll rate bug on iOS 9

On iOS 8, the below code works fine, it can scroll with more inertia.

webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;

As for iOS 9, this code is meaningless, without setting the rate value within UIScrollView delegate scrollViewWillBeginDragging.

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
}

See Stack Overflow: Cannot change WKWebView's scroll rate on iOS 9

Cannot disable long press link menu

CSS: -webkit-touch-callout: none; and JavaScript: document.documentElement.style.webkitTouchCallout='none'; won't work.

Note: This bug was fixed in iOS 8.2.

Sometimes capturing WKWebView fails

Sometimes capturing a screenshot of WKWebView itself failed, try to capture WKWebView's scrollView property instead.

Otherwise, if you are not afraid of using private API, try lemonmojo/WKWebView-Screenshot.

Xcode 6.1 and above doesn't indicate precise memory usage for WKWebView

As of Xcode 6.1, it indicates lower memory usage than is actually used.

window.webkit.messageHandlers won't work on some websites

Some websites somehow override JavaScript's window.webkit. To prevent this issue, you should cache this to a variable before a website's content starts loading. WKUserScriptInjectionTimeAtDocumentStart can help you.

Cookie saving sometimes failed

Are cookies synced between NSHTTPCookie and WKWebView at some point?

Thanks to @winzig, he gives me information: "Cookie discussion / ajax #3"

See this Stack Overflow question: Can I set the cookies to be used by a WKWebView?

At WKWebView initialization time, it can set cookies to both cookie management areas without waiting for the areas to be synced.

WKWebView's backForwardList is readonly

I want WKWebView to restore its paging history.

Hard to coexist with UIWebView on iOS 7 and below

Before some person tried to submit thier app for both iOS 7 and iOS 8 using UIWebView and WKWebView, the submission was rejected right at the time.

See this issue Cannot coexist with UIWebView on iOS 7 and below

Links

Naituw/WBWebViewConsole "WBWebViewConsole is an In-App debug console for your UIWebView && WKWebView"

Conclusion

As you can see, WKWebView still looks hard to use and UIWebView looks easy.

However, Apple announced to developers:

Starting February 1, 2015, new iOS apps uploaded to the App Store must include 64-bit support and be built with the iOS 8 SDK, included in Xcode 6 or later.

It is possible Apple will make UIWebView deprecated. See 64-bit and iOS 8 Requirements for New Apps.

If you're curious how WKWebView works for web browser apps, try my Ohajiki Web Browser. http://en.ohajiki.ios-web.com

wkwebviewtips's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wkwebviewtips's Issues

Height

hi:

How to get the WKWebview's realHeight after finishLoad??
please help...

How to NOT reload page on back gesture?

I am sure this is simple, as it seems so straightforward, but I do not want the page my user will go back to to be refreshed each back stroke. It seems it is supposed to load from cache, but i am not seeing how to accomplish this. Thanks for anyone with a pointer!

WKWebView scrollView contentSize

Thanks for your tips!
I have a question that how to get a correct contentSize of WKWebView?
In my project, I use WKWebView to load some local html string.after loading,I wish the webView would fit the size automatic.But, sometimes I got a wrong size,the webView's contentSize height longer than the content real height.
Can you give me some suggestion to solve it?
Thanks!

Cannot coexist with UIWebView on iOS 7 and below

Hey,

I'm wondering what your experience with this was. Does this mean Apple will automatically reject an app if it uses both WKWebView and UIWebView? Wondering why you think Apple would take this position

Thanks!!

Edgar

UIWebView and WKWebView

Do you have any documentation as to why UIWebView and WKWebView can't co-exist? Any message from Apple or another source?

Question: Did you get the error: "Could not signal service com.apple.WebKit.WebContent"

Hi,
Sorry to bother you, in my app, I put my WKWebView in a UIView, in the view controller, I can slide the screen to change to next view and load a new web page. Sometimes I can get the print log in my console, did you meet this ?

2017-05-06 12:11:48.012962+0800 myAPP [14155:2172134] [] nw_socket_write_close shutdown(56, SHUT_WR): [57] Socket is not connected
2017-05-06 12:11:48.013116+0800 myAPP[14155:2172134] [] nw_endpoint_flow_service_writes [75.1 124.193.230.160:443 ready socket-flow (satisfied)] Write request has 0 frame count, 0 byte count
2017-05-06 12:11:48.026290+0800 myAPP[14155:2172692] [] tcp_connection_write_eof_block_invoke Write close callback received error: [89] Operation canceled
2017-05-06 12:11:48.416666+0800 myAPP[14155:2170078] Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service

WKWebView does not response correct MimeType in `decidePolicyForNavigationResponse`

I want to detect the response MimeType so that accordingly handle the type of file that's being downloaded. So, for example, if the file type is application/vnd.ms-excel then I want to take certain action but, with WKWebView it is always returning text/html in

-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler

I noticed that if I debug the WKWebView using Safari then the response MimeType is correctly displaying as application/vnd.ms-excel but, maybe because of QuickLook feature available in WkWebView the content is getting converted into HTML and responding text/html.

Is there any way to detect the mimeType apart from the above option that returns the actual file's mimeType?

https://stackoverflow.com/questions/62009832/wkwebview-does-not-response-correct-mimetype-in-decidepolicyfornavigationrespon

NSURLProtocol is not supported

This should be mentioned as it is a show stopper for some apps - mine included. And I did not notice until the switch to WKWebView was otherwise complete.

Taking screenshots of WKWebView on OS X

When trying to take a screenshot of a WKWebView on OS X using techniques that work with other Views and the old WebView class the resulting image is always just white.

This issue is well documented on the internet:
http://stackoverflow.com/questions/30149373/render-off-screen-wkwebview-into-nsimage/32146331#32146331
http://stackoverflow.com/questions/31969950/wkwebview-cachedisplayinrect-screenshot-in-os-x/32146270#32146270
http://stackoverflow.com/questions/24727499/wkwebview-screenshots/32146236#32146236

I've just worked around this by using private(!) APIs of WebKit and published the solution in the following repo: https://github.com/lemonmojo/WKWebView-Screenshot

Feel free to include it in your tips if you want to!

a new tip

WKWebView post will miss params so ajax request type must be get

WKWebview Content not fitting properly on device orientation

I have to load html content in wkwebview. I have added viewport and width=device-width,user-scalable=no. Initially the content loads properly in portrait mode, but when device is rotated to landscape and then back to portrait, the content overflows and does not fit to the device width. I dont need horizontal scrolling so I have disabled horizontal scroll of webview. Also I have reloaded web view on device orientation. Any help would be appreciated.

Video not playing

Hi

I have downloaded a video from api and added to tmp directory

on replacing src="http://.." with src="file:///..." Video view is loading but it is not playing.

Please suggest how can I proceed. I need to render media , in wkwebview in offline mode. once downloaded .

NsUrlCache

Since WkWebView does not respect NSUrlCache, it would be nice to see what your preferred caching solution is from a performance standpoint.

What is the current status of wkwebview

hi there, first of all thanks for these wonderful tips

my question is, how is the current status of wekwebview? should we use for apps ios8+ or does still using uiwebview is a good idea?

memory leak of WKWebView

Hello,

i am getting memory leak issue with WKWebView.

Can you please help me to resolve this issue?

Thanks in advance.

Correction about storyboard

The following item is not true after iOS 11.0:

You need to set WKWebView and any NSLayoutConstraints programmatically.

You need to bump deployment target to minimum 11.0 though.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.