Make writing a habit together! This is the second day of my participation in the “Gold Digging Day New Plan · April More text challenge”. Click here for more details.

WKWebView provides far more classes than UIWebView and can achieve richer functions. It has its own framework, WebKit, which contains all related classes. This article will explain all the classes according to the Apple documentation.

New understanding will continue to be added in the subsequent practical use

  1. WebKit structure knowledge
  2. Web View Awareness
  3. Web view configuration
  4. Data management
  5. Navigation related
  6. download
  7. Handling of web content
  8. Web search
  9. Context menu
  10. A snapshot of the configuration

1. Understanding of WebKit structure

Use the WebKit framework to integrate stylized Web content into the native content of your application. WebKit provides a complete browsing experience for the Web interface.

There are a number of things you can do with the WebKit framework:

  1. Display rich Web content using HTML, CSS, and JavaScript;
  2. Handle more loading of page content;
  3. Display multiple MIME types and composite frame elements;
  4. Navigate between content pages;
  5. Manage a before and after list of recently visited pages.

That is, we render a WKWebView object in the custom view hierarchy and load the web page content. Use the corresponding objects to manage cookies, execute scripts, control navigation, generate snapshots, and perform text-based searches.

2. Web view understanding

The WKWebView class is used to display web view content, and the WKUIDelegate protocol is used to display local user interface elements on web pages

2.1 WKWebView

2.1.1 Simple Usage process

Create a Web view programmatically using the WKWebViewConfiguration object. Load the content from the Web server using the URLRequest structure or load the content directly from a local file or HTML string before your Web view appears on the screen. 3, in line with the WKNavigationDelegate protocol can achieve programming navigation

2.1.2 Creating a Web View

API:

// create a view using configuration - (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration NS_DESIGNATED_INITIALIZER; // create a view using a coder object - (nullable instancetype)initWithCoder:(NSCoder *)coder NS_DESIGNATED_INITIALIZER; @property (nonatomic, readOnly, copy) WKWebViewConfiguration * Configuration;Copy the code

2.1.3 Can links be loaded

API:

+ (BOOL)handlesURLScheme:(NSString *)urlScheme;
Copy the code

Description:

  • Returns a Boolean that checks whether WKWebViews handles the given URL scheme by default.

2.1.4 Displaying the Local USER Interface

API:

@property (nullable, nonatomic, weak) id <WKUIDelegate> UIDelegate;
Copy the code

Description:

  • Web View UI proxy, an object used to integrate custom UI elements, such as menus or panels, into web view interaction.

2.1.5 Managing Web navigation

API:

@property (nullable, nonatomic, weak) id <WKNavigationDelegate> navigationDelegate;
Copy the code

Description:

  • An object that manages the navigation behavior of a Web view.
  • Methods for accepting or rejecting navigation changes, and methods for tracking the progress of navigation requests.

2.1.6 Loading web Pages

API:

// Loads the Web content referenced by the specified URL request object and navigates to that content. - (nullable WKNavigation *)loadRequest:(NSURLRequest *)request; // Loads the contents of the specified data object and navigates to it. - (nullable WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL // loads the content of the specified HTML string and navigates to it. - (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL; // Load the Web content from the file specified by the URL request object and navigate to it. - (WKNavigation *)loadFileRequest:(NSURLRequest *)request allowingReadAccessToURL:(NSURL *)readAccessURL // Load web content from the specified file and navigate to it. - (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL Just as data is a response to a request. - (WKNavigation *)loadSimulatedRequest:(NSURLRequest *)request response:(NSURLResponse *)response responseData:(NSData *)data // Load Web content from the HTML you provide as if the HTML were a response to a request. - (WKNavigation *)loadSimulatedRequest:(NSURLRequest *)request responseHTMLString:(NSString *)string Indicates whether the view is currently loading content. @property (nonatomic, readonly, getter=isLoading) BOOL loading; // Estimate how many parts of the current navigation have been loaded. @property (nonatomic, readonly) double estimatedProgress;Copy the code

2.1.7 Managing the Loading Process

API:

// Reload the current page - (nullable WKNavigation *)reload; // @param sender The object that sent this message. - (IBAction)reload (nullable id)sender; // Reload the current web page and, if possible, re-validate the content end-to-end using cache validation criteria. // @result A new navigation representing the reload. - (nullable WKNavigation *)reloadFromOrigin; // Reload the current web page and, if possible, re-validate the content end-to-end using cache validation criteria. - (IBAction)reloadFromOrigin:(nullable id)sender; // Stop loading all resources on the current page. - (void)stopLoading; // Stop loading all resources on the current page. - (IBAction)stopLoading:(nullable id)sender;Copy the code

2.1.8 Managing the download of web pages

API:

// Start downloading the resource at the requested URL. - (void)startDownloadUsingRequest:(NSURLRequest *)request completionHandler:(void(^)(WKDownload *))completionHandler // Restore failed or cancelled downloads. - (void)resumeDownloadFromResumeData:(NSData *)resumeData completionHandler:(void(^)(WKDownload *))completionHandlerCopy the code

2.1.9 Viewing View Information

API:

A scroll view associated with a Web view. @property (nonatomic, readonly, strong) UIScrollView *scrollView; // @Discuss@link wkwebview@ /link is keyvalue observing (KVO) compliant for this propert.@property (nullable, nonatomic, readonly, copy) NSString *title; //URL @property (nullable, nonatomic, readonly, copy) NSURL *URL; //The media type for the contents of the web view. @property (nonatomic, nullable, Copy) NSString *mediaType // User-defined user agent string. @Property (Nullable, nonAtomic, Copy) NSString *customUserAgent // A trust management object used to evaluate the trust level of the current web page. @Property (nonatomic, ReadOnly, Nullable) SecTrustRef serverTrust // A Boolean value indicating whether the Web view loads all resources on the page over a securely encrypted connection. @property (nonatomic, readonly) BOOL hasOnlySecureContent; // The theme color the system gets from the first valid meta tag in the web page. @property (nonatomic, ReadOnly, Nullable) UIColor *themeColor // The color displayed in the Web view behind the active page that is visible when the user scrolls beyond the page boundary. @property (nonatomic, null_resettable, copy) UIColor *underPageBackgroundColorCopy the code

2.1.10 Scaling Content

API:

// Scale factor, the Web view scales the content according to its boundaries. @property (nonatomic) CGFloat pageZoom // A Boolean value indicating whether the zooming gesture changes the zooming of the web page view. @property (nonatomic) BOOL allowsMagnification; // The factor by which the page content is currently scaled. @property (nonatomic) CGFloat magnification; // Scale the page content and center the result at the specified point. - (void)setMagnification:(CGFloat)magnification centeredAtPoint:(CGPoint)point;Copy the code

