Last active
August 17, 2019 04:04
-
-
Save zzdjk6/90a85e20e92d07b3db76bbc7b653c233 to your computer and use it in GitHub Desktop.
WKWebView CORS Solution: WebAppViewController.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WebAppViewController: UIViewController { | |
var webView: WKWebView? | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let contentController = WKUserContentController() | |
contentController.add(self, name: "native") | |
let config = WKWebViewConfiguration() | |
config.userContentController = contentController | |
let webView = WKWebView(frame: self.view.frame, configuration: config) | |
self.webView = webView | |
view.addSubview(webView) | |
} | |
} | |
extension WebAppViewController: WKScriptMessageHandler { | |
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { | |
guard let body = message.body as? [String: Any] else { return } | |
guard let type = body["type"] as? String else { return } | |
if (type == "SEND_HTTP_REQUEST") { | |
guard let uuid = body["uuid"] as? String else { return } | |
guard let urlString = body["url"] as? String else { return } | |
guard let bodyString = body["body"] as? String else { return } | |
guard let method = body["method"] as? String else { return } | |
guard let contentType = body["content_type"] as? String else { return } | |
guard let accept = body["accept"] as? String else { return } | |
guard let url = URL(string: urlString) else { return } | |
var request = URLRequest(url: url) | |
request.httpMethod = method | |
request.httpBody = bodyString.data(using: .utf8) | |
request.addValue(contentType, forHTTPHeaderField: "Content-Type") | |
request.addValue(accept, forHTTPHeaderField: "Accept") | |
let task = URLSession.shared.dataTask(with: request) { data, response, error in | |
// TODO: handle the result | |
} | |
task.resume() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment