-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathExampleApp.swift
More file actions
277 lines (228 loc) · 10 KB
/
Copy pathExampleApp.swift
File metadata and controls
277 lines (228 loc) · 10 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
//
// ExampleApp.swift
// Example
//
// Created by Matheus Gois on 16/12/23.
//
import DebugSwift
import SwiftUI
import UserNotifications
import UIKit
import CoreData
@available(iOS 14.0, *)
@main
struct ExampleApp: App {
@UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
var body: some Scene {
WindowGroup {
ContentView()
.onAppear() {
DebugSwift.PushNotification.enableSimulation()
}
.onOpenURL { url in
print("🔗 [SwiftUI] onOpenURL called with: \(url.absoluteString)")
appDelegate.handleDeepLinkFromSwiftUI(url)
}
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
let debugSwift = DebugSwift()
func application(
_: UIApplication,
didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
// Remove comment below to remove specific features and comment DebugSwift.setup() not to double trigger.
// DebugSwift.setup(hideFeatures: [.interface, .app, .resources, .performance])
// If you have New Relic, disable leak detector to prevent conflicts:
// debugSwift.setup(disable: [.leaksDetector])
print("Hey, DebugSwift is running!")
DiskWriteTracker.install()
debugSwift
.setup(enableBetaFeatures: [.swiftUIRenderTracking, .networkSessionPersistence, .agentDebugLog])
.show()
DebugSwift.Network.configureSessionHistory(retentionDays: 14, batchSize: 1)
// To fix Alamofire `uploadProgress`
// DebugSwift.Network.delegate = self
// MARK: Core Data Example Setup
setupCoreDataExample()
// MARK: SwiftData Example Setup
setupSwiftDataExample()
// MARK: Custom Actions Demo - Including Network History Clear
setupCustomActions()
// Request push notification permissions for APNS token demo
requestPushNotificationPermissions()
return true
}
// MARK: - Core Data Setup
private func setupCoreDataExample() {
CoreDataExample.shared.setupDebugSwift()
let context = CoreDataExample.shared.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
let count = try? context.count(for: fetchRequest)
if count == 0 {
CoreDataExample.shared.createSampleData()
}
}
private func setupSwiftDataExample() {
guard #available(iOS 17.0, *) else { return }
SwiftDataExample.shared.setupDebugSwift()
SwiftDataExample.shared.createSampleDataIfNeeded()
}
// MARK: - Deep Link Handling
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// Handle debugswift:// URLs
if url.scheme == "debugswift" {
handleDeepLink(url)
return true
}
return false
}
func handleDeepLinkFromSwiftUI(_ url: URL) {
handleDeepLink(url)
}
private func handleDeepLink(_ url: URL) {
// Show test view with deep link details
DispatchQueue.main.async {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
return
}
// Find the main app window (not CustomWindow from DebugSwift)
let appWindow = windowScene.windows.first { window in
let isCustomWindow = String(describing: type(of: window)).contains("CustomWindow")
return !isCustomWindow && window.rootViewController != nil
}
guard let window = appWindow else {
return
}
// Get the topmost view controller
guard let topViewController = self.getTopViewController(from: window.rootViewController) else {
return
}
let testView = DeepLinkTestView(url: url)
let hostingController = UIHostingController(rootView: testView)
hostingController.modalPresentationStyle = .fullScreen
topViewController.present(hostingController, animated: true)
}
}
private func getTopViewController(from viewController: UIViewController?) -> UIViewController? {
if let presented = viewController?.presentedViewController {
return getTopViewController(from: presented)
}
if let navigation = viewController as? UINavigationController {
return getTopViewController(from: navigation.visibleViewController)
}
if let tab = viewController as? UITabBarController {
return getTopViewController(from: tab.selectedViewController)
}
return viewController
}
func additionalViewControllers() -> [UIViewController] {
let viewController = UITableViewController()
viewController.title = "PURE"
return [viewController]
}
// MARK: - Custom Actions Setup
private func setupCustomActions() {
DebugSwift.App.shared.customAction = {
[
.init(title: "Environment Management", actions: [
.init(title: "Clear Network History") {
DebugSwift.Network.shared.clearNetworkHistory()
print("✅ Network history cleared!")
},
.init(title: "Clear All Network Data") {
DebugSwift.Network.shared.clearAllNetworkData()
print("✅ All network data cleared!")
},
.init(title: "Switch to Development") {
// Your environment switch logic here
print("🔄 Switching to Development...")
DebugSwift.Network.shared.clearNetworkHistory()
print("✅ Switched to Development & cleared network history")
},
.init(title: "Switch to Production") {
// Your environment switch logic here
print("🔄 Switching to Production...")
DebugSwift.Network.shared.clearNetworkHistory()
print("✅ Switched to Production & cleared network history")
}
]),
.init(title: "Development Tools", actions: [
.init(title: "Clear UserDefaults") {
// Example: Clear specific user data
print("🗑️ UserDefaults cleared")
},
.init(title: "Reset App State") {
print("🔄 App state reset")
}
])
]
}
}
// MARK: - Push Notification Setup
private func requestPushNotificationPermissions() {
Task { @MainActor in
let center = UNUserNotificationCenter.current()
// Inform DebugSwift that we're about to request permissions
DebugSwift.APNSToken.willRequestPermissions()
do {
let granted = try await center.requestAuthorization(options: [.alert, .badge, .sound])
if granted {
// Register for remote notifications
UIApplication.shared.registerForRemoteNotifications()
} else {
// Inform DebugSwift that permissions were denied
DebugSwift.APNSToken.didDenyPermissions()
}
} catch {
print("Failed to request notification permissions: \(error)")
DebugSwift.APNSToken.didFailToRegister(error: error)
}
}
}
}
// MARK: - Push Notification Delegate Methods
extension AppDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Register the device token with DebugSwift for debugging
DebugSwift.APNSToken.didRegister(deviceToken: deviceToken)
// Your existing push notification setup code would go here
// For example, sending the token to your server
let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print("📱 Registered for push notifications with token: \(tokenString)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Register the failure with DebugSwift for debugging
DebugSwift.APNSToken.didFailToRegister(error: error)
// Your existing error handling code would go here
print("❌ Failed to register for push notifications: \(error.localizedDescription)")
}
}
// MARK: - Alamofire bugfix in uploadProgress
extension AppDelegate: @preconcurrency CustomHTTPProtocolDelegate {
func urlSession(
_ protocol: URLProtocol,
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64
) {
// This is a workaround to fix the uploadProgress bug in Alamofire
// It will be removed in the future when Alamofire is fixed
// Please check the Alamofire issue for more details:
// Session.default.session.getAllTasks { tasks in
// let uploadTask = tasks.first(where: { $0.taskIdentifier == task.taskIdentifier }) ?? task
// Session.default.rootQueue.async {
// Session.default.delegate.urlSession(
// session,
// task: uploadTask,
// didSendBodyData: bytesSent,
// totalBytesSent: totalBytesSent,
// totalBytesExpectedToSend: totalBytesExpectedToSend
// )
// }
// }
}
}