ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Swift 외부 브라우저(사파리)로 링크 열기
    Language/iOS,AOS 2024. 7. 10. 15:33

    React + Swift WebView로 개발된 서비스에서 외부 브라우저(사파리)에서 다른서비스를 띄워야 하는 니즈가 발생하였다.

    정리해두자.

     

    JavaScript

    common.js

    class Common {
      ...
      
      static openExternalLink(url) {
        if (Util.Browser.isAndroidApp()) {
          Common.open2(url);
        } else if (Util.Browser.isIosApp()) {
          window.openExternalLinkCallback = (jsonData) => {
            if (jsonData['result'] === false) {
              Common.open2(url);
            }
          };
    
          const message = {
            action: 'openExternalLink',
            params: { url: Util.getFullUrl(url) },
            callback: 'window.openExternalLinkCallback',
          };
          window.webkit.messageHandlers.IosBridge1.postMessage(message);
        } else {
          Common.open2(url);
        }
      }
      
      ...
    }
    
    export default Common;

     

    팝업 호출

    네이티브에서 외부 브라우저로 띄워주는 함수 호출

    Common.openExternalLink('https://naver.com');

     

     

    Swift

    MainViewController

    // MARK: - iOS Bridge
    // 웹 액션 정의 : WebAction을 구분하는데 사용되는 타입
    enum WebAction: String {
        ...
        case openExternalLink
        ...
    }
    extension MainViewController: WKScriptMessageHandler {
        func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            guard message.name == IOS_BRIDGE_NAME,
                  let messageBody = message.body as? [String: Any],
                  let action = messageBody["action"] as? String else { return }
            
            let webAction = WebAction(rawValue: action)
            
            Utils.Log("@@@@@@@@@@@@@@@@@@@@@@@ \(action)")
            
            switch webAction {
            
            ...
            
            case .openExternalLink:
                guard let params: [String: String] = messageBody["params"] as? [String: String],
                      let url: String = params["url"] else {
                    return
                }
                
                Utils.openExternalLink(urlStr: url);
            
            ...
            
        }
    }

     

    Utils

    import Foundation
    import UIKit
    import WebKit
    
    class Utils: NSObject {
        ...
        
        static func openExternalLink(urlStr: String, _ handler:(() -> Void)? = nil) {
            guard let url = URL(string: urlStr) else {
                return
            }
            
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:]) { (result) in
                    handler?()
                }
            } else {
                Utils.Log("Cannot open URL")
            }
        }
        
        ...
    }

     

     

    댓글

Designed by Tistory.