2.1.11 Interaction between web pages and media

API:

// Pause all media playback in the Web view. - (void) pauseAllMediaPlaybackWithCompletionHandler (void (^ _Nullable) (void)) completionHandler / / gaining media play in web view state. - (void)requestMediaPlaybackStateWithCompletionHandler:(void (^)(WKMediaPlaybackState))completionHandler // Change whether the page pauses all media in the page. - (void)setAllMediaPlaybackSuspended:(BOOL)suspended completionHandler:(void (^_Nullable)(void))completionHandler // Close all media displayed in the Web view, including in-picture video and full-screen video. - (void)closeAllMediaPresentationsWithCompletionHandler:(void (^_Nullable)(void))completionHandlerCopy the code

2.1.12 Managing Microphones and Cameras

API:

// Enumerate properties indicating whether a web page is using a camera to capture an image or video. @property (nonatomic, readonly) WKMediaCaptureState cameraCaptureState // Enumeration of properties indicating whether a web page uses a microphone to capture audio. @property (nonatomic, readonly) WKMediaCaptureState microphoneCaptureState // Sets whether a web page uses a camera to capture images or videos. - (void)setCameraCaptureState:(WKMediaCaptureState)state completionHandler:(void (^_Nullable)(void))completionHandler // Set whether a web page uses a microphone to capture audio. - (void)setMicrophoneCaptureState:(WKMediaCaptureState)state completionHandler:(void (^_Nullable)(void))completionHandler // An enumeration that describes whether a media device (such as a camera or microphone) is currently capturing audio or video. typedef NS_ENUM(NSInteger, WKMediaCaptureState) { WKMediaCaptureStateNone, WKMediaCaptureStateActive, WKMediaCaptureStateMuted, }Copy the code

2.1.13 Searching the Contents of the Current Page

API:

// Searches the contents of the Web view for the specified string. - (void)findString:(NSString *)string withConfiguration:(nullable WKFindConfiguration *)configuration completionHandler:(void (^)(WKFindResult *result))completionHandlerCopy the code

Description:

  • WKFindConfiguration is the configuration parameter to use when searching web view content.
  • WKFindResult Object that contains the results of a search for web view content.

2.1.14 Navigation between Web pages

API:

// A Boolean value indicating whether the horizontal swipe gesture triggers front and back page navigation. / / the default value is NO @ property (nonatomic) BOOL allowsBackForwardNavigationGestures; // An object that manages a list of previously loaded pages and is used by the Web view to navigate forward and backward. @property (nonatomic, readonly, strong) WKBackForwardList *backForwardList; // @new navigation to the requested item, or nil if there is no back item in the back-forward list. - (nullable WKNavigation *)goBack; - (IBAction)goBack:(nullable id)sender; - (nullable WKNavigation *)goForward; - (IBAction)goForward:(nullable id)sender; - (nullable WKNavigation *)goToBackForwardListItem:(WKBackForwardListItem *)item; // A Boolean value indicating whether there is a valid backward item in the forward list. @property (nonatomic, readonly) BOOL canGoBack; // A Boolean value indicating whether a valid forward item exists in the forward list. @property (nonatomic, readonly) BOOL canGoForward; // A Boolean value that determines whether a link is pressed to display a preview of the link destination. AllowsLinkPreview @Property (nonatomic) BOOL allowsLinkPreview // An object that captures the current interaction state in a Web view so that it can be restored to another Web view later. //WKWebView interactive state (forward list, currently loaded page, scroll position, form data... // The recovery state can be retrieved and set in another WKWebView. @property (nonatomic, nullable, copy) id interactionStateCopy the code

2.1.15 execute JavaScript

API:

EvaluateJavaScript (NSString *)javaScriptString completionHandler (void (^ _Nullable)(_Nullable)  id, NSError * _Nullable error))completionHandler; // Evaluates the specified JavaScript script in the specified frame and content world. - (void)evaluateJavaScript:(NSString *)javaScriptString inFrame:(nullable WKFrameInfo *)frame inContentWorld:(WKContentWorld *)contentWorld completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler // Executes the specified string as an asynchronous JavaScript function. - (void)callAsyncJavaScript:(NSString *)functionBody arguments:(nullable NSDictionary<NSString *, id> *)arguments inFrame:(nullable WKFrameInfo *)frame inContentWorld:(WKContentWorld *)contentWorld completionHandler:(void (^ _Nullable)(_Nullable_result id, NSError * _Nullable error))completionHandlerCopy the code

2.1.16 Obtaining Web View Content

API:

Asynchronously generate a platform-native image from the contents of the Web view. - (void)takeSnapshotWithConfiguration:(nullable WKSnapshotConfiguration *)snapshotConfiguration completionHandler:(void (^)(UIImage * _Nullable snapshotImage, NSError * _Nullable error))completionHandler // Asynchronously generates PDF data from the content of the Web view. - (void)createPDFWithConfiguration:(nullable WKPDFConfiguration *)pdfConfiguration completionHandler:(void (^)(NSData * _Nullable pdfDocumentData, NSError * _Nullable error))completionHandler // Asynchronously creates a Web archive of web view content. - (void)createWebArchiveDataWithCompletionHandler:(void (^)(NSData *, NSError *))completionHandler // Returns the print action object to use when printing web view content. - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfoCopy the code

Description:

  • WKSnapshotConfiguration is the configuration data used when generating images from the contents of the Web view.
  • WKPDFConfiguration is the configuration data to use when generating a PDF representation of web view content.

2.2 WKUIDelegate

WKUIDelegate provides a way for Web pages to render local user interface elements, and the Web View user interface delegate implements this protocol to control the opening of new Windows, increase the behavior of default menu items that appear when a user clicks on an element, and perform other user interface related tasks. The default Web view implementation assumes one window per Web view, so an unconventional user interface might implement a user interface delegate. Common is to do a pop-up or open a new WKWebView.

2.2.1 Creating and Closing a Web View

//Creates a new web view. - (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures; // Notify your application that the DOM window has closed successfully. - (void)webViewDidClose:(WKWebView *)webViewCopy the code

2.2.2 Displaying the UI Panel

// Displays the JavaScript popbox panel. - the webView: runJavaScriptAlertPanelWithMessage: initiatedByFrame: completionHandler: / / display JavaScript confirm box panel. - the webView: runJavaScriptConfirmPanelWithMessage: initiatedByFrame: completionHandler: / / display JavaScript input box panel. webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:Copy the code

