Swiftpack.co - vincent-k-sm/MKWebviewBridge as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by vincent-k-sm.
vincent-k-sm/MKWebviewBridge 2.0.7
Common Webview Bridging with scheme (deeplink)
โญ๏ธ 0
๐Ÿ•“ 1 week ago
iOS macOS
.package(url: "https://github.com/vincent-k-sm/MKWebviewBridge.git", from: "2.0.7")

MKWebViewBridge

์†Œ๊ฐœ

  • ๊ฐœ์ธ ํ”„๋กœ์ ํŠธ์—์„œ ๊ณตํ†ต์œผ๋กœ ์‚ฌ์šฉ๋˜๋Š” ์›น๋ทฐ๋ฅผ ํ”„๋ ˆ์ž„์›Œํฌํ™” ํ•ฉ๋‹ˆ๋‹ค

https://user-images.githubusercontent.com/24787667/160655332-d618e441-6147-40f9-b263-f002eae52a35.mov



Requirements

Platform Minimum Swift Version Installation Status
iOS 13.0+ / macOS 11.0+ 5.0 Swift Package Manager, Manual Fully Tested



Installation

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding MKWebViewBridge as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/vincent-k-sm/MKWebviewBridge", .upToNextMajor(from: "1.0.0"))
]

Manually

If you prefer not to use any of the aforementioned dependency managers, you can integrate MKWebViewBridge into your project manually.

Embedded Framework

  • Open up Terminal, cd into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:

    $ git init
    
  • Add MKWebView as a git submodule by running the following command:

    $ git submodule add https://github.com/vincent-k-sm/MKWebviewBridge
    

    After download We Suggest Remove Example Folder When Embed

  • Click on the + button under th Frameworks, Libraries, and Embedded Content

  • Click on the Add Other and Select in MKFoundation folder

  • Drag the MKFoundation folder into the Project Navigator of your application's Xcode project.

    It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.

  • And that's it!



Features



Example



Common WebView Configuration

MKWebViewConfiguration.swift

/// Webview๋ฅผ ์„ธํŒ…ํ•˜๋Š” MKWebViewConfiguration ์ž…๋‹ˆ๋‹ค
/// - Parameters:
///   - host: deeplink ์— ํ™œ์šฉ๋˜๋Š” host๊ฐ€ ์ ์šฉ๋ฉ๋‹ˆ๋‹ค (plist ๋‚ด ๋“ฑ๋ก๋œ url Types๋ฅผ ๋ชจ๋‘ ์ฒดํฌํ•ฉ๋‹ˆ๋‹ค)
///   - urlString: landing url ์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค
///   - title: ๋„ค๋น„๊ฒŒ์ด์…˜ ๋ฐ” ๋‚ด ํŽ˜์ด์ง€ ํƒ€์ดํ‹€์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค
///   - leftBtn: ์ขŒ์ธก ๋ฒ„ํŠผ (<-) ์„ ํ™œ์„ฑํ™” ํ•ฉ๋‹ˆ๋‹ค
///   - rightBtn: ์šฐ์ธก ๋ฒ„ํŠผ (x) ์„ ํ™œ์„ฑํ™” ํ•ฉ๋‹ˆ๋‹ค
///   - navigationColor: ๋„ค๋น„๊ฒŒ์ด์…˜ ๋ฐ”์˜ ์ƒ‰์ƒ์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค (hexString)
///   - statusBarColor: ์ƒ๋‹จ ์Šคํ…Œ์ดํ„ฐ์Šค ๋ฐ”์˜ ์ƒ‰์ƒ์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค (hexString)
///   - tintColor: ๋„ค๋น„๊ฒŒ์ด์…˜ ๋ฐ” ๋‚ด ๋ฒ„ํŠผ, ํƒ€์ดํ‹€ ๋“ฑ์˜ ์ƒ‰์ƒ์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค (hexString)
///   - removeStack:๊ธฐ์กด stack ์— ์Œ“์—ฌ์žˆ๋Š” ๋ชจ๋“   controller๋ฅผ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค
///   - navigationBarIsEnable: 
///     -> host, urlString, navigationBarIsEnable, removeStack ๊ฐ’์— ๋”ฐ๋ผ ๋„ค๋น„๊ฒŒ์ด์…˜๋ฐ” ๋…ธ์ถœ ์—ฌ๋ถ€๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค
///   - important:
///     -> host, urlString, navigationBarIsEnable, removeStack ์„ ์ œ์™ธํ•˜๊ณ  ๋ชจ๋“  value๊ฐ€ nil ์ธ ๊ฒฝ์šฐ ๋„ค๋น„๊ฒŒ์ด์…˜๋ฐ”๊ฐ€ ๋…ธ์ถœ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค
public struct MKWebViewConfiguration: Codable {
    public var host: String                = ""
    public var urlString: String           = ""
    public var title: String?              = nil
    public var leftBtn: Bool?              = nil
    public var rightBtn: Bool?             = nil
    public var navigationColor: String?    = nil
    public var statusBarColor: String?     = nil
    public var tintColor: String?          = nil
    public var removeStack: Bool?          = nil
    public var navigationBarIsEnable: Bool = false
}

USE CASE

  • It's automatically pared from deeplink action
    • eg.
    mkwebview://webview?url=https://smbh.kr/mk_bridge/sample
    &title=ํ…Œ์ŠคํŠธ
    &navigationColor=FFFFFF
    &tintColor=000000
    &statusBarColor=FFFFFF
    
  • Even you can use in model input
    /// create option
    let configure = MKWebViewConfiguration(
        host: "webview",
        urlString: "https://smbh.kr/mk_bridge/sample",
        title: <#T##String?#>,
        leftBtn: <#T##Bool?#>,
        rightBtn: <#T##Bool?#>,
        navigationColor: <#T##String?#>,
        statusBarColor: <#T##String?#>,
        tintColor: <#T##String?#>,
        removeStack: <#T##Bool?#>
    )
    
    /// set configuration
    let vc = MKWebViewController()
    vc.configuration = configure
    self.pushViewController(vc, animated: true)
    



Initial Header

MKWebviewController

  • For Apply Headers when load or reload
open func headers() -> [String: String] {
    return [:]
}

USE CASE

private var headerInfos: [String: String] = [
    "Content-Type": "application/json",
    "app-device-uuid": UUID().uuidString,
    "app-device-os-version": UIDevice.current.systemVersion,
    "app-version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "",
    "access-token": "access-token",
    "refresh-token": "refresh-token-value"
]
----
override func headers() -> [String: String] {
    return self.headerInfos
}




Initial Cookies

MKWebviewController

  • For Apply cookies when load or reload
open func cookies() -> [HTTPCookie] {
    return []
}

USE CASE

override func cookies() -> [HTTPCookie] {
    var cookies: [HTTPCookie] = []
    if let uuidCookie = HTTPCookie(properties: [.domain: "smbh.kr",
                                                .path: "/",
                                                .name: "CID",
                                                .value: "\(UUID().uuidString)",
                                                .secure: "TRUE"]) { cookies.append(uuidCookie) }
    return cookies
}



Remove Cookies

MKWebviewController

  • For Remove All Cookies

USE CASE

WebkitManager.shared.removeCookies {
    //
}

or

MKWebview.shared.clearCookies(completion: nil)



Load url based

MKWebviewController

  • For Static URL Load
open func loadURLString() -> String? {
    return nil
}

USE CASE

override func loadURLString() -> String? {
    return "https://smbh.kr/mk_bridge/sample"
}



Load local html file based

MKWebviewController

  • For Static Local File Load
open func loadLocalFile() -> URL? {
    return nil
}

USE CASE

override func loadLocalFile() -> URL? {
    guard let url = Bundle.main.url(forResource: "sampleScheme", withExtension: "html") else { return nil }
    return url
}



Adding Custom User Scripts

MKWebviewController

  • For Custom Scripts

can handle in addPostMessageHandler(##String##) on onAddPostMessage

open func onAddUserScript() -> String? {
    return nil
}

USE CASE

eg. It can Called window.CustomScripts.showToast('msg';) in JavaScript

//// Add Script

override func onAddUserScript() -> String? {
    return """
        CustomScripts = {
            showToast(s) {
                window.webkit.messageHandlers.showToast.postMessage(s);
            },
        }
    """

/// Handle
override func onAddPostMessage() {
    addPostMessageHandler("showToast") { (res) in
        
        if let res = res as? String {
            Toast.shared.makeToast(res)
        }
    }
}
}



Handle JavaScripts

MKWebviewController

  • For Handle Scripts
open func onAddPostMessage() {
    //
}

USE CASE 1

eg. It can Called window.webkit.messageHandlers.showToast.postMessage('msg';) in JavaScript

override func onAddPostMessage() {
    super.onAddPostMessage()
    addPostMessageHandler("showToast") { (res) in
        // do stuff
        if let res = res as? String {
            Toast.shared.makeToast(res)
        }
    }
}

USE CASE 2

  • It can make return data (iOS 14.0 *) when call Javascript with promise

eg. It can Called window.webkit.messageHandlers.showToast.postMessage('msg';) in JavaScript

///--- javaScript ---
var promise = window.webkit.messageHandlers.testWithPromise.postMessage( inputInfo );
promise.then(
            function(result) {
                console.log(result); // "Stuff worked!"
                successFunc( result )
            },
            function(err) {
                console.log(err); // Error: "It broke"
                errorFunc( err )
            });

///--- override func onAddPostMessage() ---
if #available(iOS 14.0, *) {
    let promiseResult: ReplyHandler = ("Return Data", nil)
    addPostMessageReplyHandler("testWithPromise", handler: promiseResult, result: { result in
        print("Called")
    })
}




Evalutate JavaScripts

MKWebviewController

func evaluateJavascript(_ function: String, result: ((Bool, Any?) -> Void)?)

USE CASE

let value = "javascript:setToken('NEW_ACSESS_TOKEN');"
self.evaluateJavascript(value) { (result, _ ) in
    Debug.print(result)
}



Reload Webview

MKWebviewController

public func reloadWebview()

USE CASE

self.reloadWebview()

GitHub

link
Stars: 0
Last commit: 1 week ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Release Notes

1.0.0 Release
1 year ago

What's Changed

New Contributors

Full Changelog: https://github.com/vincent-k-sm/MKWebviewBridge/commits/1.0.0

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics