-
Notifications
You must be signed in to change notification settings - Fork 22
/
DebugViewController.swift
540 lines (473 loc) · 17.6 KB
/
DebugViewController.swift
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
//
// File.swift
//
//
// Created by Jake Mor on 8/26/21.
//
// swiftlint:disable force_unwrapping file_length type_body_length function_body_length
import UIKit
import Foundation
import StoreKit
import Combine
var primaryColor = UIColor(hexString: "#75FFF1")
var primaryButtonBackgroundColor = UIColor(hexString: "#203133")
var secondaryButtonBackgroundColor = UIColor(hexString: "#44494F")
var lightBackgroundColor = UIColor(hexString: "#181A1E")
var darkBackgroundColor = UIColor(hexString: "#0D0F12")
struct AlertOption {
var title: String? = ""
var action: (@MainActor () async -> Void)?
var style: UIAlertAction.Style = .default
}
@MainActor
final class DebugViewController: UIViewController {
var logoImageView: UIImageView = {
let superwallLogo = UIImage(named: "SuperwallKit_superwall_logo", in: Bundle.module, compatibleWith: nil)!
let imageView = UIImageView(image: superwallLogo)
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = .clear
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.isHidden = false
return imageView
}()
lazy var exitButton: SWBounceButton = {
let button = SWBounceButton()
let image = UIImage(named: "SuperwallKit_exit", in: Bundle.module, compatibleWith: nil)!
button.setImage(image, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.imageView?.tintColor = UIColor.white.withAlphaComponent(0.5)
button.addTarget(self, action: #selector(pressedExitButton), for: .primaryActionTriggered)
return button
}()
lazy var consoleButton: SWBounceButton = {
let button = SWBounceButton()
let image = UIImage(named: "SuperwallKit_debugger", in: Bundle.module, compatibleWith: nil)!
button.setImage(image, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.imageView?.tintColor = UIColor.white.withAlphaComponent(0.5)
button.addTarget(self, action: #selector(pressedConsoleButton), for: .primaryActionTriggered)
return button
}()
lazy var bottomButton: SWBounceButton = {
let button = SWBounceButton()
button.setTitle("Preview", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
button.backgroundColor = primaryButtonBackgroundColor
button.setTitleColor(primaryColor, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
let image = UIImage(named: "SuperwallKit_play_button", in: Bundle.module, compatibleWith: nil)!
button.titleEdgeInsets = UIEdgeInsets(top: -1, left: 0, bottom: 0, right: 0)
// button.imageEdgeInsets = UIEdgeInsets(top: 1, left: 5, bottom: -1, right: -3)
button.setImage(image, for: .normal)
button.imageView?.tintColor = primaryColor
button.layer.cornerCurve = .continuous
button.layer.cornerRadius = 64.0 / 3
button.addTarget(self, action: #selector(pressedBottomButton), for: .primaryActionTriggered)
return button
}()
lazy var previewPickerButton: SWBounceButton = {
let button = SWBounceButton()
button.setTitle("", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
button.backgroundColor = lightBackgroundColor
button.setTitleColor(primaryColor, for: .normal)
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
button.translatesAutoresizingMaskIntoConstraints = false
button.imageView?.tintColor = primaryColor
button.layer.cornerRadius = 10
let image = UIImage(named: "SuperwallKit_down_arrow", in: Bundle.module, compatibleWith: nil)!
button.semanticContentAttribute = .forceRightToLeft
button.setImage(image, for: .normal)
button.imageView?.tintColor = primaryColor
button.addTarget(self, action: #selector(pressedPreview), for: .primaryActionTriggered)
return button
}()
private let activityIndicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView()
view.hidesWhenStopped = true
view.startAnimating()
view.translatesAutoresizingMaskIntoConstraints = false
view.style = .large
view.color = primaryColor
return view
}()
lazy var previewContainerView: SWBounceButton = {
let button = SWBounceButton()
button.shouldAnimateLightly = true
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(pressedPreview), for: .primaryActionTriggered)
return button
}()
var paywallDatabaseId: String?
var paywallIdentifier: String?
var paywall: Paywall?
var paywalls: [Paywall] = []
var previewViewContent: UIView?
private var cancellable: AnyCancellable?
private var initialLocaleIdentifier: String?
private unowned let storeKitManager: StoreKitManager
private unowned let network: Network
private unowned let paywallRequestManager: PaywallRequestManager
private unowned let paywallManager: PaywallManager
private unowned let debugManager: DebugManager
private let factory: RequestFactory & ViewControllerFactory
init(
storeKitManager: StoreKitManager,
network: Network,
paywallRequestManager: PaywallRequestManager,
paywallManager: PaywallManager,
debugManager: DebugManager,
factory: RequestFactory & ViewControllerFactory
) {
self.storeKitManager = storeKitManager
self.network = network
self.paywallRequestManager = paywallRequestManager
self.paywallManager = paywallManager
self.debugManager = debugManager
self.factory = factory
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
initialLocaleIdentifier = Superwall.shared.options.localeIdentifier
addSubviews()
Task { await loadPreview() }
}
private func addSubviews() {
view.addSubview(previewContainerView)
view.addSubview(activityIndicator)
view.addSubview(logoImageView)
view.addSubview(consoleButton)
view.addSubview(exitButton)
view.addSubview(bottomButton)
previewContainerView.addSubview(previewPickerButton)
view.backgroundColor = lightBackgroundColor
previewContainerView.clipsToBounds = false
NSLayoutConstraint.activate([
previewContainerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
previewContainerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
previewContainerView.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 25),
previewContainerView.bottomAnchor.constraint(equalTo: bottomButton.topAnchor, constant: -30),
logoImageView.widthAnchor.constraint(equalTo: view.layoutMarginsGuide.widthAnchor, constant: -10),
logoImageView.heightAnchor.constraint(equalToConstant: 20),
logoImageView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 20),
logoImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
consoleButton.centerXAnchor.constraint(equalTo: bottomButton.leadingAnchor),
consoleButton.centerYAnchor.constraint(equalTo: logoImageView.centerYAnchor),
exitButton.centerXAnchor.constraint(equalTo: bottomButton.trailingAnchor),
exitButton.centerYAnchor.constraint(equalTo: logoImageView.centerYAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: previewContainerView.centerYAnchor),
activityIndicator.centerXAnchor.constraint(equalTo: previewContainerView.centerXAnchor),
bottomButton.centerXAnchor.constraint(equalTo: view.layoutMarginsGuide.centerXAnchor),
bottomButton.heightAnchor.constraint(equalToConstant: 64),
bottomButton.widthAnchor.constraint(equalTo: view.layoutMarginsGuide.widthAnchor, constant: -40),
bottomButton.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -10),
previewPickerButton.centerXAnchor.constraint(equalTo: previewContainerView.centerXAnchor, constant: 0),
previewPickerButton.heightAnchor.constraint(equalToConstant: 26),
previewPickerButton.centerYAnchor.constraint(equalTo: previewContainerView.bottomAnchor)
])
}
func loadPreview() async {
activityIndicator.startAnimating()
previewViewContent?.removeFromSuperview()
if paywalls.isEmpty {
do {
paywalls = try await network.getPaywalls()
await finishLoadingPreview()
} catch {
Logger.debug(
logLevel: .error,
scope: .debugViewController,
message: "Failed to Fetch Paywalls",
error: error
)
}
} else {
await finishLoadingPreview()
}
}
func finishLoadingPreview() async {
var paywallId: String?
if let paywallIdentifier = paywallIdentifier {
paywallId = paywallIdentifier
} else if let paywallDatabaseId = paywallDatabaseId {
paywallId = paywalls.first(where: { $0.databaseId == paywallDatabaseId })?.identifier
paywallIdentifier = paywallId
} else {
return
}
do {
let request = factory.makePaywallRequest(
eventData: nil,
responseIdentifiers: .init(paywallId: paywallId),
overrides: nil,
isDebuggerLaunched: true,
presentationSourceType: nil,
retryCount: 6
)
var paywall = try await paywallRequestManager.getPaywall(from: request)
let productVariables = await storeKitManager.getProductVariables(for: paywall)
paywall.productVariables = productVariables
self.paywall = paywall
self.previewPickerButton.setTitle("\(paywall.name)", for: .normal)
self.activityIndicator.stopAnimating()
self.addPaywallPreview()
} catch {
Logger.debug(
logLevel: .error,
scope: .debugViewController,
message: "No Paywall Response",
info: nil,
error: error
)
}
}
func addPaywallPreview() {
guard let paywall = paywall else {
return
}
let child = factory.makePaywallViewController(
for: paywall,
withCache: nil,
delegate: nil
)
addChild(child)
previewContainerView.insertSubview(child.view, at: 0)
previewViewContent = child.view
child.didMove(toParent: self)
child.view.translatesAutoresizingMaskIntoConstraints = false
child.view.isUserInteractionEnabled = false
NSLayoutConstraint.activate([
child.view.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0),
child.view.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1.0),
child.view.centerYAnchor.constraint(equalTo: previewContainerView.centerYAnchor),
child.view.centerXAnchor.constraint(equalTo: previewContainerView.centerXAnchor)
])
child.view.clipsToBounds = true
child.view.layer.borderColor = UIColor.white.withAlphaComponent(0.25).cgColor
child.view.layer.borderWidth = 1.0
child.view.layer.cornerRadius = 52
child.view.alpha = 0.0
let ratio = previewContainerView.frame.size.height / view.frame.size.height
child.view.transform = CGAffineTransform.identity.scaledBy(
x: ratio,
y: ratio
)
child.view.layer.cornerCurve = .continuous
UIView.animate(
withDuration: 0.25,
delay: 0.1
) {
child.view.alpha = 1.0
}
}
@objc func pressedPreview() {
guard let id = paywallDatabaseId else { return }
let options: [AlertOption] = paywalls.map { paywall in
var name = paywall.name
if id == paywall.databaseId {
name = "\(name) ✓"
}
let alert = AlertOption(
title: name,
action: { [weak self] in
self?.paywallDatabaseId = paywall.databaseId
self?.paywallIdentifier = paywall.identifier
Task { await self?.loadPreview() }
},
style: .default
)
return alert
}
presentAlert(
title: nil,
message: "Your Paywalls",
options: options,
on: previewPickerButton
)
}
@objc func pressedExitButton() {
Task {
await debugManager.closeDebugger(animated: false)
}
}
@objc func pressedConsoleButton() {
presentAlert(
title: nil,
message: "Menu",
options: [
AlertOption(title: "Localization", action: showLocalizationPicker, style: .default),
AlertOption(title: "Templates", action: showConsole, style: .default)
],
on: consoleButton
)
}
func showLocalizationPicker() async {
let viewController = SWLocalizationViewController { [weak self] identifier in
Superwall.shared.options.localeIdentifier = identifier
Task { await self?.loadPreview() }
}
let navController = UINavigationController(rootViewController: viewController)
await present(navController, animated: true)
}
func showConsole() async {
guard let paywall = paywall else {
Logger.debug(
logLevel: .error,
scope: .debugViewController,
message: "Paywall is nil"
)
return
}
guard let (productsById, _) = try? await storeKitManager.getProducts(
withIds: paywall.productIds,
forPaywall: paywall.name
) else {
return
}
var products: [StoreProduct] = []
for id in paywall.productIds {
if let product = productsById[id] {
products.append(product)
}
}
let viewController = SWConsoleViewController(products: products)
let navController = UINavigationController(rootViewController: viewController)
navController.modalPresentationStyle = .overFullScreen
await present(navController, animated: true)
}
@objc func pressedBottomButton() {
presentAlert(
title: nil,
message: "Which version?",
options: [
AlertOption(
title: "With Free Trial",
action: { [weak self] in
self?.loadAndShowPaywall(freeTrialAvailable: true)
},
style: .default
),
AlertOption(
title: "Without Free Trial",
action: { [weak self] in
self?.loadAndShowPaywall(freeTrialAvailable: false)
},
style: .default
)
],
on: bottomButton
)
}
func loadAndShowPaywall(freeTrialAvailable: Bool = false) {
guard let paywallIdentifier = paywallIdentifier else {
return
}
bottomButton.setImage(nil, for: .normal)
bottomButton.showLoading = true
let inactiveSubscriptionPublisher = CurrentValueSubject<SubscriptionStatus, Never>(SubscriptionStatus.inactive)
.eraseToAnyPublisher()
let presentationRequest = factory.makePresentationRequest(
.fromIdentifier(
paywallIdentifier,
freeTrialOverride: freeTrialAvailable
),
paywallOverrides: nil,
presenter: self,
isDebuggerLaunched: true,
subscriptionStatus: inactiveSubscriptionPublisher,
isPaywallPresented: Superwall.shared.isPaywallPresented,
type: .presentation
)
cancellable = Superwall.shared
.internallyPresent(presentationRequest)
.sink { state in
switch state {
case .presented:
self.bottomButton.showLoading = false
let playButton = UIImage(named: "SuperwallKit_play_button", in: Bundle.module, compatibleWith: nil)!
self.bottomButton.setImage(
playButton,
for: .normal
)
case .skipped(let reason):
var errorMessage: String?
switch reason {
case .holdout:
errorMessage = "The user was assigned to a holdout."
case .noRuleMatch:
errorMessage = "The user didn't match a rule."
case .eventNotFound:
errorMessage = "Couldn't find event."
case .userIsSubscribed:
errorMessage = "The user is subscribed."
}
self.presentAlert(
title: "Paywall Skipped",
message: errorMessage,
on: self.view
)
self.bottomButton.showLoading = false
let playButton = UIImage(named: "SuperwallKit_play_button", in: Bundle.module, compatibleWith: nil)!
self.bottomButton.setImage(playButton, for: .normal)
self.activityIndicator.stopAnimating()
case .dismissed:
break
case .presentationError(let error):
Logger.debug(
logLevel: .error,
scope: .debugViewController,
message: "Failed to Show Paywall",
info: nil
)
self.presentAlert(
title: "Presentation Error",
message: error.safeLocalizedDescription,
on: self.view
)
self.bottomButton.showLoading = false
let playButton = UIImage(named: "SuperwallKit_play_button", in: Bundle.module, compatibleWith: nil)!
self.bottomButton.setImage(playButton, for: .normal)
self.activityIndicator.stopAnimating()
}
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
paywallManager.resetCache()
debugManager.isDebuggerLaunched = false
Superwall.shared.options.localeIdentifier = initialLocaleIdentifier
}
}
extension DebugViewController {
func presentAlert(
title: String?,
message: String?,
options: [AlertOption] = [],
on sourceView: UIView
) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
for option in options {
let action = UIAlertAction(
title: option.title,
style: option.style
) { _ in
Task {
await option.action?()
}
}
alertController.addAction(action)
}
alertController.popoverPresentationController?.sourceView = sourceView
alertController.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil))
alertController.view.tintColor = .black
present(
alertController,
animated: true
)
}
}