2.2.3 Displaying the Upload panel

// Display the file upload panel. - the webView: runOpenPanelWithParameters: initiatedByFrame: completionHandler: / / file upload control configuration details of the web content. WKOpenPanelParametersCopy the code

2.2.4 Displaying the Context menu

// Tell the delegate that the context menu interaction has started. - the webView: contextMenuConfigurationForElement: completionHandler: / / provide animation object to entrust, web view to display the context menu that USES it. - the webView: contextMenuForElement: willCommitWithAnimator: / / tell the entrusted web view will display the specified element's context menu. - the webView: contextMenuWillPresentForElement: / / tell entrust web view cancelled the specified element's context menu. - webView:contextMenuDidEndForElement:Copy the code

Description:

  • UIContextMenuConfiguration contain the context menu configuration details of the object.

2.2.5 Requested Permissions

// Determines whether the web resources described by the security source object can access the direction and movement of the device. - webView:requestDeviceOrientationAndMotionPermissionForOrigin:initiatedByFrame:decisionHandler: Determines whether the Web resources described by the security source object can access the microphone audio and camera video of the device. - the webView: requestMediaCapturePermissionForOrigin: initiatedByFrame: type: decisionHandler: / / equipment resource access may decide on the enumeration of rights. typedef NS_ENUM(NSInteger, WKPermissionDecision) { WKPermissionDecisionPrompt, WKPermissionDecisionGrant, WKPermissionDecisionDeny,} / / list to capture audio, video, or the media device type of enumeration. typedef NS_ENUM(NSInteger, WKMediaCaptureType) { WKMediaCaptureTypeCamera, WKMediaCaptureTypeMicrophone, WKMediaCaptureTypeCameraAndMicrophone, }Copy the code

3. Web view configuration

3.1 WKWebViewConfiguration

WKWebViewConfiguration is a collection of properties used to initialize the Web view. Provides information on how to configure a WKWebView object. You create a WKWebViewConfiguration object in your code, configure its properties, and pass it to your WKWebView object’s initializer. Web views include your configuration Settings only when they are created; You cannot change these Settings dynamically later

Function:

  • The initial cookie for your Web content
  • Handlers for any custom URL scheme your Web content uses
  • How do I handle media content
  • Information about how to manage selections in a Web view
  • Custom script injection into web pages
  • Custom rules for determining how content is rendered

3.1.1 Configuring Web View Behavior

API:

@property (nonatomic, strong) WKWebsiteDataStore *websiteDataStore
Copy the code

Description:

  • Object used to get and set site cookies and track cached data objects.
  • Used as a Cookie setting

API:

@property (nonatomic, strong) WKUserContentController *userContentController;
Copy the code

Description:

  • This object coordinates the interaction between the native code of the application and the scripts and other content of the web page.
  • Used for Web interaction with Native

API:

@property (nonatomic, strong) WKProcessPool *processPool;
Copy the code

Description:

  • Process pools for Web content
  • When a Web view is initialized, a new Web content process is created from the specified pool or an existing process
  • This object coordinates the process that the Web view uses to render its Web content and execute the script.

API:

@property (nullable, nonatomic, copy) NSString *applicationNameForUserAgent
Copy the code

Description:

  • The name of the application that appears in the user agent string.

API:

@property (nonatomic) BOOL limitsNavigationsToAppBoundDomains
Copy the code

Description:

  • A Boolean value indicating whether the Web view restricts navigation to pages within the application domain.

3.1.2 Configuring Web View Preferences

API:

@property (nonatomic, strong) WKPreferences *preferences;
Copy the code

Description:

  • Objects that manage preferences related Settings for web views.

API:

@property (null_resettable, nonatomic, copy) WKWebpagePreferences *defaultWebpagePreferences
Copy the code

Description:

  • Default preferences to use when loading and rendering content.

3.1.3 Adding handlers for custom URL schemes

API:

- (void)setURLSchemeHandler:(nullable id <WKURLSchemeHandler>)urlSchemeHandler forURLScheme:(NSString *)urlScheme
Copy the code

Description:

  • Registers an object to load resources associated with the specified URL scheme.
  • Sets the processing object for the URL pattern

API:

- (nullable id <WKURLSchemeHandler>)urlSchemeHandlerForURLScheme:(NSString *)urlScheme
Copy the code

Description:

  • Returns the handler object currently registered for the specified URL schema.

3.1.4 Configuring the presentation behavior

API:

@property (nonatomic) BOOL ignoresViewportScaleLimits
Copy the code

Description:

  • A Boolean that determines whether the web view allows zooming.
  • The default value is NO

API:

@property (nonatomic) BOOL suppressesIncrementalRendering;
Copy the code

Description:

  • A Boolean value indicating whether the Web view suppresses content rendering until the content is fully loaded into memory.
  • The default value is NO

3.1.5 Setting Media Playback Preferences

API:

@property (nonatomic) BOOL allowsInlineMediaPlayback;
Copy the code

Description:

  • A Boolean value indicating whether the HTML5 video is played inline or using the native full-screen controller.

API:

@property (nonatomic) BOOL allowsAirPlayForMediaPlayback
Copy the code

Description:

  • A Boolean value indicating whether the Web view allows media to be played through AirPlay.

API:

@property (nonatomic) BOOL allowsPictureInPictureMediaPlayback
Copy the code

Description:

  • Indicates whether HTML5 video can be played
  • The default is YES

API:

@property (nonatomic) WKAudiovisualMediaTypes mediaTypesRequiringUserActionForPlayback
Copy the code

Description:

  • The type of media that requires user gestures to start playing.

API:

typedef NS_OPTIONS(NSUInteger, WKAudiovisualMediaTypes) {
    WKAudiovisualMediaTypeNone = 0,
    WKAudiovisualMediaTypeAudio = 1 << 0,
    WKAudiovisualMediaTypeVideo = 1 << 1,
    WKAudiovisualMediaTypeAll = NSUIntegerMax
}
Copy the code

Description:

  • The type of media that requires user gestures to start playing.

3.1.6 Determining the data type

API:

@property (nonatomic) WKDataDetectorTypes dataDetectorTypes 
Copy the code

Description:

  • The type of data detector applied to web view content.
  • WKDataDetectorTypes is a data detector type class

3.1.7 Setting the Selection granularity

API:

@property (nonatomic) WKSelectionGranularity selectionGranularity;

