Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add preload banner to sample app #48

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
4EF54F242A6F456B00F5E407 /* CartManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EF54F232A6F456B00F5E407 /* CartManager.swift */; };
4EF54F272A6F4C4F00F5E407 /* CartViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EF54F262A6F4C4F00F5E407 /* CartViewController.swift */; };
4EF54F312A6F63C000F5E407 /* CartViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 4EF54F2F2A6F63C000F5E407 /* CartViewController.xib */; };
6A8D64D22AF2A10600FE4E4A /* ShopifyCheckout in Frameworks */ = {isa = PBXBuildFile; productRef = 6A8D64D12AF2A10600FE4E4A /* ShopifyCheckout */; };
6A8D64D42AF5635000FE4E4A /* PreloadBanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A8D64D32AF5635000FE4E4A /* PreloadBanner.swift */; };
86250DE42AD5521C002E45C2 /* AppConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86250DE32AD5521C002E45C2 /* AppConfiguration.swift */; };
/* End PBXBuildFile section */

Expand All @@ -43,6 +45,7 @@
4EF54F232A6F456B00F5E407 /* CartManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CartManager.swift; sourceTree = "<group>"; };
4EF54F262A6F4C4F00F5E407 /* CartViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CartViewController.swift; sourceTree = "<group>"; };
4EF54F2F2A6F63C000F5E407 /* CartViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = CartViewController.xib; sourceTree = "<group>"; };
6A8D64D32AF5635000FE4E4A /* PreloadBanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PreloadBanner.swift; sourceTree = "<group>"; };
86250DE32AD5521C002E45C2 /* AppConfiguration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppConfiguration.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

Expand Down Expand Up @@ -111,6 +114,7 @@
4EF54F262A6F4C4F00F5E407 /* CartViewController.swift */,
4EF54F2F2A6F63C000F5E407 /* CartViewController.xib */,
4EA7F9B42A9D2B9D003276A1 /* SettingsViewController.swift */,
6A8D64D32AF5635000FE4E4A /* PreloadBanner.swift */,
);
name = Application;
sourceTree = "<group>";
Expand Down Expand Up @@ -246,6 +250,7 @@
4EF54F242A6F456B00F5E407 /* CartManager.swift in Sources */,
4EBBA76F2A5F0CE200193E19 /* ProductViewController.swift in Sources */,
4EF54F272A6F4C4F00F5E407 /* CartViewController.swift in Sources */,
6A8D64D42AF5635000FE4E4A /* PreloadBanner.swift in Sources */,
4EBBA76B2A5F0CE200193E19 /* AppDelegate.swift in Sources */,
86250DE42AD5521C002E45C2 /* AppConfiguration.swift in Sources */,
4EBBA7AA2A5F124F00193E19 /* StorefrontClient.swift in Sources */,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
MIT License

Copyright 2023 - Present, Shopify Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import UIKit

class PreloadBanner {
static let shared = PreloadBanner()
private let bannerView: UIView
private let label: UILabel
private let height: CGFloat = 30
private let yVisible: CGFloat = UIScreen.main.bounds.height - 113
private let yHidden: CGFloat = UIScreen.main.bounds.height - 108

private init() {
bannerView = UIView(
frame: CGRect(
x: 0,
y: yHidden,
width: UIScreen.main.bounds.width,
height: height
)
)
bannerView.backgroundColor = .systemGreen
bannerView.isHidden = true
bannerView.alpha = 0

label = UILabel(frame: bannerView.bounds)
label.textAlignment = .center
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 14)

bannerView.addSubview(label)

let firstConnectedScene = UIApplication.shared.connectedScenes.first

if let windowScene = firstConnectedScene as? UIWindowScene, let window = windowScene.windows.first {
window.addSubview(bannerView)
}
}

func showBanner(withText text: String) {
label.text = text

UIView.animate(withDuration: 0.3) {
self.bannerView.frame.origin.y = self.yVisible
self.bannerView.alpha = 1
self.bannerView.isHidden = false
}

// Schedule a timer to hide the banner after 3 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.hideBanner()
}
}

