I have not touched Swift code for more than a year. My skills become rusty.
I am not sure what stupid errors I made in the following code:
extension Bundle {
func readResourceFile(_ filename: String) -> String? {
if let fileUrl = self.resourceURL?.appendingPathComponent(filename, isDirectory: false) {
return try? String(contentsOf: fileUrl)
}
return nil
}
}
class MyVC {
//...
@IBAction func testButton_click(_ sender: Any) {
Task.init { await self.test1() }
}
func test1() async {
var loaded = false
do {
let result = try await self.webView.evaluateJavaScript("typeof(jQuery)")
loaded = result as? String == "function"
} catch {
self.statusLabel.stringValue = "error: \(error)"
}
if (loaded) {
await self.runUserScript(self.input.string)
return
}
let scriptFiles = ["jQuery.js", "Scriptlets.js"]
var count = 0
for scriptFile in scriptFiles {
print("Loading \(scriptFile)")
do {
if let script = Bundle.main.readResourceFile(scriptFile) {
try await self.webView.evaluateJavaScript(script)
print("Loaded \(scriptFile)")
count += 1
}
} catch {
self.statusLabel.stringValue = "error: \(error)"
}
}
}
The line if let script = Bundle.main.readResourceFile(scriptFile) {
succeeds but script still is nil and causes app crash in next line self.webView.evaluateJavaScript(script)
.
Bundle.main.readResourceFile(scriptFile)
is working if I run this line elsewhere.
EDIT:
When I click on the I button in debugging on variable script
I get:
(String) script = <no location, value may have been optimized out>
However, I can print(script)
and the output is correct.