I am new to swift, so any advice would be appreciated. So the I have seen URL and URLSession return a timeout response, the android varient of my app does not show this issue.
class HasInternet: ObservableObject {
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "Monitor")
private var status: NWPath.Status = .requiresConnection
@Published var isConnected = false
init(){
monitor.pathUpdateHandler = { [weak self] path in
if let url = URL(string: "https://google.com") {
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
request.timeoutInterval = 30
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 30.0
sessionConfig.timeoutIntervalForResource = 60.0
URLSession(configuration: sessionConfig)
.dataTask(with: request) { (_, response, error) -> Void in
guard error == nil else {
return
}
guard (response as? HTTPURLResponse)?
.statusCode == 200 else { return }
DispatchQueue.main.async {
self?.isConnected = true
}
}
.resume()
}
}
monitor.start(queue: queue)
}
}
Here is another place with the same behaviour.
func post(dModel: DialogModel? = nil, url: String, type: responseTypes, body: [String: Any], headers: [headerType], async: Bool = true) { //async
let semaphore = DispatchSemaphore(value: 0)
let timeout: TimeInterval = 10
if let url = URL(string: url) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.timeoutInterval = 30
for header in headers {
request.setValue(header.value, forHTTPHeaderField: header.key)
}
do {
request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
} catch let error {
self.processError(dModel: dModel, error: error.localizedDescription, type: .report)
return
}
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 30.0
sessionConfig.timeoutIntervalForResource = 60.0
URLSession(configuration: sessionConfig)
.dataTask(with: request) { (data, response, error) -> Void in
if let error = error {
self.processError(dModel: dModel, error: error.localizedDescription, type: .report)
if(async){
semaphore.signal() // Signal semaphore even in case of error
}
return
}
if let httpResponse = response as? HTTPURLResponse{
if let unWrappedData = data {
if let httpResponseData = String(data: unWrappedData, encoding: .utf8) {
self.parse(dModel: dModel, type: type, response: httpResponseData, statusCode: httpResponse.statusCode)
}
}
} else {
self.processError(error: "Invalid response")
}
if(async){
semaphore.signal() // Signal semaphore after processing the response
}
}
.resume()
if(async){
semaphore.wait(timeout: .now() + timeout)
}
} else {
processError(error: "Invalid URL")
}
}
WebKit JS
RSS for tagAccess and modify DOM elements within a webpage, including touch events and visual effects, using WebKit JS.
Posts under WebKit JS tag
50 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
i can sure the app already hava the camera access, but in the embedded html, i still cannot open the camera. And this HTML page is work at Safari, but cant work on app when the page is embedded in app.
there is the error message:
DOMException: undefine is not an object (evaluating 'navigator.mediaDevices.getUserMedia')
and i also try to use 'navigator.getUserMedia' and 'navigator.mediaDevices.enumerateDevices()', this all dont work.
Since my question exceeds 700 words, please check it in the attachment. Thank you!
Question
We are using a WKWebKit based Cordova application and we are getting WKWebKit crash resulting in blank page.
The same web app is working in browser and other platforms. Upon investigation we found the memory used in iOS app using safari debugger / profiler.
The total memory used is 870.13 MB. Break up of that is
Page: 549MB
JavaScript: 321.13MB
However, the max comparison for memory shown in safari is 1.37GB while the current usage is 870.13MB. Is there any internal memory calculation for crash cutoff?
In this case the current memory is around 62% of the max comparison. Hence, we need to know whether this is the expected behaviour from iOS platform.
JetsamEvent-2024-05-23-102822.ips
Issue Summary:
I have encountered an issue where JavaScript does not execute in a WebView when another UIViewController is presented modally with modalPresentationStyle.fullScreen. This problem only occurs on physical devices running iOS 17.5.1. The issue is not present on iOS 17.5 simulators or devices running iOS 17.4.1 or earlier.
Reproduction Steps:
Create a ViewController with a WebView.
Load a web page (e.g., https://apple.com) in the WebView.
Present another ViewController modally with modalPresentationStyle.fullScreen.
Verify that JavaScript execution in the initial WebView stops working.
Test Code:
import UIKit
import WebKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Set up the WebView
let configuration = WKWebViewConfiguration()
let webView = WKWebView(frame: view.frame, configuration: configuration)
view.addSubview(webView)
webView.frame = view.frame
if #available(iOS 16.4, *) {
webView.isInspectable = true
} else {
// Fallback on earlier versions
}
webView.load(URLRequest(url: URL(string: "https://apple.com")!))
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let navigationController = UINavigationController(rootViewController: TargetViewController())
navigationController.modalPresentationStyle = .fullScreen
present(navigationController, animated: true)
}
}
class TargetViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Set up the WebView
let webView = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
view.addSubview(webView)
webView.frame = view.frame
if #available(iOS 16.4, *) {
webView.isInspectable = true
} else {
// Fallback on earlier versions
}
webView.load(URLRequest(url: URL(string: "https://apple.com")!))
}
}
Observations:
The JavaScript within the WebView stops executing only on physical devices running iOS 17.5.1.
This issue does not occur on the iOS 17.5 simulator.
Devices running iOS 17.4.1 or earlier do not experience this issue.
Request for Assistance:
Could you please provide any insights or potential workarounds for this issue? Additionally, if this is a known bug, any information on upcoming fixes would be highly appreciated.
Thank you.
Hi
In my app I've to complete the IDV [Identity verification] by capturing the face os user and his/her documents, for this the backend developer provides me the URL from the IDV 3rd party, which URL I do open in webview, so before during loading the camera captureing screen in webview the Live Broadcast screen pops up from no where. I don't want this Live Broadcast screen but somehow it opens anyway. Although it is good thing that my expected camera screen was still open in background so I can go further from there.
First time I'm also bit confused like how this kind of screen popsup even if I did't code for it. Also it takes me a little bit time to figure out how to close that screen.
Simple peoples/users who're going to use my app they don't know how to close it. Please check the screenshots I attached. Please help me to rid of this popup.
Thank You
I have the following html that is opened in a WKWebView.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Popup Window Test</title>
</head>
<body>
<textarea id="myTextarea" cols="5" rows="1">Empty</textarea>
<script>
function openWindow() {
const popup = window.open(
"https://www.apple.com/",
"PopupSample",
"width=400,height=400,dialog=yes,dependent=yes,scrollbars=yes,location=yes"
);
console.log("Popup closed: ", popup.closed);
document.getElementById("myTextarea").value = popup.closed
? "Closed"
: "Open";
const timer = setInterval(() => {
console.log(popup.location.href);
if (popup.closed) {
clearInterval(timer);
console.log("Popup closed: ", popup.closed);
document.getElementById("myTextarea").value = "Closed";
}
}, 1000);
}
</script>
<button onclick="openWindow()">Open Window</button>
</body>
</html>
When I click the button and open page "https://www.apple.com/" in another WKWebView, the javascript code does not work as expected here, the popup object returned from window.open() does not refer to the valid window object, and the closed property is set to true even the new popup window is still alive.
This is a regression since MacOS14.4 updated, I've reported to apple DTS, but they said it's out of their scope.
Does anyone has any clue about this?
Hi Apple Team,
We have a PWA which supports downloading and playback for audio and video content. Downloaded content is stored in IndexedDB in the form of blobs and blob URLs are generated on runtime through which content is played.
We have observed that the blob URLs have stopped working on iOS 17.4.1. They work on iOS 17.4 and iOS 17.3 as well.
This feature is very critical for us as it is the heart of the offline mode of the app.
Thanks!
I am trying to migrate some of my mapkit code to the Map Server API. My JWT is fine and I can use that within the API Playground just fine. However, when I try to implement a test using PHP and cURL to get my Map token, I receive a 401 Not Authorized Error. My code is below:
<?php
$URL="https://maps-api.apple.com/v1/token";
$accesstoken = "<MY TOKEN HERE>";
$authorization = 'Authorization: Bearer'.$accesstoken;
$headers = [];
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, [$authorization]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$headers[strtolower(trim($header[0]))][] = trim($header[1]);
return $len;
}
);
$result=curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_close ($ch);
print_r($headers);
echo($result);
echo($status_code);
?>
Now the exact response that I am receiving is:
Array ( [date] => Array ( [0] => Thu, 18 Apr 2024 18:32:15 GMT ) [content-type] => Array ( [0] => application/json;charset=utf8 ) [content-length] => Array ( [0] => 51 ) [connection] => Array ( [0] => keep-alive ) [cache-control] => Array ( [0] => max-age=0 ) [x-rid] => Array ( [0] => c9507281-bc32-46ac-be3b-dc59e97e7fed ) [strict-transport-security] => Array ( [0] => max-age=31536000; includeSubDomains; ) )
{"error":{"message":"Not Authorized","details":[]}}
401
Any help getting this to work would be appreciated.
Hello
Our app met issue after iOS 17.4 update.
Native view works properly with App language setting. But WKWebview's language is set with general OS setting's language.
In example,
When OS language is Korean and App language is English,
Native view is shown with English, but WKWebview is shown with Korean.
We found that navigator.language is Korean.
This problem has been occurring since iOS 17.4 version.
If anyone knows anything about this issue, could you please share?
Even when iOS's '"." Shortcut' keyboard setting is enabled, double-tapping the spacebar in WKWebView doesn't insert a period.
While making WKWebView editable , "." shortcut is not working. It works fine when any other external keyboard is used. I am facing this issue in WKWebView using apple keyboard. Even forceful adding javascript to replace double tap of space bar to period character logic is not working.
After insert this script I can't see the property window.app.isNative = true on Safari, What I'm missing here? Thanks in advance
userContentController.addUserScript(WKUserScript(source: """function() {
if (!window.app) {
window.app = {};
}
window.app.isAndroid = false;
window.app.isIOS = true;
window.app.isNative = true;
originWhitelist={['*']}
}
""", injectionTime: .atDocumentStart, forMainFrameOnly: true))
After upgrading to ios17.4, webview app cannot access localstorage
How to detect the location of a mouseDown event using Swift?
With the following code snippet, I get the error "Cannot find type 'NSEvent' in scope"?
import SpriteKit
func mouseDown(with event: NSEvent) {
if let ourScene = GameScene(fileNamed: "GameScene") {
let location = event.location(in: view)
let node:SKNode = ourScene.atPoint(location)
if (node.name == "creditsInfo") {
showCredits()
}
} // if let ourScene
} // mouseDown
Anybody have a floodlight to shine on this very basic error?
Firebase JS SDK require Notification check so we are added. But its not working in iOS and iPad.
Version: 17.3.1
Working MacOS Safari 17.3.1
Hi Team,
We are working on one of the Acute Healthcare Imaging application and application is running under WKWebview controller. We have observed many crashes when GC doesn't get executed in timely manner. This is very critical healthcare app which has direct impact on patient care.
Appreciate any guidance or direction to force GC or optimized dereferenced objects.
Thanks in advance for your attnetion.
-RA
Hello community, first post I hope to meet the guidelines.
I am developing a web site that uses a library that involves audio playback.
This playback is accompanied by an animated canva, and in the IOS17 version in safari, this does not work. The audio is muted and the canva does not animate.
However, in ios16 safari it works perfectly.
I have also tried in safari on MacOs and ipadOs and it works, which makes me see that the problem is with ios 17 safari.
The library in question is this: https://github.com/foobar404/Wave.js/
I don't think the failure is in the library since it works as I said in all other platforms.
Specifically the code is here: https://github.com/foobar404/wave.js/blob/main/src/index.ts and makes me think that some HTML element is being incompatible.
It is necessary to emphasize that in ios17 it does not work, but it does not appear any error in console.
I would love to get help or know if this is a bug to report it.
Hi,
After iOS 17 software update, we've encountered an anomaly with the video element within our videojs player. Upon video load, there's a noticeable shift and recentring of the video to its correct position.
This issue becomes more pronounced when the player is in a horizontal orientation while the video being played is vertical.
Additionally, we've observed resizing and cropping issues during the initialization of the player, which were not present in earlier versions. In our current implementation, we have a canvas element inserted before the player. Due to resizing, the video sticks to the canvas and fails to return to the correct position.
<div>
<video class="vjs-tech"
webkit-playsinline
playsinline
src="hls video source">
</video>
<canvas style="filter: blur(15px)" class="vjs-tech custom-canvas" width="412" height="320">
</canvas>
</div>
Intercept WebView requests and add Auth token in all subsequent resource request [GET --> .js, .png, .css].
We have tried the below delegate methods and those call are not getting invoked.
We have a challenge with Webview when load our application URL.
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
we are looking for some delegate or protocol to intercept the request to add the token for all the requests.
is there any possible solution to fix this issue?
Thanks
I'm finding some issues with my iOS application that are related to the WebKit framework. I'm receiving the following errors in the application log:
01:05.995.258 Error Space Warhog (2434) com.apple.WebKit IPC 0x114088220 - Connection::dispatchIncomingMessages: IPC throttling was triggered (has 2'458 pending incoming messages, will only process 60 before yielding)
01:05.995.286 Error Space Warhog (2434) com.apple.WebKit IPC 0x114088220 - Connection::dispatchIncomingMessages: first IPC message in queue is WebUserContentControllerProxy_DidPostMessage
It happens just when I make a purchase in the app. It does the whole process correctly (apparently), but once the "Purchase successful" pop up appears, the result is duplicated. If I make a second purchase, once I get the correct coins, the APP freezes and I have to restart it.
Thank you for your help!