typedef NS_ENUM(NSInteger, WKSelectionGranularity) {
    WKSelectionGranularityDynamic,
    WKSelectionGranularityCharacter,
}
Copy the code

Description:

  • Users can interactively choose the level of granularity of web view content.
  • The default value is WKSelectionGranularityDynamic.
  • WKSelectionGranularity Enumeration Allows users to select and modify the granularity of web view content.

3.1.8 Selecting the direction of the USER interface

API:

@property (nonatomic) WKUserInterfaceDirectionPolicy userInterfaceDirectionPolicy

typedef NS_ENUM(NSInteger, WKUserInterfaceDirectionPolicy) {
    WKUserInterfaceDirectionPolicyContent,
    WKUserInterfaceDirectionPolicySystem,
}
Copy the code

Description:

  • Orientation of user interface elements.
  • WKUserInterfaceDirectionPolicy enumeration decide the direction of the user interface elements in web view of strategy

3.2 WKWindowFeatures

A WKWindowFeatures object contains properties requested by a web page from its contained Web view. Is used to display the properties of the page requesting its window. Wkwindows Features objects cannot be created directly. When a navigation operation results in the display of a new Web view, WKWebView creates this object, And pass it to its UI delegate object webView: createWebViewWithConfiguration: forNavigationAction: windowFeatures: method. The delegate uses the information in this object to configure and return a new Web view.

Check the position and size of the window:

A Boolean value indicating whether to make the contained window resizable. @property (nullable, nonatomic, readonly) NSNumber *allowsResizing;Copy the code

Check the visibility properties:

A Boolean value indicating whether a web page requests a visible menu bar. @property (nullable, nonatomic, readonly) NSNumber *menuBarVisibility; A Boolean value indicating whether a web page requests a visible status bar. @property (nullable, nonatomic, readonly) NSNumber *statusBarVisibility; A Boolean value indicating whether a web page requests a toolbar to be visible. @property (nullable, nonatomic, readonly) NSNumber *toolbarsVisibility;Copy the code

3.3 WKProcessPool

The WKProcessPool object represents a single process that WebKit uses to manage Web content. An opaque token used to run multiple Web views in a process.

To provide a more secure and stable experience, WebKit renders the content of a Web view in a separate process, rather than in your application’s process space.

By default, WebKit gives each Web view its own process space until it reaches implementation-defined process limits. After that, Web views with the same WKProcessPool object share the same Web content process.

If your application creates multiple Web views, assign the same WKProcessPool object to web views that may safely share a process space. Instantiate an instance of this class and assign it to the processPool property of the WKWebViewConfiguration object for each Web view.

No properties or methods are provided

3.4 WKPreferences

Use the WKPreferences object to specify your web site’s preferences, including minimum font size, JavaScript behavior, and behavior for handling fraudulent web sites. It encapsulates the standard behavior applied to web sites.

Create this object and assign it to the Preferences property of the WKWebViewConfiguration object that you use to create the Web view.

3.4.1 Setting render preferences

API:

@property (nonatomic) CGFloat minimumFontSize;
Copy the code

Description:

  • Minimum font size, in points.

API:

@property (nonatomic) BOOL tabFocusesLinks
Copy the code

Description:

  • A Boolean value indicating whether pressing the TAB key changes the focus to links and form controls.

3.4.2 Setting Java and JavaScript Preferences

API:

javaScriptCanOpenWindowsAutomatically
Copy the code

Description:

  • A Boolean value indicating whether JavaScript can open a window without user interaction.

3.4.3 Set fraud warning preference

API:

@property (nonatomic, getter=isFraudulentWebsiteWarningEnabled) BOOL fraudulentWebsiteWarningEnabled
Copy the code

Description:

  • A Boolean value indicating whether the Web view displays a warning for suspected fraudulent content, such as malware or phishing.

3.5 WKWebpagePreferences

An object that specifies the behavior to use when loading and rendering page content. Create a WKWebpagePreferences object when you want to change the default rendering behavior of your Web view. Typically, iOS devices render Web content for a mobile experience, while Mac devices render content for a desktop experience.

3.5.1 Setting JavaScript Preferences

API:

@property (nonatomic) BOOL allowsContentJavaScript
Copy the code

Description:

  • A Boolean value indicating whether JavaScript from Web content is allowed to run.

3.5.2 Setting the Preferred Content Mode

API:

@property (nonatomic) WKContentMode preferredContentMode

typedef NS_ENUM(NSInteger, WKContentMode) {
    WKContentModeRecommended,
    WKContentModeMobile,
    WKContentModeDesktop
}
Copy the code

Description:

  • The content mode that web views use when loading and rendering web pages.
  • WKContentMode indicates how to render web view content constants

4. Data management

4.1 WKWebsiteDataStore

Use WKWebsiteDataStore objects to configure and manage web site data. For managing cookies, disk and memory caches, and other types of data for Web views.

Function:

  • Manage cookies used by websites
  • Understand the types of data your site stores
  • Delete unwanted website data

4.1.1 Creating a Data Store Object

API:

+ (WKWebsiteDataStore *)defaultDataStore;
Copy the code

Description:

  • Returns the default data store
  • This storage persistently stores data to disk

API:

+ (WKWebsiteDataStore *)nonPersistentDataStore;
Copy the code

Description:

  • Create a new non-persistent datastore object that stores web site data in memory rather than writing it to disk.
  • Implementing “private browsing” is useful

4.1.2 Checking Data Store Properties

API:

@property (nonatomic, readonly, getter=isPersistent) BOOL persistent;
Copy the code

Description:

  • A Boolean value indicating whether the object stores data to disk.

4.1.3 Retrieving the Cookie Store

API:

@property (nonatomic, readonly) WKHTTPCookieStore *httpCookieStore
Copy the code

Description:

  • An object that manages HTTP cookies for web sites.

4.1.4 Retrieving specific types of data

API:

- (void)fetchDataRecordsOfTypes:(NSSet<NSString *> *)dataTypes completionHandler:(void (^)(NSArray<WKWebsiteDataRecord *> *))completionHandler
Copy the code

Description:

  • Gets the specified record type from the data store.

API:

+ (NSSet<NSString *> *)allWebsiteDataTypes;
Copy the code

Description:

  • Returns a collection of all available data types.

4.1.5 Deleting Data of a Specific Type

API:

- (void)removeDataOfTypes:(NSSet<NSString *> *)dataTypes forDataRecords:(NSArray<WKWebsiteDataRecord *> *)dataRecords completionHandler:(void (^)(void))completionHandler;
Copy the code

