AppDelegate.swift
7.77 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
//
// AppDelegate.swift
// Runner
//
// Created by 权海 on 2026/6/11.
//
import Foundation
import UIKit
import Flutter
import UserNotifications
import AppTrackingTransparency
import AdSupport
typealias FlutterBridgeMethod = ((_ params: Any?, _ result: FlutterResult) -> Void)
@Observable
class AppDelegate: NSObject, UIApplicationDelegate {
var window: UIWindow?
private(set) var enginInitError: String?
enum FlutterBridgeMethodName: String{
case handleFlutterUrl
}
private var methods: [String: FlutterBridgeMethod] = [:]
var flutterEngine: FlutterEngine?
var channel: FlutterMethodChannel?
private var isFlutterEngineReady = false
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
setup()
cacheLaunchURLIfNeeded(launchOptions)
return true
}
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
handleFlutterUrl(url.absoluteString)
return true
}
func application(
_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
) -> Bool {
guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let urlString = userActivity.webpageURL?.absoluteString else {
return false
}
handleFlutterUrl(urlString)
return true
}
func setup(){
AppShared.shared.agent.genUA()
AppShared.shared.payment.delegate = self
_ = AppShared.shared.payment.listenForTransactions()
UIApplication.shared.registerForRemoteNotifications()
UNUserNotificationCenter.current().setBadgeCount(0)
UNUserNotificationCenter.current().delegate = self
requestIDFAAuthorization()
WatchConnectivityService.shared.activate()
HealthKitService.shared.startBackgroundObserversIfNeeded()
}
func warmUpFlutterEngineIfNeeded() {
guard !isFlutterEngineReady else {
enginInitError = nil
return
}
flutterEngine = FlutterEngine(name: "main_flutter_engine")
guard let flutterEngine else{
enginInitError = "engin 初始化失败"
return
}
isFlutterEngineReady = true
flutterEngine.run()
GeneratedPluginRegistrant.register(with: flutterEngine)
NativePigeonRegistrar.register(binaryMessenger: flutterEngine.binaryMessenger)
channel = FlutterMethodChannel(name: "doublefeel_flutter_main_channel", binaryMessenger: flutterEngine.binaryMessenger)
methods = defaultMethods()
enginInitError = nil
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
AppGroupConstants.defaults?.set(token, forKey: AppGroupConstants.Key.appDeviceToken)
Task{
await AppShared.shared.reportDeviceInfo()
}
}
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("❌ Failed to register: \(error.localizedDescription)")
}
}
extension AppDelegate{
private func defaultMethods() -> [String: FlutterBridgeMethod]{
var methods: [String: FlutterBridgeMethod] = [:]
methods[FlutterBridgeMethodName.handleFlutterUrl.rawValue] = { params, result in
result(params)
}
return methods
}
func invoke(method: FlutterBridgeMethodName, arguments: Any?, result: @escaping FlutterResult){
channel?.invokeMethod(method.rawValue, arguments: arguments, result: result)
}
private func cacheLaunchURLIfNeeded(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
if let url = launchOptions?[.url] as? URL {
AppShared.shared.unhandedUrl = url.absoluteString
return
}
if let userActivityDictionary = launchOptions?[.userActivityDictionary] as? [AnyHashable: Any] {
for value in userActivityDictionary.values {
guard let userActivity = value as? NSUserActivity,
userActivity.activityType == NSUserActivityTypeBrowsingWeb,
let urlString = userActivity.webpageURL?.absoluteString else {
continue
}
AppShared.shared.unhandedUrl = urlString
return
}
}
if let userInfo = launchOptions?[.remoteNotification] as? [AnyHashable: Any],
let urlString = Self.flutterURLString(from: userInfo) {
AppShared.shared.unhandedUrl = urlString
}
}
func handleFlutterUrl(_ urlString: String) {
guard !urlString.isEmpty else {
return
}
guard channel != nil else {
AppShared.shared.unhandedUrl = urlString
return
}
invoke(method: .handleFlutterUrl, arguments: [
"url": urlString
]) { result in
if let error = result as? FlutterError {
DebugLogger.log(desc: "handleFlutterUrl error: \(error.message ?? error.code)")
}
}
}
private static func flutterURLString(from userInfo: [AnyHashable: Any]) -> String? {
if let urlString = userInfo["url"] as? String {
return urlString
}
guard let payload = userInfo["payload"] as? String,
let data = payload.data(using: .utf8),
let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
return nil
}
return dict["url"] as? String
}
}
extension AppDelegate: UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound, .badge])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// 从通知中获取 URL
if let urlString = Self.flutterURLString(from: userInfo) {
handleFlutterUrl(urlString)
}
completionHandler()
}
}
extension AppDelegate {
private func requestIDFAAuthorization() {
if ATTrackingManager.trackingAuthorizationStatus == .notDetermined {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
ATTrackingManager.requestTrackingAuthorization { status in
switch status {
case .authorized:
let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
print("✅ IDFA: \(idfa)")
case .denied:
print("❌ 用户拒绝了IDFA授权")
case .restricted:
print("⚠️ IDFA受限制,无法获取")
case .notDetermined:
print("⏳ 用户尚未做出选择")
@unknown default:
print("未知的IDFA授权状态")
}
// ReyunUtil.initSDK()
}
}
} else {
// ReyunUtil.initSDK()
}
}
}