FlutterWebViewController.swift 12.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//
//  FlutterWebViewController.swift
//  flutter_inappbrowser
//
//  Created by Lorenzo on 13/11/18.
//

import Foundation
import WebKit

public class FlutterWebViewController: NSObject, FlutterPlatformView {
    
    private weak var registrar: FlutterPluginRegistrar?
    var webView: InAppWebView?
    var viewId: Int64 = 0
    var channel: FlutterMethodChannel?
17

18 19
    init(registrar: FlutterPluginRegistrar, withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: NSDictionary) {
        super.init()
20
        
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
        self.registrar = registrar
        self.viewId = viewId
        
        let initialUrl = (args["initialUrl"] as? String)!
        let initialFile = args["initialFile"] as? String
        let initialData = args["initialData"] as? [String: String]
        let initialHeaders = (args["initialHeaders"] as? [String: String])!
        let initialOptions = (args["initialOptions"] as? [String: Any])!
        
        let options = InAppWebViewOptions()
        options.parse(options: initialOptions)
        let preWebviewConfiguration = InAppWebView.preWKWebViewConfiguration(options: options)
        
        webView = InAppWebView(frame: frame, configuration: preWebviewConfiguration, IABController: nil, IAWController: self)
        let channelName = "com.pichillilorenzo/flutter_inappwebview_" + String(viewId)
        self.channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger())
        self.channel?.setMethodCallHandler(self.handle)
        
        webView!.options = options
        webView!.prepare()
        