Description:

  • Removes the specified web site data type from one or more data records.

API:

- (void)removeDataOfTypes:(NSSet<NSString *> *)dataTypes modifiedSince:(NSDate *)date completionHandler:(void (^)(void))completionHandler;
Copy the code

Description:

  • Deletes site data that has changed after a specified date.

4.2 WKWebsiteDataRecord

Use the WKWebsiteDataRecord object to discover the type of information the site stores. A persistent record of data stored on a particular web site.

Records identify the type of data stored on the site, but not the actual data. You can use this information to help users manage site data. Safari, for example, gives users a way to view and delete web site data. Each recorded domain name contains the domain name and suffix of the website.

We cannot create a WKWebsiteDataRecord object directly. WebKit creates these records and stores them in the Data store of the Web view.

The use of the data storage fetchDataRecordsOfTypes: completionHandler: object to retrieve the current record. You can also use this object to delete unwanted records.

4.2.1 Obtaining Record Information

API:

@property (nonatomic, readonly, copy) NSString *displayName;
Copy the code

Description:

  • The display name of the data record.

4.2.2 Obtaining the Data type

API:

@property (nonatomic, readonly, copy) NSSet<NSString *> *dataTypes;
Copy the code

Description:

  • The data type associated with the record.

4.3 WKHTTPCookieStore

Objects that manage HTTP cookies associated with a particular Web view. Use WKHTTPCookieStore to specify initial cookies for your web page and manage cookies for web page content. For example, you can use this object to delete cookies for the current session when the user exits. To detect when a web page changes cookies, install a cookie watcher using the addObserver: method.

You don’t need to create the WKHttpCookeStore object directly. Instead, retrieve the object from the WKWebsiteDataStore object of the configuration object in the Web view.

4.3.1 management cookies

API:

- (void)getAllCookies:(void (^)(NSArray<NSHTTPCookie *> *))completionHandler;
Copy the code

Description:

  • Asynchronously retrieves all stored cookies and delivers them to the specified completion handler.

API:

- (void)setCookie:(NSHTTPCookie *)cookie completionHandler:(nullable void (^)(void))completionHandler;
Copy the code

Description:

  • Add a cookie to cookieStore.

API:

- (void)deleteCookie:(NSHTTPCookie *)cookie completionHandler:(nullable void (^)(void))completionHandler
Copy the code

Description:

  • Deletes the specified cookie.

4.3.2 Observing Cookie Store changes

API:

- (void)addObserver:(id<WKHTTPCookieStoreObserver>)observer;
Copy the code

Description:

  • Add an observer to the cookie store

API:

- (void)removeObserver:(id<WKHTTPCookieStoreObserver>)observer;
Copy the code

Description:

  • Removes an observer from the cookie store.
  • WKHTTPCookieStoreObserver monitoring web cookies in the change of the object

4.4 WKURLSchemeHandler

A protocol for loading resources, loading URL patterns that are not handled by WebKit, i.e. loading custom resources. Use the WKURLSchemeHandler protocol in objects to handle custom URL schemes for your Web content.

Custom schemas allow you to integrate custom resource types into your Web content, and you can also define custom schemas for the resources required by your application.

In your application object using this protocol, and USES WKWebViewConfiguration setURLSchemeHandler: forURLScheme: method to register it.

When a Web view encounters a resource that uses a custom schema, it creates a WKURLSchemeTask object and passes it to the methods of your schema handler object.

The webView: startURLSchemeTask: way to start loading resources.

When your processor load this object, web view might call you processor webView: stopURLSchemeTask: way to inform you of this resource is no longer needed.

Loading a custom resource:

// The request handler starts loading data for the specified resource. - webView:startURLSchemeTask:Copy the code

Responding to a canceled resource request:

// The request handler stops loading data for the specified resource. - webView:stopURLSchemeTask:Copy the code

4.5 WKURLSchemeTask

The WKURLSchemeTask protocol defines the interface that WebKit uses to request custom resources. Do not use this interface in your own objects. Instead, WebKit creates objects that use this interface and delivers them to the custom schema handler (objects that use the WKURLSchemeHandler protocol). You can use the objects provided by WebKit to get information about the requested resources and load them. You can also use these objects to report your progress to WebKit.

Description:

  • When WebKit needs a custom schema, it places an appropriate URL request in the request attribute of the task.
  • Upon receiving the request, determine the size of the resource and invoke the didReceiveResponse: method with the appropriate URL response object.
  • Providing the response reflects the behavior of the Web server when it receives the request.
  • After loading a portion of the resource data, call the didReceiveData: method to send it to WebKit.
  • You can call this method multiple times to deliver the data incrementally, or you can call it once with all the data.
  • After you have delivered all the data, call the didFinish method. If an error occurs during loading, call didFailWithError: to report it.

5. Navigation

5.1 WKNavigationDelegate

The WKNavigationDelegate provides methods for accepting or rejecting navigation changes, as well as methods for tracking the progress of navigation requests. A method that implements the WKNavigationDelegate protocol in an object used to coordinate changes in the main frame of a Web view. When a user tries to navigate web content, the Web view coordinates with its navigation delegate to manage any transformations.

Function:

  • Restrict navigation of specific links in content
  • Track the progress of requests and respond to errors and authentication challenges

5.1.1 Allow or deny navigation requests

API:

- webView:decidePolicyForNavigationAction:preferences:decisionHandler:
Copy the code

Description:

  • The request delegate gets permission to navigate to new content based on specified preferences and action information.

API:

- webView:decidePolicyForNavigationAction:decisionHandler:
Copy the code

Description:

  • The request delegate grants permission to navigate to new content based on the specified action information.
  • WKNavigationActionPolicy indicates whether constant navigation from action to web page is allowed or unenabled

API:

- webView:decidePolicyForNavigationResponse:decisionHandler:
Copy the code

Description:

  • The permission of the request delegate to navigate to the new content after knowing the response to the navigation request.
  • WKNavigationResponsePolicy indicating whether to allow or remove from the constant response to navigate to the web page

5.1.2 Tracing the request loading progress

API:

- webView:didStartProvisionalNavigation:
Copy the code

Description:

  • Tells the delegate principal that the navigation of the framework is started.

API:

- webView:didReceiveServerRedirectForProvisionalNavigation:
Copy the code

Description:

  • A server redirect that tells the delegate Web view that it received a request.

API:

- webView:didCommitNavigation:
Copy the code

Description:

  • Tell the delegate that the Web view has started receiving the content of the body frame.

API:

- webView:didFinishNavigation:
Copy the code

Description:

  • Tell the delegate navigation is complete.

5.1.3 Responding to authentication Challenges

API:

- webView:didReceiveAuthenticationChallenge:completionHandler:
Copy the code

Description:

  • Request the delegate to respond to the authentication challenge.

API:

- webView:authenticationChallenge:shouldAllowDeprecatedTLS:
Copy the code

Description:

  • Ask the delegate whether to continue using the connection with the deprecated VERSION of TLS.

5.1.4 Response navigation Error

API:

- webView:didFailNavigation:withError:
Copy the code

Description:

  • Tell the delegate that an error occurred during navigation.

API:

- webView:didFailProvisionalNavigation:withError:
Copy the code

Description:

  • Tell the delegate that an error occurred during early navigation.

API:

- webViewWebContentProcessDidTerminate:
Copy the code

Description:

  • The content procedure that tells the delegate web view is terminated.

5.1.5 Handling the Download Progress

API:

webView:navigationResponse:didBecomeDownload:
Copy the code

Description:

  • Tell the delegate navigation that the response has become a download.

API:

- webView:navigationAction:didBecomeDownload:
Copy the code

Description:

  • Tell the delegate that the navigation operation becomes a download.

5.2 WKBackForwardList

Use the WKBackForwardList object to retrieve the page loaded before the Web view. Used to manage a list of previously loaded pages that the Web view uses to navigate forward and backward.

Typically, the WKBackForwardList object is not created directly. Each Web view automatically creates one and uses it to store a history of all loaded pages. Get this object from the backForwardList property of the Web view and use its contents to facilitate programmatic navigation.

5.2.1 Obtaining the latest Item

@property (Nullable, nonatomic, ReadOnly, strong) WKBackForwardListItem *backItem; @property (Nullable, nonatomic, readOnly, strong) WKBackForwardListItem *currentItem; @property (Nullable, Nonatomic, ReadOnly, strong) WKBackForwardListItem *forwardItem;Copy the code

5.2.2 Getting specific items in the list

- (nullable WKBackForwardListItem *)itemAtIndex:(NSInteger)index;
Copy the code

Description:

  • Returns the item at the offset relative to the current item.

5.2.3 Obtaining sublists

// An array of items before the current item. @property (nonatomic, readonly, copy) NSArray<WKBackForwardListItem *> *backList; // An array of items after the current item. @property (nonatomic, readonly, copy) NSArray<WKBackForwardListItem *> *forwardList;Copy the code

5.3 WKBackForwardListItem

Use the wkBackForwardListtitem object to get information about previously visited web pages. Web page view A previously accessed web page item. This object identifies the title and URL of the page. It also identifies the URL from which the page was requested. You do not need to create the wkBackForwardListtitem object directly. Instead, when the Web view loads new pages, the WKBackForwardList object creates them with its associated Web view.

Get page-specific information:

- (instancetype)init NS_UNAVAILABLE; / *! @abstract The URL of the webpage represented by this item. */ @property (readonly, copy) NSURL *URL; / *! @abstract The title of the webpage represented by this item. */ @property (nullable, readonly, copy) NSString *title;Copy the code

Get the request page:

// The web view was originally requested to load the source URL for this page. @property (readonly, copy) NSURL *initialURL;Copy the code

5.4 WKNavigation

The WKNavigation object uniquely identifies a load request for a web page. An object that tracks the progress of web page loading. When you ask the Web view to load content or navigate to a page, the Web view returns a WKNavigation object to identify your request. As the load operation progresses, the Web view reports the progress of that operation to its navigation delegate’s various methods and passes them the matching WKNavigation object.

Get the content mode:

The content mode that WebKit uses to load web pages. @property (nonatomic, readonly) WKContentMode effectiveContentModeCopy the code

5.5 WKNavigationAction

Use a WKNavigationAction object to decide whether to allow navigation in your application’s Web view. Contains information about the actions that caused the navigation to occur. You cannot create a WKNavigationAction object directly. Instead, the Web view creates them and passes them to the appropriate delegate object. Delegate methods are used to analyze operations and determine whether navigation is allowed.

5.5.1 Obtaining the Navigation Type

API:

@property (nonatomic, readonly) WKNavigationType navigationType;
Copy the code

Description:

  • The type of action that triggers navigation.

API:

typedef NS_ENUM(NSInteger, WKNavigationType) {
    WKNavigationTypeLinkActivated,
    WKNavigationTypeFormSubmitted,
    WKNavigationTypeBackForward,
    WKNavigationTypeReload,
    WKNavigationTypeFormResubmitted,
    WKNavigationTypeOther = -1,
}
Copy the code

Description:

  • The type of action that triggers navigation.

5.5.2 Checking Navigation Information

API:

@property (nonatomic, readonly, copy) NSURLRequest *request;
Copy the code

Description:

  • The URL request object associated with the navigation operation.

API:

@property (nonatomic, readonly, copy) WKFrameInfo *sourceFrame;
Copy the code

Description:

  • A framework for requesting navigation.

API:

@property (nullable, nonatomic, readonly, copy) WKFrameInfo *targetFrame;
Copy the code

Description:

  • A framework in which to display new content.

5.5.3 Checking User operations

API:

@property (nonatomic, readonly) NSInteger buttonNumber;
Copy the code

Description:

  • The number of mouse buttons that cause navigation requests.

API:

@property (nonatomic, readonly) NSEventModifierFlags modifierFlags;
Copy the code

Description:

  • The modify key that is pressed on a navigation request.

5.6 WKNavigationResponse

Use the WKNavigationResponse object to decide whether to allow navigation in your application’s Web view. An object that contains responses to navigation requests for making navigation-related policy decisions. You can’t create a WKNavigationResponse object directly. Instead, the Web view creates them and passes them to the appropriate delegate object. Delegate methods are used to analyze the response and determine whether navigation is allowed.

5.6.1 Obtaining Response details

@property (nonatomic, readOnly, copy) NSURLResponse *response;Copy the code

5.6.2 Obtaining additional response information

//A Boolean value that indicates whether the response targets the Web view's main frame.@property (nonatomic, readonly) BOOL canShowMIMEType; // A Boolean value indicating whether the response is specific to the main frame of the Web view. @property (nonatomic, readonly, getter=isForMainFrame) BOOL forMainFrame;Copy the code

6, download

6.1 WKDownload

An object that represents a Web resource download.

6.2 WKDownloadDelegate

The protocols you implement to track download progress and handle redirects, authentication challenges, and failures.

