CampaignViewController.swift 30.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
//
//  CampaignViewController.swift
//  SwiftWarplyFramework
//
//  Created by Βασιλης Σκουρας on 11/5/22.
//

import Foundation
import UIKit
import WebKit
import SwiftEventBus

// Location Permissions
import CoreLocation


var timer2: DispatchSourceTimer?

//@objc public class CampaignViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {
@objc public class CampaignViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, CLLocationManagerDelegate, WKUIDelegate, UIScrollViewDelegate {
    @IBOutlet weak var webview: WKWebView!
    
    public var campaignUrl: String = ""
    public var params: String = ""
    public var showHeader: Bool = false
    
    // Location Permissions
    var webView: WKWebView!
    var locationManager: CLLocationManager!
    var listenersCount = 0;
    
    public override func loadView() {
        super.loadView();

        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        let contentController = WKUserContentController()
        contentController.add(self, name: "Cosmote")
        contentController.add(self, name: "listenerAdded");
        contentController.add(self, name: "listenerRemoved");

        let config = WKWebViewConfiguration()
        config.userContentController = contentController

        let script = WKUserScript(source: getJavaScripToEvaluate(), injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        contentController.addUserScript(script)

        self.webView = WKWebView(frame: self.view.bounds, configuration: config)

        webView?.uiDelegate = self
        webView?.navigationDelegate = self
        webView?.scrollView.delegate = self
        webView?.scrollView.bounces = false
        webView?.scrollView.bouncesZoom = false
        view.addSubview(webView!)

    }
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        let campaignUrl = campaignUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        print("Webview url: " + (campaignUrl ?? ""))

        if let url = URL(string: campaignUrl ?? "") {
            webView.load(URLRequest(url: url))
            webView.allowsBackForwardNavigationGestures = true
        }

        self.hidesBottomBarWhenPushed = true

        if (showHeader) {
            setBackButton()
        }

    }
   
    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if (!showHeader) {
            // navigationController?.setNavigationBarHidden(true, animated: animated)
            self.navigationController?.isNavigationBarHidden = true
        } else {
            self.navigationController?.hideHairline()
        }
    }

    public override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if (!showHeader) {
            // navigationController?.setNavigationBarHidden(false, animated: animated)
            self.navigationController?.isNavigationBarHidden = false
        }

        stopTimer()

        let persistedSteps = swiftApi().getSteps()
        if (persistedSteps > 0) {

            let currentDateTime = Date()
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let dateString = dateFormatter.string(from: currentDateTime)

            swiftApi().setPacingDetailsAsync(persistedSteps, dateString, setPacingDetailsAsyncCallback, failureCallback: {errorCode in })
        }
        
        func setPacingDetailsAsyncCallback (_ responseData: swiftApi.GenericResponseModel?) -> Void {
            if (responseData != nil) {
                DispatchQueue.main.async {
                    if (responseData?.getStatus == 1) {
                        // print("===== steps sent on back button press ====")
                    }
                }
            } else {
            }
        }
    }
    