func hideBanner() {
UIView.animate(withDuration: 0.3, animations: {
self.bannerView.frame.origin.y = self.yHidden
self.bannerView.alpha = 0
}, completion: {(_ completed) in
self.bannerView.isHidden = true
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ import Buy
import UIKit
import ShopifyCheckout

class ProductViewController: UIViewController {

class ProductViewController: UIViewController, CheckoutEventListener {
// MARK: Properties

@IBOutlet private var image: UIImageView!
Expand Down Expand Up @@ -55,6 +54,12 @@ class ProductViewController: UIViewController {
title = "Browse"

tabBarItem.image = UIImage(systemName: "books.vertical")

ShopifyCheckout.events.addEventListener(self, for: .load)
}

deinit {
ShopifyCheckout.events.removeEventListener(self, for: .load)
}

// MARK: UIViewController Lifecycle
Expand All @@ -74,6 +79,15 @@ class ProductViewController: UIViewController {
reloadProduct()
}

func handleCheckoutEvent(_ event: CheckoutEvent, message: String? = nil) {
switch event {
case .load:
if ShopifyCheckout.configuration.preloading.enabled {
PreloadBanner.shared.showBanner(withText: "\(message ?? "")")
}
}
}

// MARK: Actions

@IBAction func addToCart() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {

var window: UIWindow?

var preloadBanner: PreloadBanner?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }

Expand All @@ -47,6 +49,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
window.rootViewController = tabBarController
window.makeKeyAndVisible()

preloadBanner = PreloadBanner.shared

self.window = window
}
}
34 changes: 25 additions & 9 deletions Sources/ShopifyCheckout/CheckoutView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ extension CheckoutView: WKScriptMessageHandler {
}
}

private var timer: Date?

extension CheckoutView: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

Expand Down Expand Up @@ -161,18 +163,32 @@ extension CheckoutView: WKNavigationDelegate {
return .allow
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
viewDelegate?.checkoutViewDidStartNavigation()
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
timer = Date()
viewDelegate?.checkoutViewDidStartNavigation()
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
viewDelegate?.checkoutViewDidFinishNavigation()
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
timer = nil
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
CheckoutView.cache = nil
viewDelegate?.checkoutViewDidFailWithError(error: .sdkError(underlying: error))
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
viewDelegate?.checkoutViewDidFinishNavigation()

if let startTime = timer {
let endTime = Date()
let diff = endTime.timeIntervalSince(startTime)
ShopifyCheckout.events.triggerEvent(.load, message: "Preloaded checkout in \(String(format: "%.2f", diff))s")
}

timer = nil
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
timer = nil
CheckoutView.cache = nil
viewDelegate?.checkoutViewDidFailWithError(error: .sdkError(underlying: error))
}

private func isExternalLink(_ action: WKNavigationAction) -> Bool {
if action.navigationType == .linkActivated && action.targetFrame == nil { return true }
Expand Down
34 changes: 34 additions & 0 deletions Sources/ShopifyCheckout/ShopifyCheckout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,37 @@ public func present(checkout url: URL, from: UIViewController, delegate: Checkou
viewController.presentationController?.delegate = rootViewController
from.present(viewController, animated: true)
}

public enum CheckoutEvent: Hashable {
case load
}

public protocol CheckoutEventListener: AnyObject {
func handleCheckoutEvent(_ event: CheckoutEvent, message: String?)
}

public var events = Events()

public struct Events {
private var eventListeners = [CheckoutEvent: [CheckoutEventListener]]()

public mutating func addEventListener(_ listener: CheckoutEventListener, for event: CheckoutEvent) {
if eventListeners[event] == nil {
eventListeners[event] = [CheckoutEventListener]()
}
eventListeners[event]?.append(listener)
}

public mutating func removeEventListener(_ listener: CheckoutEventListener, for event: CheckoutEvent) {
eventListeners[event]?.removeAll { $0 === listener }
}

func triggerEvent(_ event: CheckoutEvent, message: String?) {
guard let listeners = eventListeners[event] else {
return
}
for listener in listeners {
listener.handleCheckoutEvent(event, message: message)
}
}
}