6.2.1 Tracking the Download Progress

API:

- download:decideDestinationUsingResponse:suggestedFilename:completionHandler:
Copy the code

Description:

  • The request delegate provides a file destination where the system should write the download data.

API:

- downloadDidFinish:
Copy the code

Description:

  • Tell the delegate that the download is complete.

API:

- download:didFailWithError:resumeData:
Copy the code

Description:

  • Tell the delegate that the download failed and provide an error message and data that can be used to restart the download.

6.2.2 Responding to Authorization Challenges

API:

- download:didReceiveAuthenticationChallenge:completionHandler:
Copy the code

Description:

  • Request the delegate to respond to the authentication challenge.

API:

WKDownloadRedirectPolicy
Copy the code

Description:

  • Enumeration with use cases indicating whether redirection should continue.

6.2.3 Redirection

API:

- download:willPerformHTTPRedirection:newRequest:decisionHandler:
Copy the code

Description:

  • Request delegate response downloaded redirect response.

API:

WKDownloadRedirectPolicy
Copy the code

Description:

  • Enumeration with use cases indicating whether redirection should continue.

7, web content processing

7.1 WKUserContentController

The WKUserContentController object provides a bridge between your application and the JavaScript code running in the Web view. Used to manage interactions between JavaScript code and web views, and to filter content in web views.

Create and configure a WKUserContentController object as part of the entire Web view setup. Before creating the Web view, assign this object to the userContentController property of your WKWebViewConfiguration object

Process:

  1. Inject JavaScript code into a web page running in a Web view.
  2. Install custom JavaScript functions to call your application’s native code.
  3. Specifies custom filters to prevent web pages from loading restricted content.

7.1.1 Adding and Deleting user-defined Scripts

API:

- (void)addUserScript:(WKUserScript *)userScript;
Copy the code

Description:

  • Inject the specified script into the content of the web page.

API:

- (void)removeAllUserScripts;
Copy the code

Description:

  • Remove all user scripts from the Web view.

API:

@property (nonatomic, readonly, copy) NSArray<WKUserScript *> *userScripts;
Copy the code

Description:

  • The user script associated with the user content controller.

7.1.2 Adding and removing message handlers

API:

- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
Copy the code

Description:

  • Add a message callback handler that can be invoked from JavaScript code.

API:

- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler contentWorld:(WKContentWorld *)world name:(NSString *)name
Copy the code

Description:

  • Install a message handler that you can invoke from the content world specified in your JavaScript code.

API:

- (void)addScriptMessageHandlerWithReply:(id <WKScriptMessageHandlerWithReply>)scriptMessageHandlerWithReply contentWorld:(WKContentWorld *)contentWorld name:(NSString *)name
Copy the code

Description:

  • Install a message handler that returns a reply to the JavaScript code.

API:

- (void)removeScriptMessageHandlerForName:(NSString *)name;
Copy the code

Description:

  • Unmounts a custom message handler with the specified name from the JavaScript code.

API:

- (void)removeScriptMessageHandlerForName:(NSString *)name contentWorld:(WKContentWorld *)contentWorld
Copy the code

Description:

  • Unmounts the custom message handler from the content world specified in the JavaScript code.

API:

- (void)removeAllScriptMessageHandlersFromContentWorld:(WKContentWorld *)contentWorld
Copy the code

Description:

  • Unmounts all custom message handlers from the content world specified in the JavaScript code.

API:

- (void)removeAllScriptMessageHandlers
Copy the code

Description:

  • Unmounts all custom message handlers associated with the user content controller.

API:

WKScriptMessageHandler
Copy the code

Description:

  • An interface to receive messages from JavaScript code running on a web page.

API:

WKScriptMessageHandlerWithReply
Copy the code

Description:

  • Interface for messages that respond to JavaScript code running on a web page.

7.1.3 Adding and Deleting Content Rules

API:

- (void)addContentRuleList:(WKContentRuleList *)contentRuleList
Copy the code

Description:

  • Adds the specified list of content rules to the content controller object.

API:

- (void)removeContentRuleList:(WKContentRuleList *)contentRuleList
Copy the code

Description:

  • Removes the specified list of rules from the content controller object.

API:

- (void)removeAllContentRuleLists
Copy the code

Description:

  • Removes all rule lists from the content controller.

API:

WKContentRuleList
Copy the code

Description:

  • A list of rules for Web content.

7.2 WKContentRuleListStore

Use WKContentRuleListStore to compile and manage rules for filtering content in web views. Contains rules for how to load and filter content in web views. Rule lists act as content blockers in your application. You can use them to prevent web views from loading specific content, whether based on the original location of the content or some other criteria you specify.

Description:

  • Get the default WKContentRuleListStore object or create a custom Store object and use it to compile or access the available rules.
  • Each Store object persistently stores its existing rules in the file system and loads them at creation time.
  • A Store object does not automatically apply any of its rules to a particular Web view. To apply a rule to a Web view, you need to add it to the WKUserContentController object of the Web View configuration object.

7.2.1 Creating a Content Rule List Store

API:

+ defaultStore
Copy the code

Description:

  • Returns the default content rule list store.

API:

+ storeWithURL:
Copy the code

Description:

  • Creates a new content rule list store in the specified directory.

7.2.2 Creating and Deleting a Content Rule List

API:

compileContentRuleListForIdentifier:encodedContentRuleList:completionHandler:
Copy the code

Description:

  • Compile the specified JSON content into a new rule list and add it to the current data store.

API:

- removeContentRuleListForIdentifier:completionHandler:
Copy the code

Description:

  • Asynchronously removes the rule list from the current data store.

7.2.3 Accessing the Current Rule List

API:

- getAvailableContentRuleListIdentifiers:
Copy the code

Description:

  • Asynchronously gets the identifier for all rule lists in the store.

API:

- lookUpContentRuleListForIdentifier:completionHandler:
Copy the code

Description:

  • Asynchronously searches a list of specific rules in a data store.

7.3 WKContentWorld

Use the WKContentWorld object as a namespace to separate the web environment of your application from that of the individual web pages or scripts you execute. An object that defines the execution scope of JavaScript code to prevent conflicts between different scripts. Content worlds help prevent problems that occur when two scripts modify environment variables in conflicting ways. Executing the script in its own content world effectively provides it with a copy of a separate environment variable modification.

Description:

  • The WKContentWorld object is a namespace that does not persist data outside the current Web view or web page.
  • If you use the same content world in two WKWebView objects, variables in the content world of one Web view do not appear in the other Web view.
  • Similarly, when the user or your application navigates to a new web page, the variables from the previous page disappear, even though the two pages share the same content world.
  • Use the methods and properties of this class to retrieve the desired content world.
  • WKContentWorld provides a default content world for your application and a content world for the current web page. You can also create new content worlds. For example, you can create a custom content world for each JavaScript extension you manage. Specify content world objects when configuring or executing scripts associated with content.

Action Scene:

  1. You have complex script logic to connect your Web content to your application, but your Web content has its own complex script library. In this case, one content world is used for application-specific scripts and a separate content world is used for content-specific scripts.
  2. You have implemented a Web browser that supports JavaScript extensions. In this case, create a unique content world for each extension to prevent conflicts between extensions.

7.3.1 Getting the Default content world

The default world of the client. defaultClientWorldCopy the code

7.3.2 Getting the namespace of the current page

The content world of the current web page content. pageWorldCopy the code

7.3.3 Retrieving custom content worlds

Returns a custom content world with the specified name. + worldWithName: The name of the custom content world. nameCopy the code

7.4 WKFrameInfo

An object that contains information about a frame on a web page. An instance of this class is a temporary, data-only object. It cannot uniquely identify a framework across multiple delegate method calls.

Check the frame’s information:

A Boolean value indicating whether the frame is the main or subframe of the site. The current request for the mainFrame framework. The security source of the Request framework. securityOriginCopy the code

7.5 WKSecurityOrigin

The WKSecurityOrigin object is a temporary, data-only object that identifies the host name, protocol, and port number associated with a particular resource. You cannot create a WKSecurityOrigin object directly. Instead, WebKit creates them for the resources it loads. A first-party load is any load URL that has the same security source as the requesting site. First-party web pages can access each other’s resources, such as scripts and databases.

Because the WKSecurityOrigin object is transient, it cannot uniquely identify the security source across multiple delegate method calls.

Obtain host information:

host

port
Copy the code

Get host protocol:

protocol
Copy the code

7.6 WKUserScript

A webView injection script for a web page. Create a WKUserScript object when you want to inject custom script code into your Web view page. Use this object to specify the JavaScript code to inject, as well as parameters related to when and how it should be injected. Before you create your Web view, add this object to the WKUserContentController object associated with your Web view configuration.

7.6.1 Creating a User Script Object

API:

- (instancetype)initWithSource:(NSString *)source injectionTime:(WKUserScriptInjectionTime)injectionTime forMainFrameOnly:(BOOL)forMainFrameOnly;
Copy the code

Description:

  • Creates a user script object that contains the specified source code and properties.

API:

- (instancetype)initWithSource:(NSString *)source injectionTime:(WKUserScriptInjectionTime)injectionTime forMainFrameOnly:(BOOL)forMainFrameOnly inContentWorld:(WKContentWorld *)contentWorld
Copy the code

Description:

  • Create a user script object whose scope is a specific content world.

7.6.2 Checking Script Information

// The source code of the script. @property (nonatomic, readonly, copy) NSString *source; // The time to inject the script into the web page. @property (nonatomic, readonly) WKUserScriptInjectionTime injectionTime; // The time constant for injecting script content into the web page. typedef NS_ENUM(NSInteger, WKUserScriptInjectionTime) { WKUserScriptInjectionTimeAtDocumentStart, WKUserScriptInjectionTimeAtDocumentEnd} / / a Boolean value that indicates the script into the main framework or all of the framework. @property (nonatomic, readonly, getter=isForMainFrameOnly) BOOL forMainFrameOnly;Copy the code

8. Web search

8.1 WKFindConfiguration

Is a configuration parameter to use when searching web view content. Create a WKFindConfiguration object and configure its properties to specify how to perform a search in the contents of the Web view. To start the search, call the appropriate method of WKWebView and pass the object along with the search string.

Configure search parameters:

// A Boolean value indicating the search direction relative to the current selection. Default to NO @property (nonatomic) BOOL BACKWARDS; // A Boolean value indicating whether case is taken into account when matching search strings. Default is NO @property (nonatomic) BOOL caseSensitive; // A Boolean value indicating whether the search goes around to the other side of the page. The default is YES @property (nonatomic) BOOL wraps;Copy the code

8.2 WKFindResult

An object that contains the results of a search for web view content. When you perform a search using the WKWebView method, the WebView creates a WKFindResult object and delivers it to your completion handler. You do not need to create an instance of the class directly. Use the objects provided by the Web view to determine if it has found a match.

Get search results:

// A Boolean value indicating whether the Web view found a match during the search. @property (nonatomic, readonly) BOOL matchFound;Copy the code

9. Context menu

9.1 WKContextMenuElementInfo

The WKContextMenuElementInfo object contains the URL of the link in the Web view content. Object that contains information about a link that a user clicked on in a web page, which you can use to configure a context menu for that link.

You do not need to create an instance of the class directly. Instead, as the user interacts with links, the Web view creates them and passes them to the methods of the WKUIDelegate object associated with them. In the delegate method implementation, the URL in this object is used to determine how to configure the context menu.

Get element information:

// The URL of the link that the user clicked. @property (nonatomic, readonly, nullable) NSURL *linkURL;Copy the code

10. Snapshot configuration

10.1 WKSnapshotConfiguration

Configuration data to use when generating images from the content of a Web view. Create a WKSnapshotConfiguration object when you want to generate an image from the contents of a Web view. Use this object to specify the portion of the Web view to capture and the capture behavior.

To generate a snapshot, please pass a configuration object to WKWebView takeSnapshotWithConfiguration: completionHandler: method, this method returns a platform native image for you to use.

Specify snapshot size:

// The part of your Web view to capture is specified as a rectangle in the view coordinate system. @property (nonatomic) CGRect rect; //The width of the captured image, in points. @property (nullable, nonatomic, copy) NSNumber *snapshotWidth;Copy the code

Configure the capture behavior:

//A Boolean value that indicates whether to take the snapshot after incorporating any pending screen updates @property (nonatomic) BOOL afterScreenUpdatesCopy the code

10.2 WKPDFConfiguration

Configuration data to use when generating a PDF representation of web view content. When you want to generate a PDF version of web view content, create a WKPDFConfiguration object. Use this object to specify the part of the Web view to capture. To generate a PDF content, delivers the configuration object to WKWebView createPDF (configuration: completionHandler:) method, this method returns the PDF data for you to use.

Specify snapshot size:

// The part of your Web view to capture is specified as a rectangle in the view coordinate system. @property (nonatomic) CGRect rectCopy the code