//    public override func viewDidLoad() {
//        super.viewDidLoad()
//
//        var campaignUrl = campaignUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
//        print("Webview url: " + (campaignUrl ?? ""))
//
//        self.hidesBottomBarWhenPushed = true
//
//        if (showHeader) {
//            setBackButton()
//        }
//
//        webview.navigationDelegate = self
//
//        if let url = URL(string: campaignUrl ?? "") {
//            webview.load(URLRequest(url: url))
//            webview.allowsBackForwardNavigationGestures = true
//        }
//
//        webview.configuration.userContentController.add(self, name: "Cosmote")
//    }

    // MARK: - Functions
    func startTimer() {
        // print("========= Webview Timer Started! =========")

        let queue = DispatchQueue(label: Bundle.main.bundleIdentifier! + ".webview.timer")
        timer2 = DispatchSource.makeTimerSource(queue: queue)
        timer2!.schedule(deadline: .now(), repeating: .seconds(1))
        timer2!.setEventHandler { [weak self] in
            // do whatever stuff you want on the background queue here here
            // print("========= Webview interval! =========")

            DispatchQueue.main.async {
                // update your model objects and/or UI here
                let metersParam = swiftApi().getMetersWebview()
                let scriptSource = "passMeters(\(metersParam));"
                
                self?.webview.evaluateJavaScript(scriptSource, completionHandler: { (object, error) in
                    // print("==== object ====")
                    // print(object)
                    // print("==== error ====")
                    // print(error)

                    swiftApi().setSavedStepsWebview(swiftApi().getSavedStepsWebview() + swiftApi().getStepsWebview())
                    swiftApi().setStepsWebview(0)
                    swiftApi().setMetersWebview(0.0)

                    // print("==== SavedStepsWebview ====")
                    // print(swiftApi().getSavedStepsWebview())
                })
            }
        }
        timer2!.resume()
    }

    func stopTimer() {
        // print("========= Webview Timer Stopped! =========")
        timer2?.cancel()
        timer2 = nil
    }
    
    // Location Permissions
    func locationServicesIsEnabled() -> Bool {
        return (CLLocationManager.locationServicesEnabled()) ? true : false;
    }

    func authorizationStatusNeedRequest(status: CLAuthorizationStatus) -> Bool {
        return (status == .notDetermined) ? true : false;
    }

    func authorizationStatusIsGranted(status: CLAuthorizationStatus) -> Bool {
        return (status == .authorizedAlways || status == .authorizedWhenInUse) ? true : false;
    }

    func authorizationStatusIsDenied(status: CLAuthorizationStatus) -> Bool {
        return (status == .restricted || status == .denied) ? true : false;
    }

    func onLocationServicesIsDisabled() {
//        webView.evaluateJavaScript("navigator.geolocation.helper.error(2, 'Location services disabled');");
        locationManager.requestWhenInUseAuthorization();
    }

    func onAuthorizationStatusNeedRequest() {
        locationManager.requestWhenInUseAuthorization();
    }

    func onAuthorizationStatusIsGranted() {
        locationManager.startUpdatingLocation();
    }

    func onAuthorizationStatusIsDenied() {
        webView.evaluateJavaScript("navigator.geolocation.helper.error(1, 'App does not have location permission');");
    }

    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        print("=== locationManager didChangeAuthorization: ",status)

        // didChangeAuthorization is also called at app startup, so this condition checks listeners
        // count before doing anything otherwise app will start location service without reason
        if (listenersCount > 0) {
            if (authorizationStatusIsDenied(status: status)) {
                onAuthorizationStatusIsDenied();
            }
            else if (authorizationStatusIsGranted(status: status)) {
                onAuthorizationStatusIsGranted();
            }
        }
    }

    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            print("=== locationManager didUpdateLocations latitude: ",location.coordinate.latitude)
            print("=== locationManager didUpdateLocations longitude: ",location.coordinate.longitude)
            
            webView.evaluateJavaScript("navigator.geolocation.helper.success('\(location.timestamp)', \(location.coordinate.latitude), \(location.coordinate.longitude), \(location.altitude), \(location.horizontalAccuracy), \(location.verticalAccuracy), \(location.course), \(location.speed));");
        }
    }

    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("=== locationManager didFailWithError: ", error)
        webView.evaluateJavaScript("navigator.geolocation.helper.error(2, 'Failed to get position (\(error.localizedDescription))');");
    }

    func getJavaScripToEvaluate() -> String {
        let javaScripToEvaluate = """
            // management for success and error listeners and its calling
            navigator.geolocation.helper = {
                listeners: {},
                noop: function() {},
                id: function() {
                    var min = 1, max = 1000;
                    return Math.floor(Math.random() * (max - min + 1)) + min;
                },
                clear: function(isError) {
                    for (var id in this.listeners) {
                        if (isError || this.listeners[id].onetime) {
                            navigator.geolocation.clearWatch(id);
                        }
                    }
                },
                success: function(timestamp, latitude, longitude, altitude, accuracy, altitudeAccuracy, heading, speed) {
                    var position = {
                        timestamp: new Date(timestamp).getTime() || new Date().getTime(), // safari can not parse date format returned by swift e.g. 2019-12-27 15:46:59 +0000 (fallback used because we trust that safari will learn it in future because chrome knows that format)
                        coords: {
                            latitude: latitude,
                            longitude: longitude,
                            altitude: altitude,
                            accuracy: accuracy,
                            altitudeAccuracy: altitudeAccuracy,
                            heading: (heading > 0) ? heading : null,
                            speed: (speed > 0) ? speed : null
                        }
                    };
                    for (var id in this.listeners) {
                        this.listeners[id].success(position);
                    }
                    this.clear(false);
                },
                error: function(code, message) {
                    var error = {
                        PERMISSION_DENIED: 1,
                        POSITION_UNAVAILABLE: 2,
                        TIMEOUT: 3,
                        code: code,
                        message: message
                    };
                    for (var id in this.listeners) {
                        this.listeners[id].error(error);
                    }
                    this.clear(true);
                }
            };

            // @override getCurrentPosition()
            navigator.geolocation.getCurrentPosition = function(success, error, options) {
                var id = this.helper.id();
                this.helper.listeners[id] = { onetime: true, success: success || this.noop, error: error || this.noop };
                window.webkit.messageHandlers.listenerAdded.postMessage("");
            };

            // @override watchPosition()
            navigator.geolocation.watchPosition = function(success, error, options) {
                var id = this.helper.id();
                this.helper.listeners[id] = { onetime: false, success: success || this.noop, error: error || this.noop };
                window.webkit.messageHandlers.listenerAdded.postMessage("");
                return id;
            };

            // @override clearWatch()
            navigator.geolocation.clearWatch = function(id) {
                var idExists = (this.helper.listeners[id]) ? true : false;
                if (idExists) {
                    this.helper.listeners[id] = null;
                    delete this.helper.listeners[id];
                    window.webkit.messageHandlers.listenerRemoved.postMessage("");
                }
            };
        """;

        return javaScripToEvaluate;
    }
    // <===

    // MARK: - API Calls
    func startTrackingSteps() {
        swiftApi().startTrackingSteps(startTrackingStepsCallback)
    }
    
    func startTrackingStepsCallback (_ steps: Int) -> Void {
        DispatchQueue.main.async {
        }
    }

    // MARK: - WKNavigationDelegate
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        let scriptSource = "passParams(\(params));"
        
        webView.evaluateJavaScript(scriptSource, completionHandler: { (object, error) in
            // print("==== object ====")
            // print(object)
            // print("==== error ====")
            // print(error)

            DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
                self.startTimer()
            }
        })
        
    }
    
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            
//      if(navigationAction.navigationType == .linkActivated) {
        
        if let redirectedUrl = navigationAction.request.url {
            // Example Deeplink: https://cosmote.page.link/loyaltyWallet
            // Example Deeplink: https://preview.page.link/cosmote.page.link/loyaltyWallet
            // Example Deeplink: https://apps.apple.com/app/id482889196?mt=8
            
            if redirectedUrl.absoluteString.contains("cosmote.page.link") {
            
                // check if link can be opened.
                guard UIApplication.shared.canOpenURL(redirectedUrl) else {
                    decisionHandler(.cancel)
                    return
                }

                UIApplication.shared.open(redirectedUrl, options: [:], completionHandler: nil)
                
                decisionHandler(.cancel)
                return
            }
        }
        
