Skip to content

Commit

Permalink
fix(ios): set cors headers in asset handler for live reload
Browse files Browse the repository at this point in the history
  • Loading branch information
ItsChaceD authored Jun 23, 2023
1 parent 95b0575 commit e5a1c81
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions ios/Capacitor/Capacitor/CAPBridgeViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import Cordova
// get the web view
let assetHandler = WebViewAssetHandler(router: router())
assetHandler.setAssetPath(configuration.appLocation.path)
assetHandler.setServerUrl(configuration.serverURL)
let delegationHandler = WebViewDelegationHandler()
prepareWebView(with: configuration, assetHandler: assetHandler, delegationHandler: delegationHandler)
view = webView
Expand Down
1 change: 1 addition & 0 deletions ios/Capacitor/Capacitor/CAPWebView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ open class CAPWebView: UIView {
private lazy var assetHandler: WebViewAssetHandler = {
let handler = WebViewAssetHandler(router: router)
handler.setAssetPath(configuration.appLocation.path)
handler.setServerUrl(bridge.config.serverURL)
return handler
}()

Expand Down
12 changes: 12 additions & 0 deletions ios/Capacitor/Capacitor/WebViewAssetHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import MobileCoreServices
// swiftlint:disable type_body_length
internal class WebViewAssetHandler: NSObject, WKURLSchemeHandler {
private var router: Router
private var serverUrl: URL?

init(router: Router) {
self.router = router
Expand All @@ -15,6 +16,10 @@ internal class WebViewAssetHandler: NSObject, WKURLSchemeHandler {
router.basePath = assetPath
}

func setServerUrl(_ serverUrl: URL?) {
self.serverUrl = serverUrl
}

func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
let startPath: String
let url = urlSchemeTask.request.url!
Expand All @@ -36,6 +41,13 @@ internal class WebViewAssetHandler: NSObject, WKURLSchemeHandler {
"Content-Type": mimeType,
"Cache-Control": "no-cache"
]

// if using live reload, then set CORS headers
if self.serverUrl != nil && self.serverUrl?.scheme != localUrl.scheme {
headers["Access-Control-Allow-Origin"] = self.serverUrl?.absoluteString
headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
}

if let rangeString = urlSchemeTask.request.value(forHTTPHeaderField: "Range"),
let totalSize = try fileUrl.resourceValues(forKeys: [.fileSizeKey]).fileSize,
isMediaExtension(pathExtension: url.pathExtension) {
Expand Down

0 comments on commit e5a1c81

Please sign in to comment.