I need to load both the local source images and remote source images in WKWebView.
The url of remote images is a relative url.
To load the local images in WebView, I could use loadFileURL(:allowingReadAccessTo:).
To load the remote images in WebView, I could use loadHTMLString(:baseURL:).
But, I need both the local images and remote images.
How can I do?
WebKit
RSS for tagDisplay web content in windows and implement browser features using WebKit.
Posts under WebKit tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
We're integrating a web based group calling application within a native iOS application and finding that every time a CallKit session gets fully established the web based media streams break, rendering as gray with no audio.
Up to iOS 18 we worked around it by not fulfilling the call start action but that's no longer an option as the audio stopped getting automatically redirected to the speakers. We would now need the CXProvider's didActivateAudioSession callback but that would break the video.
The sample project loads up a simple webpage in a WKWebView which contains a video tag streaming the media from the device's camera.
At the same time it sets up a new CallKit session by requesting and fulfilling a CXStartCallAction transaction.
You will notice that the media doesn't render and, if you are to follow the warnings we left, you will find that not fulfilling the CXStartCallAction fixes it.
Unfortunately that's not a workaround we can use as we need the CXProvider delegate to inform us about audio session changes so we can redirect the audio to the speaker (so the proximity sensor doesn't activate and locking the screen doesn't end the call)
Any insights or workarounds would be greatly appreciated.
Hello, Team.
We used WKWebView for our project. We loaded the HTML file into the webview and added the following configuration.
weak var webView: WKWebView!
func configWebView() {
let webViewConfig = WKWebViewConfiguration()
let controller = WKUserContentController()
controller.add(self, name: "sometest")
webViewConfig.userContentController = controller
webViewConfig.processPool = WKProcessPool()
webViewConfig.setValue(true, forKey: "allowUniversalAccessFromFileURLs")
webViewConfig.mediaTypesRequiringUserActionForPlayback = []
let webpagePreferences = WKWebpagePreferences()
webpagePreferences.allowsContentJavaScript = true
webViewConfig.defaultWebpagePreferences = webpagePreferences
webViewConfig.websiteDataStore = WKWebsiteDataStore.default()
webView = WKWebView(frame: .zero, configuration: webViewConfig)
webView.navigationDelegate = self
webView.uiDelegate = self
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: view.topAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
loadWebView()
}
func loadWebView() {
guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
return
}
let contentFolderURL = documentsDirectoryURL.appendingPathComponent("content")
let assetFolderURL = contentFolderURL.appendingPathComponent(interactiveGUID)
if FileManager.default.fileExists(atPath: assetFolderURL.path) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let documentsURL = URL(fileURLWithPath: documentsPath)
let fileToLoadPath = (documentsPath as NSString).appendingPathComponent("content/index_p.html")
let fileURL = URL(fileURLWithPath: fileToLoadPath)
autoreleasepool {
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.webView.loadFileURL(fileURL, allowingReadAccessTo: documentsURL)
}
}
}
We are experiencing webview crashes when loading an HTML file. What happened when I loaded the video file? It automatically looped. Webview frequently crashes when the HTM/JS file is loaded.
When a webview crashes, the delegate method usually calls webViewWebContentProcessDidTerminate. This method calls webview.reload().
Also we are clear and cache/ deallocate eveything when i initialized those configuration mentioned as the above.
Can you suggest a solution to this? Why is webview crashing?
Thank you.
I couldn't find any documentation related to if WebRTC is supported in macOS/macOS Catalyst, but all my tests related to that fail.
I also experience the same as in this post:
https://developer.apple.com/forums/thread/695871?login=true
Meanwhile in iOS it works well.
Hi!
I have a rather complicated SwiftUI browser app with a WKWebView. There is an option to reload the website after a configurable amount of time. Starting with iOS 18, the app crashes after repeated reloads. How many reloads that are required depends on the device, sometimes 100, sometimes 1000.
Reloading is done via a timer that triggers the following code on the main thread:
let request = URLRequest(url: url, cachePolicy: policy)
self.parent.webView.load(request)
The URL is configurable and cachePolicy can be either .reloadIgnoringLocalAndRemoteCacheData or .useProtocolCachePolicy
How the crash affects the device also differs from device to device and from time to time. I have suffered from the following crashtypes:
App is killed
App is killed and Safari also stops working
App is killed and the whole OS is really slow
The WKWebView stops loading and hangs at 20%.
The device is rebooted
My app has an option to disable cache. Cache is disabled by setting cachePolicy to .reloadIgnoringLocalAndRemoteCacheData and by removing all cache in a rather complicated way.
Basicly i'm doing something like this:
dataStore.removeData(ofTypes: types, modifiedSince: Date.distantPast, completionHandler: nil)
if let klazz = NSClassFromString("Web" + "History"),
let clazz = klazz as AnyObject as? NSObjectProtocol {
if clazz.responds(to: Selector(("optional" + "Shared" + "History"))) {
if let webHistory = clazz.perform(Selector(("optional" + "Shared" + "History"))) {
let o = webHistory.takeUnretainedValue()
_ = o.perform(Selector(("remove" + "All" + "Items")))
}
}
}
if let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first {
let contents = (try? FileManager.default.contentsOfDirectory(atPath: cachesPath)) ?? []
for file in contents {
if foldersToDelete.contains(file) {
let path = cachesPath.appending("/").appending(file)
do {
try FileManager.default.removeItem(atPath: path)
} catch {
print("Can't delete cache file: \(path), error: \(error.localizedDescription)")
}
}
}
}
The cache state affects the intensity of the crash. Disabling the cache shortens the time the app is working, while enabling the cache reduces the intensity of the bug.
Based on my investigation, I suspect that loading a website in a WKWebVew leaks memory in iOS 18. If the whole website needs to be requested (= caching off), it results in a more significant memory leak and a faster crash time.
Is this a known issue? Am I doing something wrong? Is there a potential workaround?
I am experiencing a critical issue with WKWebView navigation in iOS 18.2 beta, specifically regarding the function webView.loadFileURL(_:allowingReadAccessTo:).
In previous versions of iOS, this function works as expected when loading valid file URLs from the app’s local directory (e.g., Application Support). However, in iOS 18.2 beta, the function fails to complete the navigation, producing a provisional navigation failure with WebKitErrorDomain, code 102 (Frame load interrupted). This issue severely impacts our app’s ability to load essential local resources, breaking core functionality.
Here’s a summary of the troubleshooting steps and findings:
File and Directory Verification: The url provided to loadFileURL is valid. Both the file path and parent directory exist within the app’s sandbox, and the directory is accessible.
Configuration: The code specifies the parent directory in the allowingReadAccessTo parameter to meet sandboxing requirements, which works on iOS 18.1 and prior releases.
Testing on Stable iOS Versions: The issue is exclusive to iOS 18.2 beta; testing on earlier stable iOS releases confirms that the function works as intended.
Impact: This regression severely disrupts the app’s navigation and content loading, effectively blocking access to local resources required for the WKWebView to display content properly.
The error log returned in the console is as follows:
> Error Domain=WebKitErrorDomain Code=102 "Frame load interrupted" UserInfo={_WKRecoveryAttempterErrorKey=<WKReloadFrameErrorRecoveryAttempter: 0x303dd67e0>, NSErrorFailingURLStringKey=file:///var/mobile/Containers/Data/Application/4D128818-7E51-460E-B5D4-D2D70363EFA0/Library/, NSErrorFailingURLKey=file:///var/mobile/Containers/Data/Application/4D128818-7E51-460E-B5D4-D2D70363EFA0/Library/, NSLocalizedDescription=Frame load interrupted}
We suspect this may be due to a change in WebKit permissions in iOS 18.2 beta that affects local file handling within WKWebView.
Given that the our app relies heavily on these resources, we kindly request this issue be addressed promptly. If any additional information or sample code is required, please let us know, and we will gladly provide further details to assist in resolving this issue.
Thank you for your attention and support.
Best regards,
Isabela
Hello everyone,
in my website I need to give users the ability to choose a color via input type=“color”.
I don't understand why it works fine on desktop (even on Safari for Mac) but doesn't open the color picker on iPhone.
How can I solve this?
Thank you,
Andrea
Hello everyone,
I am currently facing an issue with a Cordova-based app using WKWebView. In our app, we handle page navigation within the WebView. We’ve implemented a back button at the top of the page, which successfully triggers history.goBack() when clicked. However, we also want to support the native left edge pan gesture (swipe back) to trigger history.back().
The issue is that, while the swipe back gesture works most of the time, there are cases where instead of navigating to the immediate previous page, it behaves as if it’s going back to the first page (or initial page). This only occurs on iOS versions 17.5.1 and above. I’ve already set allowsBackForwardNavigationGestures to true, and the back button itself works perfectly.
Has anyone experienced a similar issue, where the swipe back gesture sometimes skips pages and seems to return to the first page on iOS 17.5.1 or later? Any suggestions on how to fix or troubleshoot this would be greatly appreciated.
Thank you!
iOS WKWebview - When we run the WKWebview with loading the HTML file. Including JS method call and video looping it here in js file. Getting this method call webViewWebContentProcessDidTerminate(_ webView: WKWebView). Can anyone provide the solution?
Thanks
Since iPadOS 18.x WKWebView seems to have a bug within its Fullscreen API (which can be enabled via WKPreferences.isElementFullscreenEnabled). This bug has the effect that websites trying to make an element (for example a video player) fullscreen fail to do so. This does not always happen, most of the time the fullscreen mode does work fine, but sometimes (far too often to be ignored) it does not. If an instance of WKWebView shows this issue, it can not be "fixed" by reloading the page or loading other pages, this issue exists in this instance forever.
My App is a web browser App so I can create and remove WKWebView instance easily (by opening or closing Tabs). And there are times where I never see this bug, and times where ever other tab shows this bug. It's totally unreliable.
The App does not show any issues at all when running under iPadOS 17 or older. The issue is only present under iPadOS 18.x.
After some testing I've found out that when the bug has affected an instance of WKWebView, the JavaScript call element.requestFullscreen() will work if the element is a video element, but does no longer work if it is another element (like a DIV). If an instance of WKWebView is not affected by this bug, element.requestFullscreen() will work for all HTML elements.
Does anyone has experienced this bug as well? And maybe found a workaround? Or maybe found a pattern which helps to find out what exactly is triggering this bug?
Recently, we ran into a bit of a problem when using WKWebView. Sometimes, problems with all pages blank occur which use WKWebView.
I implemented WKNavigationDelegate and found that it stops at
- (void)webView:(WKWebView *)theWebView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
and it won't call below func forever
- (void)webView:(WKWebView*)theWebView didStartProvisionalNavigation:(WKNavigation*)navigation
I suspected that the render process is terminated and it won't restart.
Then i try to resolve this problem by call reload func
[self.webView reload];
But it didn't work. In The Meanwhile, i got some error message in console
I have tested it in iOS 16 and 17. only iOS 17 got the issue.
Pray for some help. Thanks a lot.
I'm working on a rather complex web application that includes 3D terrain, 2D mapping, and SVG animations. Both Safari and the Swift app I've built using WkWebKit reload the page after some period of time. Safari pops up a small text block that says:
This webpage was reloaded because it was using significant memory.
Yes. That's true. It's also true that the M1 Max Mac was in now way experiencing issues, nor were any of the other web pages running in other tabs or windows.
The memory limit is simply too low for modern web apps. So far I've not found any way to adjust the parameters in Safari or WkWebView.
Apple, help a brother out. It's not 1997 anymore. Web apps are big. And resetting them at some arbitrary point causes more problems that is solves.
Anyone have any suggestions? Quinn, any way (other than casting a stone into the one-way abyss of Radar) of getting help from the big A here?
I'm developing an application that utilizes WKWebView to display a webpage. My goal is to improve the performance and loading speed of this webpage by intercepting specific API calls and providing pre-stored JSON responses directly from within the app, ensuring the webpage renders instantaneously.
The challenge I am encountering is the inability to intercept HTTPS URL schemes directly from WKWebView. Any insights or solutions from the community on how to effectively manage and overwrite these particular network requests would be greatly appreciated.
I'm injecting some javascript into a WKWebview on iOS. At a certain point the web view spits out these warnings into the console and the javascript execution stops.
0x109018c40 - [PID=778] WebProcessProxy::gpuProcessExited: reason=IdleExit
0x109019200 - [PID=779] WebProcessProxy::gpuProcessExited: reason=IdleExit
Failed to terminate process: Error Domain=com.apple.extensionKit.errorDomain Code=18 "(null)" UserInfo={NSUnderlyingError=0x303c3c060 {Error Domain=RBSRequestErrorDomain Code=3 "No such process found" UserInfo={NSLocalizedFailureReason=No such process found}}}
I can't find any solution for this so am looking if anyone has any idea of what to try.
None of the WKWebview delegate functions trigger when this occurs so I can't attempt to reload the webview at this stage
Hi. I've noticed on both iOS 17 and iPadOS 16 that when an user opens a website in a WKWebview (e.g from Gmail), then requests it to be opened in the external Safari app (through the "compass" icon), their localStorage data is not transferred to the Safari tab.
This behaviour breaks web experiences that rely on data being locally stored, e.g auth tokens or user identification data. It effectively stops users from being able to use some websites outside of an in-app context.
I am aware of Webkit's tracking prevention mechanisms such as https://webkit.org/tracking-prevention/#partitioned-third-party-localstorage, but I don't think this should apply to this case. Here the user is navigating between two Safari tabs (one internal and one external) on the same domain, exact same URL, by pressing a native Safari webview icon. There is no third-party cross-domain tracking happening.
Is this a bug or intended behaviour?
Running a web server on localhost is breaking on the iOS Simulator. It is also blocking me from testing my mobile application.
Full Log:
Full Log
I would like to program an app in Swift Playground that displays WhatsApp Web in a webview, so to speak. But I keep seeing an error like in the screenshot.
My Code:
import SwiftUI
import WebKit
import PlaygroundSupport
struct WebView: UIViewRepresentable {
let url: URL
func makeUIView(context: Context) -> WKWebView {
let webView = WKWebView()
let request = URLRequest(url: url)
webView.load(request)
return webView
}
func updateUIView(_ webView: WKWebView, context: Context) {
}
}
struct ContentView: View {
var body: some View {
WebView(url: URL(string: "https://web.whatsapp.com")!)
.edgesIgnoringSafeArea(.all)
}
}
PlaygroundPage.current.setLiveView(ContentView())
In iOS18, WKWebView's default cookie SameSite value is Lax. Prior to iOS18, the default value is None.
Is this intentional, or a bug? This change is not documented anywhere.
I made a sample XCode project (ViewController code below) to show this change. It loads www.apple.com into a WKWebView and prints cookies. That site has several cookies, but it only explicitly sets SameSite to None for one cookie, s_vi. Every other cookie relies on default WKWebView behavior. When looking at cookies, either in the console or in Safari's Web Inspector, the SameSite value differs. If older than iOS18, every cookie has SameSite of None. If iOS18, all cookies except s_vi have SameSIte of Lax.
I also tried manually setting the following cookies:
testCookie-none with SameSite set to None
testCookie-lax with SameSite set to Lax
testCookie-strict with SameSite set to Strict
testCookie- with SameSite set to an empty string
When looking at these cookies, testCookie-none and testCookie- have their SameSite of None if older than iOS18, but are both Lax in iOS18. So, it seems we cannot manually set the SameSIte to None either.
I realize updating the server to return the SameSite value would resolve this. However, in my app where I'm struggling with this issue, that server is Salesforce. Only they can update their response headers. Since this change isn't documented by Apple, I am assuming it is a bug and not intentional. Are there any workarounds? Any input by Apple on a fix?
Below is the ViewController code, and images of the cookies in Safari's Web Inspector.
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
// Create WKWebView
let config = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: config)
// Allow inspection in Safari debugger
webView.isInspectable = true
// Track the request to load our website
webView.navigationDelegate = self
// Manually add four cookies:
// testCookie-none with SameSite set to None
// testCookie-lax with SameSite set to Lax
// testCookie-strict with SameSite set to Strict
// testCookie- with SameSite set to an empty string
addTestCookies()
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// Load a website
let urlString = "https://www.apple.com"
self.webView.load(URLRequest(url: URL(string:urlString)!))
}
// Once the website loads, print the cookies.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
WKWebsiteDataStore.default().httpCookieStore.getAllCookies { cookies in
for cookie in cookies {
print(cookie)
}
}
}
/*
Manually add the following cookies for domain .apple.com
testCookie-none with SameSite set to None
testCookie-lax with SameSite set to Lax
testCookie-strict with SameSite set to Strict
testCookie- with SameSite set to an empty string
In older iOS versions, both testCookie-none and testCookie- will have their SameSite as none.
In iOS18, no cookie will have SameSite as None.
*/
func addTestCookies()
{
let httpCookieStore = WKWebsiteDataStore.default().httpCookieStore
for sameSitePolicy in ["none", "lax", "strict", ""] {
httpCookieStore.setCookie(HTTPCookie(properties: [
HTTPCookiePropertyKey.path: "/",
HTTPCookiePropertyKey.name: "testCookie-"+sameSitePolicy,
HTTPCookiePropertyKey.value: "1",
HTTPCookiePropertyKey.domain: ".apple.com",
HTTPCookiePropertyKey.secure: true,
HTTPCookiePropertyKey.sameSitePolicy: sameSitePolicy
])!)
}
}
}
I need to play a Video with transparent background on our website.
It works perfectly on Windows, Mac & Android (in all browsers).
On iPhone however, no matter what Browser, The transparent parts of the video act almost like an "overlay", making everything behind it a lot brighter. This effect gets worse, the higher I set the iPhone screen brightness. This is of course not the behavior I'm looking for.
The Video Element has two listed sources. One .WEBM (VP8 with alpha channel) and one .MP4 (HEVC with alpha channel). I am sure, that something is wrong with the MP4 file, but I don't understand why it works in Safari on Mac, but doesn't on iPhone. Shouldn't they both play the same File?
Here is my workflow:
masking the subject in DaVinci Resolve
exporting as QuickTime - Apple ProRes 444 - "Export Alpha"
using Shutter Encoder (v15.7) to convert the file to H.265 (.mp4)
under "Advanced Features": Hardware acceleration to "OSX VideoToolbox" & check "Enable alpha channel"
also converting the first file to VP8 (.webm) with "Enable alpha channel"
then adding the Videos to the website like this:
<video height="450px" autoplay loop muted playsinline disablepictureinpicture>
<source
src="(url of the mp4)"
type='video/mp4; codecs="hvc1"'>
<source
src="(url of the webm)"
type="video/webm">
</video>
Here is how it looks on Safari (Mac)
This is what it looks like in any browser on iPhone
I have re-exported, re-converted and re-implemented it multiple times and I just can't get it to work on iPhone. Does anyone have an idea, what the cause could be, or what I can do differently?
PLATFORM AND VERSION
iOS
Development environment: Other: Xamarin iOS App
Run-time configuration: iOS 14.4.2 and above
DESCRIPTION OF PROBLEM
We are using WKWebView control in our application. It loads a page, wherein there is a code which gets triggered to execute a Synchronous Ajax/XmlHttpRequest. This request needs about 1 min time to complete, but it gets aborted after 10 secs.
Observed in iPhone 6S 14.4.2. Also seen the same behavior in the latest version of iPhone and iPad OS.
Need help on the below points:
How can I extend this timeout?
Making it an Asynchronous call would have regression. Hence the ask for any other alternative to extend this timeout.
STEPS TO REPRODUCE
In the WKWebView have a webpage, which gives a Synchronous ajax/XmlHttpRequest call to a Web API, which takes more than 10 seconds to complete. The Ajax call sample code is as below, which uses jquery:
var startTime = performance.now();
$.ajax({
async: false, // Synchronous ajax call
type: "POST",
url: "http://testsite:8000/api/RunTestTimer",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
timeInSeconds: 15
}), // timeInSeconds is the parameter name in the Web API, which I used to run a timer on the server-side for the value passed to the ajax call
dataType: "json",
beforeSend: skelta.forms.utilities.addRequestHeaders
})
.done(function (result) {
var endTime = performance.now();
var message = "Request Successful (Time Taken to execute: " + ((endTime - startTime) / 1000).toFixed(3) + " secs; Type: " + "POST" + "; Async: " + "FALSE" + "; Timer: " + "15" + " seconds):" + JSON.stringify(result);
console.log(message);
})
.fail(function (result) {
var endTime = performance.now();
var message = "Request Failed (Time Taken to execute: " + ((endTime - startTime) / 1000).toFixed(3) + " secs; Type: " + "POST" + "; Async: " + "FALSE" + "; Timer: " + "15" + " seconds):" + JSON.stringify(result);
console.log(message);
});