//      }
    
        decisionHandler(.allow)
    }
    
    // MARK: - WKScriptMessageHandler
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        // Location Permissions
        if (message.name == "listenerAdded") {
            listenersCount += 1;

            if (!locationServicesIsEnabled()) {
                onLocationServicesIsDisabled();
            }
            else if (authorizationStatusIsDenied(status: CLLocationManager.authorizationStatus())) {
                onAuthorizationStatusIsDenied();
            }
            else if (authorizationStatusNeedRequest(status: CLLocationManager.authorizationStatus())) {
                onAuthorizationStatusNeedRequest();
            }
            else if (authorizationStatusIsGranted(status: CLLocationManager.authorizationStatus())) {
                onAuthorizationStatusIsGranted();
            }
        }
        else if (message.name == "listenerRemoved") {
            listenersCount -= 1;

            // no listener left in web view to wait for position
            if (listenersCount == 0) {
                locationManager.stopUpdatingLocation();
            }
        }
        // <==
        else if (message.name == "Cosmote") {
            if let event = message.body as? String {
                let eventArray = event.split(separator: ":")
                
                if (eventArray[0] == "event") {
                    if (eventArray[1] == "closeArtwork") {
                        
                        self.navigationController?.popViewController(animated: true)
                        
                    } else if (eventArray[1] == "addUserTag") {
                        // SwiftEventBus.post("questionnaire", sender: questionnaireEvent)
                        
                        swiftApi().getProfileAsync(getProfileCallback, failureCallback: {errorCode in })
                        
                        func getProfileCallback (_ profileData: swiftApi.ProfileModel?) -> Void {
                            if (profileData != nil) {
                                DispatchQueue.main.async {
                                    swiftApi().getCampaignsAsyncNew(language: "en", filters: [String : Any](), getCampaignsCallback, failureCallback: {errorCode in })
                                    
                                    func getCampaignsCallback (_ campaignsData: Array<swiftApi.CampaignItemModel>?) -> Void {
                                        if (campaignsData != nil) {
                                            DispatchQueue.main.async {
                                                let questionnaireEvent = swiftApi.QuestionnaireEventModel()
                                                questionnaireEvent._name = String(eventArray[1])
                                                if (eventArray.count > 2) {
                                                    questionnaireEvent._parameter = String(eventArray[2])
                                                    swiftApi().setUserTag(String(eventArray[2]))
                                                } else {
                                                    questionnaireEvent._parameter = ""
                                                    swiftApi().setUserTag("")
                                                }
                                                SwiftEventBus.post("questionnaire", sender: questionnaireEvent)
                                                SwiftEventBus.post("campaigns_retrieved")
                                            }
                                        } else {
                                        }
                                    }
                                    
                                }
                            } else {
                            }
                        }
                        
                        
                    } else if (eventArray[1] == "couponRetrieved") {
                        let couponEvent = swiftApi.CouponEventModel()
                        SwiftEventBus.post("coupon_retrieved", sender: couponEvent)
                        
                        swiftApi().getCouponsAsync(getCouponsCallback, failureCallback: {errorCode in })
                        swiftApi().getCampaignsAsyncNew(language: "en", filters: [String : Any](), getCampaignsCallback, failureCallback: {errorCode in })
                        
                        func getCouponsCallback (_ couponsData: Array<swiftApi.CouponItemModel>?) -> Void {
                            if (couponsData != nil) {
                                
                                DispatchQueue.main.async {
                                    SwiftEventBus.post("coupons_fetched")
                                }
                            } else {
                            }
                        }
                        
                        func getCampaignsCallback (_ campaignsData: Array<swiftApi.CampaignItemModel>?) -> Void {
                            if (campaignsData != nil) {
                                DispatchQueue.main.async {
                                    SwiftEventBus.post("campaigns_retrieved")
                                }
                            } else {
                            }
                        }
                        
                    } else if (eventArray[1] == "ccmsRetrieved") {
                        let ccmsEnabled = swiftApi.WarplyCCMSEnabledModel()
                        ccmsEnabled._isActivated = true
                        SwiftEventBus.post("ccms_enabled", sender: ccmsEnabled)
                        
                    } else if (eventArray[1] == "couponShared") {
                        
                    }
                    else if (eventArray[1] == "steps" && eventArray[2] == "widgetDisabled") {
                        let pacingWidget = swiftApi.WarplyPacingCardEventModel()
                        pacingWidget._isVisible = false
                        SwiftEventBus.post("pacing_widget", sender: pacingWidget)
                        
                    } else if (eventArray[1] == "steps" && eventArray[2] == "widgetEnabled") {
                        let pacingWidget = swiftApi.WarplyPacingCardEventModel()
                        pacingWidget._isVisible = true
                        SwiftEventBus.post("pacing_widget", sender: pacingWidget)
                        
                    }
                    else if (eventArray[1] == "steps" && eventArray[2] == "shortcutEnabled") {
                        let pacingEvent = swiftApi.WarplyPacingEventModel()
                        pacingEvent._isVisible = true
                        SwiftEventBus.post("pacing", sender: pacingEvent)
                        
                        if (swiftApi().getTrackingStepsEnabled() == false) {
                            let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                            firebaseEvent._eventName = "loyalty_steps_activation"
                            firebaseEvent._parameters = nil
                            SwiftEventBus.post("firebase", sender: firebaseEvent)
                            
                            self.startTrackingSteps()
                        }
                        
                    } else if (eventArray[1] == "steps" && eventArray[2] == "shortcutDisabled") {
                        let pacingEvent = swiftApi.WarplyPacingEventModel()
                        pacingEvent._isVisible = false
                        SwiftEventBus.post("pacing", sender: pacingEvent)
                        swiftApi().stopTrackingSteps()
                        
                    } else if (eventArray[1] == "request" || eventArray[1] == "response") {
                        print("**************** WARPLY Webview Log START *****************")
                        print(event)
                        print("**************** WARPLY Webview Log END *****************")
                        
                    } else if (eventArray[1] == "loyalty_questionnaire_selected") {
                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "loyalty_questionnaire_selected"
                        firebaseEvent.setParameter = ("completed", "true")
                        SwiftEventBus.post("firebase", sender: firebaseEvent)
                        
                    } else if (eventArray[1] == "loyalty_questionnaire_answer_again") {
                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "loyalty_questionnaire_answer_again"
                        firebaseEvent._parameters = nil
                        SwiftEventBus.post("firebase", sender: firebaseEvent)
                        
                    } else if (eventArray[1] == "loyalty_questionnaire_answers_deleted") {
                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "loyalty_questionnaire_answers_deleted"
                        firebaseEvent._parameters = nil
                        SwiftEventBus.post("firebase", sender: firebaseEvent)
                        
                    } else if (eventArray[1] == "loyalty_questionnaire_later") {
                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "loyalty_questionnaire_later"
                        firebaseEvent.setParameter = ("completed", "false")
                        SwiftEventBus.post("firebase", sender: firebaseEvent)
                        
                    } else if (eventArray[1] == "loyalty_sdk_offer_selected") {
                        var name: String = ""
                        if (eventArray.count > 2) {
                            name = String(eventArray[2])
                        } else {
                            name = ""
                        }
                        
                        var type: String = ""
                        if (eventArray.count > 3) {
                            type = String(eventArray[3])
                        } else {
                            type = ""
                        }
                        
                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "loyalty_sdk_offer_selected"
                        firebaseEvent.setParameter = ("name", name)
                        firebaseEvent.setParameter = ("type", type)
                        SwiftEventBus.post("firebase", sender: firebaseEvent)
                        
                    } else if (eventArray[1] == "loyalty_offer_activated") {
                        var name: String = ""
                        if (eventArray.count > 2) {
                            name = String(eventArray[2])
                        } else {
                            name = ""
                        }
                        
                        var type: String = ""
                        if (eventArray.count > 3) {
                            type = String(eventArray[3])
                        } else {
                            type = ""
                        }
                        
                        var successful: String = ""
                        if (eventArray.count > 4) {
                            successful = String(eventArray[4])
                        } else {
                            successful = ""
                        }
                        
                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "loyalty_offer_activated"
                        firebaseEvent.setParameter = ("name", name)
                        firebaseEvent.setParameter = ("type", type)
                        firebaseEvent.setParameter = ("successful", successful)
                        SwiftEventBus.post("firebase", sender: firebaseEvent)
                        
                    } else if (eventArray[1] == "unified_coupon_activated") {
                        SwiftEventBus.post("unified_coupon_activated")
                        
                        var name: String = ""
                        if (eventArray.count > 2) {
                            name = String(eventArray[2])
                        } else {
                            name = ""
                        }
                        
                        var type: String = ""
                        if (eventArray.count > 3) {
                            type = String(eventArray[3])
                        } else {
                            type = ""
                        }
                        
                        var successful: String = ""
                        if (eventArray.count > 4) {
                            successful = String(eventArray[4])
                        } else {
                            successful = ""
                        }
                        
                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "unified_coupon_activated"
                        firebaseEvent.setParameter = ("name", name)
                        firebaseEvent.setParameter = ("type", type)
                        firebaseEvent.setParameter = ("successful", successful)
                        SwiftEventBus.post("firebase", sender: firebaseEvent)
                        
                    } else if (eventArray[1] == "time_spent_on_loyalty_sdk") {
                        var name: String = ""
                        if (eventArray.count > 2) {
                            name = String(eventArray[2])
                        } else {
                            name = ""
                        }
                        
                        var seconds: String = ""
                        if (eventArray.count > 3) {
                            seconds = String(eventArray[3])
                        } else {
                            seconds = ""
                        }
                        
                        let firebaseEvent = swiftApi.LoyaltySDKFirebaseEventModel()
                        firebaseEvent._eventName = "time_spent_on_loyalty_sdk"
                        firebaseEvent.setParameter = ("name", name)
                        firebaseEvent.setParameter = ("seconds", seconds)
                        SwiftEventBus.post("firebase", sender: firebaseEvent)
                        
                    } else if (eventArray[1] == "refreshToken") {
                        var access_token: String = ""
                        if (eventArray.count > 2) {
                            access_token = String(eventArray[2])
                        } else {
                            access_token = ""
                        }
                        
                        var refresh_token: String = ""
                        if (eventArray.count > 3) {
                            refresh_token = String(eventArray[3])
                        } else {
                            refresh_token = ""
                        }
                        
                        if (access_token != "" && refresh_token != "") {
                            swiftApi().updateRefreshToken(access_token: access_token, refresh_token: refresh_token)
                        }
                        
                    } else if (eventArray[1] == "loyaltyWallet") {
                        // event:loyaltyWallet
                        let storyboard = UIStoryboard(name: "Main", bundle: Bundle(for: MyEmptyClass.self))
                        let vc = storyboard.instantiateViewController(withIdentifier: "WalletViewController") as! SwiftWarplyFramework.WalletViewController
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                    
                }
            }
        }
    }

}