        if #available(iOS 11.0, *) {
            self.webView!.configuration.userContentController.removeAllContentRuleLists()
            if let contentBlockers = webView!.options?.contentBlockers, contentBlockers.count > 0 {
                do {
                    let jsonData = try JSONSerialization.data(withJSONObject: contentBlockers, options: [])
                    let blockRules = String(data: jsonData, encoding: String.Encoding.utf8)
                    WKContentRuleListStore.default().compileContentRuleList(
                        forIdentifier: "ContentBlockingRules",
                        encodedContentRuleList: blockRules) { (contentRuleList, error) in
                            
                            if let error = error {
                                print(error.localizedDescription)
                                return
                            }
                            
                            let configuration = self.webView!.configuration
                            configuration.userContentController.add(contentRuleList!)
                            
                            self.load(initialUrl: initialUrl, initialFile: initialFile, initialData: initialData, initialHeaders: initialHeaders)
                    }
                    return
                } catch {
                    print(error.localizedDescription)
                }
            }
        }
        load(initialUrl: initialUrl, initialFile: initialFile, initialData: initialData, initialHeaders: initialHeaders)
    }
    
    public func view() -> UIView {
        return webView!
    }
    
    public func load(initialUrl: String, initialFile: String?, initialData: [String: String]?, initialHeaders: [String: String]) {
        if initialFile != nil {
            do {
                try webView!.loadFile(url: initialFile!, headers: initialHeaders)
            }
            catch let error as NSError {
                dump(error)
            }
            return
        }
        
        if initialData != nil {
            let data = (initialData!["data"] as? String)!
            let mimeType = (initialData!["mimeType"] as? String)!
            let encoding = (initialData!["encoding"] as? String)!
            let baseUrl = (initialData!["baseUrl"] as? String)!
            webView!.loadData(data: data, mimeType: mimeType, encoding: encoding, baseUrl: baseUrl)
        }
        else {
            webView!.loadUrl(url: URL(string: initialUrl)!, headers: initialHeaders)
        }
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let arguments = call.arguments as? NSDictionary
        switch call.method {
            case "getUrl":
                result( (webView != nil) ? webView!.url?.absoluteString : nil )
                break
            case "getTitle":
                result( (webView != nil) ? webView!.title : nil )
                break
            case "getProgress":
                result( (webView != nil) ? Int(webView!.estimatedProgress * 100) : nil )
                break
            case "loadUrl":
                if webView != nil {
                    let url = (arguments!["url"] as? String)!
                    let headers = (arguments!["headers"] as? [String: String])!
                    webView!.loadUrl(url: URL(string: url)!, headers: headers)
                    result(true)
                }
                else {
                    result(false)
                }
                break
            case "postUrl":
                if webView != nil {
                    let url = (arguments!["url"] as? String)!
                    let postData = (arguments!["postData"] as? FlutterStandardTypedData)!
                    webView!.postUrl(url: URL(string: url)!, postData: postData.data, completionHandler: { () -> Void in
                        result(true)
                    })
                }
                else {
                    result(false)
                }
                break
            case "loadData":
                if webView != nil {
                    let data = (arguments!["data"] as? String)!
                    let mimeType = (arguments!["mimeType"] as? String)!
                    let encoding = (arguments!["encoding"] as? String)!
                    let baseUrl = (arguments!["baseUrl"] as? String)!
                    webView!.loadData(data: data, mimeType: mimeType, encoding: encoding, baseUrl: baseUrl)
                    result(true)
                }
                else {
                    result(false)
                }
                break
            case "loadFile":
                if webView != nil {
                    let url = (arguments!["url"] as? String)!
                    let headers = (arguments!["headers"] as? [String: String])!
                    
                    do {
                        try webView!.loadFile(url: url, headers: headers)
                        result(true)
                    }
                    catch let error as NSError {
                        result(FlutterError(code: "InAppBrowserFlutterPlugin", message: error.domain, details: nil))
                        return
                    }
                }
                else {
                    result(false)
                }
                break
            case "injectScriptCode":
                if webView != nil {
                    let source = (arguments!["source"] as? String)!
                    webView!.injectScriptCode(source: source, result: result)
                }
                else {
                    result("")
                }
                break
            case "injectScriptFile":
                if webView != nil {
                    let urlFile = (arguments!["urlFile"] as? String)!
                    webView!.injectScriptFile(urlFile: urlFile)
                }
                result(true)
                break
            case "injectStyleCode":
                if webView != nil {
                    let source = (arguments!["source"] as? String)!
                    webView!.injectStyleCode(source: source)
                }
                result(true)
                break
            case "injectStyleFile":
                if webView != nil {
                    let urlFile = (arguments!["urlFile"] as? String)!
                    webView!.injectStyleFile(urlFile: urlFile)
                }
                result(true)
                break
            case "reload":
                if webView != nil {
                    webView!.reload()
                }
                result(true)
                break
            case "goBack":
                if webView != nil {
                    webView!.goBack()
                }
                result(true)
                break
            case "canGoBack":
                result((webView != nil) && webView!.canGoBack)
                break
            case "goForward":
                if webView != nil {
                    webView!.goForward()
                }
                result(true)
                break
            case "canGoForward":
                result((webView != nil) && webView!.canGoForward)
                break
            case "goBackOrForward":
                if webView != nil {
                    let steps = (arguments!["steps"] as? Int)!
                    webView!.goBackOrForward(steps: steps)
                }
                result(true)
                break
            case "canGoBackOrForward":
                let steps = (arguments!["steps"] as? Int)!
                result((webView != nil) && webView!.canGoBackOrForward(steps: steps))
                break
            case "stopLoading":
                if webView != nil {
                    webView!.stopLoading()
                }
                result(true)
                break
            case "isLoading":
                result((webView != nil) && webView!.isLoading)
                break
            case "takeScreenshot":
                if webView != nil {
                    webView!.takeScreenshot(completionHandler: { (screenshot) -> Void in
                        result(screenshot)
                    })
                }
                else {
                    result(nil)
                }
                break
            case "setOptions":
                if webView != nil {
                    let inAppWebViewOptions = InAppWebViewOptions()
                    let inAppWebViewOptionsMap = arguments!["options"] as! [String: Any]
                    inAppWebViewOptions.parse(options: inAppWebViewOptionsMap)
                    webView!.setOptions(newOptions: inAppWebViewOptions, newOptionsMap: inAppWebViewOptionsMap)
                }
                result(true)
                break
            case "getOptions":
                result((webView != nil) ? webView!.getOptions() : nil)
                break
            case "getCopyBackForwardList":
                result((webView != nil) ? webView!.getCopyBackForwardList() : nil)
                break
            case "findAllAsync":
                if webView != nil {
                    let find = arguments!["find"] as! String
                    webView!.findAllAsync(find: find, completionHandler: nil)
                    result(true)
                } else {
                    result(false)
                }
                break
            case "findNext":
                if webView != nil {
                    let forward = arguments!["forward"] as! Bool
                    webView!.findNext(forward: forward, completionHandler: {(value, error) in
                        if error != nil {
                            result(FlutterError(code: "FlutterWebViewController", message: error?.localizedDescription, details: nil))
                            return
                        }
                        result(true)
                    })
                } else {
                    result(false)
                }
                break
            case "clearMatches":
                if webView != nil {
                    webView!.clearMatches(completionHandler: {(value, error) in
                        if error != nil {
                            result(FlutterError(code: "FlutterWebViewController", message: error?.localizedDescription, details: nil))
                            return
                        }
                        result(true)
                    })
                } else {
                    result(false)
                }
                break
            case "clearCache":
                if webView != nil {
                    webView!.clearCache()
                }
                result(true)
                break
            default:
                result(FlutterMethodNotImplemented)
                break
        }
    }
}