iOS SDK - 고급 옵션


하이브리드 앱을 위한 자바Script 인터페이스

개요

자바Script 인터페이스를 사용하여 WKWebView 기반 하이브리드 앱의 JavaScript 코드에서 Singular SDK 기능을 활성화하세요.

지원되는 메서드:

  • setCustomUserId: 커스텀 사용자 식별자 설정
  • unsetCustomUserId: 커스텀 사용자 식별자 제거
  • event: 속성 유무와 관계없이 이벤트 추적
  • revenue: 구매 추적

WKWebView 연동 설정

뷰 컨트롤러의 WKNavigationDelegate에서 자바Script 인터페이스를 구성하여 JavaScript에서 Singular SDK 메서드를 사용할 수 있도록 하세요.

참고: iOS 8.0 이상부터 Apple은 앱에 웹 콘텐츠를 추가할 때 WKWebView 를 사용할 것을 권장합니다. UIWebView 또는 WebView 는 사용하지 마세요. 자세한 내용은 Apple의 WKWebView 문서 를 참조하세요.

Swift Objective-C
import UIKit
import WebKit

class ViewController: UIViewController {

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create WKWebView
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        view.addSubview(webView)

        // Load web content
        if let url = Bundle.main.url(forResource: "index", withExtension: "html") {
            webView.loadFileURL(url, allowingReadAccessTo: url)
        }
    }
}

extension ViewController: WKNavigationDelegate {

    func webView(_ webView: WKWebView,
                decidePolicyFor navigationAction: WKNavigationAction,
                decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        // Check if Singular JavaScript interface exists
        let js = "typeof(Singular)"
        webView.evaluateJavaScript(js) { (result, error) -> Void in
            if let resultString = result as? String {
                if resultString == "undefined" {
                    // Load Singular JavaScript interface
                    do {
                        if let path = Bundle.main.path(forResource: "Singular", ofType: "js") {
                            let contents = try String(contentsOfFile: path)
                            webView.evaluateJavaScript(contents, completionHandler: nil)
                        }
                    } catch {
                        print("Error loading Singular.js: \(error)")
                    }
                } else {
                    // Process Singular SDK request
                    Singular.processJSRequestWK(webView, withURL: navigationAction.request)
                }
            }
        }

        // Allow navigation
        decisionHandler(.allow)
    }
}

설정 요구 사항:

  • 앱 번들에 Singular.js 파일을 포함하세요
  • 뷰 컨트롤러를 WKWebView의 내비게이션 델리게이트로 설정하세요
  • decidePolicyForNavigationAction 델리게이트 메서드를 구현하세요
  • Singular SDK 요청을 처리하려면 processJSRequestWK 를 호출하세요

JavaScript 사용

WKWebView에서 실행되는 JavaScript 코드에서 Singular 메서드를 호출하세요.

이벤트 추적

JavaScript
// Simple event without attributes
Singular.event('level_completed');

// Event with attributes (pass as JSON string)
Singular.event('purchase_attempt',
    JSON.stringify({
        "item_name": "sword",
        "item_category": "weapons",
        "item_price": 9.99
    })
);

구매 추적

JavaScript
// Track revenue in USD
Singular.revenue('USD', 9.99);

// Track revenue in other currencies
Singular.revenue('EUR', 8.50);

커스텀 사용자 ID 관리

JavaScript
// Set custom user ID
Singular.setCustomUserId('user_12345');

// Remove custom user ID
Singular.unsetCustomUserId();

JavaScript API 참고 사항:

  • 모든 메서드는 글로벌 Singular 객체에서 호출됩니다
  • 이벤트 속성은 JSON 문자열화된 객체로 전달해야 합니다
  • 메서드 이름은 camelCase를 사용합니다 (예: setCustomUserId )
  • 인터페이스는 JavaScript 호출을 네이티브 SDK 메서드로 자동으로 연결합니다