PlatformHostApiImpl.swift
23.8 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
import Foundation
import AuthenticationServices
import StoreKit
import UIKit
import WebKit
import GoogleSignIn
import MessageUI
class PriceFormatter{
static func formatPrice(_ price: Decimal, currencyCode: String) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = currencyCode
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
return formatter.string(from: price as NSDecimalNumber) ?? "\(price)"
}
static func currencySymbol(for currencyCode: String) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = currencyCode
// formatter.locale = Locale(identifier: "zh_CN")
return formatter.currencySymbol
}
}
extension WatchAppOtherInfo{
func toParams() -> [String: Any]{
var json: [String: Any] = [:]
json["userId"] = userId
json["nickname"] = nickname
json["markName"] = markName
return json
}
}
/**
* PlatformApi iOS implementation.
*
* 组装完整 User-Agent,格式与 Android 端保持一致:
* `{systemWebViewUA} doublefeel/{versionCode}({versionName})(Apple##Apple##{model}; iOS{osVersion}; {height}x{width})(huawei)`
*/
final class PlatformHostApiImpl: NSObject, PlatformHostApi {
private var sendEmailCompletion: ((Result<Bool, any Error>) -> Void)?
func isDebugEnvoriment() throws -> Bool {
#if DEBUG || CI_ENV
return true
#else
return false
#endif
}
/// 检查appstore 是否是中国大陆区
func isChinaRegion(completion: @escaping (Result<Bool, any Error>) -> Void) {
Task{
let storefront = await Storefront.current
let isChinaMainLand = storefront?.countryCode == "CHN"
completion(.success(isChinaMainLand))
}
}
func requestNotificationAuth(completion: @escaping (Result<Bool, any Error>) -> Void) {
Task {
let center = UNUserNotificationCenter.current()
let settings = await center.notificationSettings()
switch settings.authorizationStatus {
case .authorized, .provisional, .ephemeral:
completion(.success(true))
case .notDetermined:
do {
let granted = try await center.requestAuthorization(options: [.alert, .sound, .badge])
if granted {
await MainActor.run {
UIApplication.shared.registerForRemoteNotifications()
}
}
completion(.success(granted))
} catch {
completion(.failure(error))
}
case .denied:
completion(.success(false))
@unknown default:
completion(.success(false))
}
}
}
func nativeHandleUrl(urlString: String) throws -> Bool {
if let url = URL(string: urlString){
UIApplication.shared.open(url)
return true
}
return false
}
func requestUnhandedUrl() throws -> String? {
let unhandedUrl = AppShared.shared.unhandedUrl
AppShared.shared.unhandedUrl = nil
return unhandedUrl
}
func jumpAppSetting() throws -> Bool {
if let url = URL(string: UIApplication.openSettingsURLString){
UIApplication.shared.open(url)
return true
}
return false
}
func requestAppReview(completion: @escaping (Result<Bool, any Error>) -> Void) {
// Task { @MainActor in
// guard let windowScene = UIApplication.shared.connectedScenes
// .compactMap({ $0 as? UIWindowScene })
// .first(where: { $0.activationState == .foregroundActive }) else {
// completion(.success(false))
// return
// }
//
// // App Store controls whether the prompt is actually displayed.
// AppStore.requestReview(in: windowScene)
// completion(.success(true))
// }
let urlString = "itms-apps://itunes.apple.com/app/id\(kAppId)?action=write-review"
guard let url = URL(string: urlString) else{
return
}
if UIApplication.shared.canOpenURL(url){
UIApplication.shared.open(url)
}
}
func shareText(text: String, completion: @escaping (Result<Bool, any Error>) -> Void) {
presentShareSheet(items: [text], completion: completion)
}
func shareFileData(databytes: FlutterStandardTypedData, completion: @escaping (Result<Bool, any Error>) -> Void) {
let fileURL = FileManager.default.temporaryDirectory
.appendingPathComponent("doublefeel-share-\(UUID().uuidString)")
.appendingPathExtension("data")
do {
try databytes.data.write(to: fileURL, options: .atomic)
} catch {
print("[PlatformHostApiImpl.shareFileData] return error: \(error)")
completion(.failure(error))
return
}
presentShareSheet(items: [fileURL], cleanupURL: fileURL, completion: completion)
}
func uploadFile(filePath: String, resourceType: HResourceType, completion: @escaping (Result<String?, any Error>) -> Void) {
let obsResourceType: HuaweiOBSResourceType
switch resourceType {
case .image:
obsResourceType = .image
case .video:
obsResourceType = .video
}
Task {
do {
let fileURL = try await HuaweiOBSUploader.shared.upload(
filePath: filePath,
resourceType: obsResourceType
)
completion(.success(fileURL))
} catch {
DebugLogger.log(desc: "uploadFile error: \(error.localizedDescription)")
completion(.failure(error))
}
}
}
func performCropImage(imageUrl: String, maxKB: Int64?, width: Int64?, height: Int64?, completion: @escaping (Result<String?, any Error>) -> Void) {
}
// 登录
func updateLoginInfo(jsonString: String, baseUrl: String) throws {
if let data = jsonString.data(using: .utf8){
do{
let model = try JSONDecoder().decode(FlutterUserSummary.self, from: data)
if let token = model.accessToken{
// 刷新用户信息
let watchUser = UserInfoModel(userId: model.meUserInfo?.id, token: token, baseUrl: baseUrl)
do{
let data = try JSONEncoder().encode(watchUser)
AppGroupConstants.defaults?.set(data, forKey: AppGroupConstants.Key.myUserInfo)
AppShared.shared.login(userInfo: watchUser)
_ = WatchConnectivityService.shared.sendLoginInfoMessage(userInfo: watchUser)
}catch{}
Task{
await AppShared.shared.reportDeviceInfo()
if await HealthKitService.shared.hasAnyReadableData() {
_ = await AnchoredHealthDataUploader.shared.uploadAll()
}
}
}
}catch{
DebugLogger.log(desc: error.localizedDescription)
}
}
}
// 退出登录
func logout() throws {
// 清除所有数据
AppShared.shared.logout()
_ = WatchConnectivityService.shared.sendLoginInfoMessage(userInfo: nil)
}
// 刷新会员
func refreshVip() throws {
_ = WatchConnectivityService.shared.sendCommandMessage(AppGroupMessageKey.reloadVip)
}
// 刷新watch app 和表盘
func refreshWatchAppAndWidgets() throws {
_ = WatchConnectivityService.shared.sendCommandMessage(AppGroupMessageKey.reloadAll)
}
func performRestore(completion: @escaping (Result<Bool, any Error>) -> Void) {
Task{
let success = await AppShared.shared.payment.restore()
completion(.success(success))
}
}
func requestAppleProductInfo(productId: String, baseUnit: Int64, completion: @escaping (Result<AppleProductInfo?, any Error>) -> Void) {
Task {
do {
let product = try await AppShared.shared.payment.requestProducts(productId)
let isTrialPeriod = await AppShared.shared.payment.isFreeTrail(product: product)
let originPrice = product.price
var displayPrice = product.displayPrice
var price = originPrice
if let introductoryOffer = product.subscription?.introductoryOffer{
price = introductoryOffer.price
displayPrice = introductoryOffer.displayPrice
}else if let offer = product.subscription?.promotionalOffers.first(where: { $0.id == product.id }){
price = offer.price
displayPrice = offer.displayPrice
}
let unitPrice = originPrice/Decimal(baseUnit)
let currencyCode = product.priceFormatStyle.currencyCode
let productInfo = AppleProductInfo(
productId: product.id,
productName: product.displayName,
originPriceDescription: product.displayPrice,
priceDescription: displayPrice,
originPrice: NSDecimalNumber(decimal: originPrice * 100).doubleValue,
price: NSDecimalNumber(decimal: price * 100).doubleValue,
unitPrice: PriceFormatter.formatPrice(unitPrice, currencyCode: currencyCode),
currencyCode: PriceFormatter.currencySymbol(for: currencyCode),
isTrialPeriod: isTrialPeriod
)
print("[PlatformHostApiImpl.requestAppleProductInfo] return: \(productInfo)")
completion(.success(productInfo))
} catch StoreKitError.productNotFound {
print("[PlatformHostApiImpl.requestAppleProductInfo] return: nil")
completion(.success(nil))
} catch {
print("[PlatformHostApiImpl.requestAppleProductInfo] error: \(error.localizedDescription)")
completion(.failure(error))
}
}
}
func performApplePayment(productId: String, uuid: String, completion: @escaping (Result<AppleProductPaymentResult?, any Error>) -> Void) {
Task {
let result = await AppShared.shared.payment.purchase(productId, uuidString: uuid)
print("[PlatformHostApiImpl.performApplePayment] return: \(result)")
completion(.success(result))
}
}
private var appleSignInCoordinator: AppleSignInCoordinator?
// private var authorizationController: ASAuthorizationController?
func requestAppleSignIn(completion: @escaping (Result<AppleSignInModel?, any Error>) -> Void) {
DispatchQueue.main.async { [weak self] in
guard let self else {
print("[PlatformHostApiImpl.requestAppleSignIn] error: \(PlatformHostApiError.deallocated.localizedDescription)")
completion(.failure(PlatformHostApiError.deallocated))
return
}
let provider = ASAuthorizationAppleIDProvider()
let request = provider.createRequest()
request.requestedScopes = [.fullName, .email]
guard let presentationAnchor = AppleSignInCoordinator.currentPresentationAnchor() else {
print("[PlatformHostApiImpl.requestAppleSignIn] error: \(PlatformHostApiError.missingPresentationAnchor.localizedDescription)")
completion(.failure(PlatformHostApiError.missingPresentationAnchor))
return
}
let coordinator = AppleSignInCoordinator(presentationAnchor: presentationAnchor) { [weak self] result in
self?.appleSignInCoordinator = nil
switch result {
case .success(let model):
print("[PlatformHostApiImpl.requestAppleSignIn] return: \(String(describing: model))")
case .failure(let error):
print("[PlatformHostApiImpl.requestAppleSignIn] error: \(error.localizedDescription)")
}
completion(result)
}
appleSignInCoordinator = coordinator
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = coordinator
controller.presentationContextProvider = coordinator
controller.performRequests()
// authorizationController = controller
}
}
func getFullUserAgent() throws -> String {
let userAgent = AppShared.shared.agent.finalUA
print("[PlatformHostApiImpl.getFullUserAgent] return: \(userAgent)")
return userAgent
}
func sendLocalNotification(dataType: Int64, dateTime: Int64, title: String, content: String, link: String, completion: @escaping (Result<Bool, any Error>) -> Void) {
Task {
do {
let sent = try await LocalNotificationSender.shared.send(
dataType: dataType,
dateTime: dateTime,
title: title,
body: content,
link: link
)
completion(.success(sent))
} catch {
completion(.failure(error))
}
}
}
func requestGoogleSignIn(completion: @escaping (Result<GoogleSignInModel?, any Error>) -> Void) {
DispatchQueue.main.async {
guard let viewController = Self.topViewController() else {
print("[PlatformHostApiImpl.requestGoogleSignIn] error: \(PlatformHostApiError.missingPresentationAnchor.localizedDescription)")
completion(.failure(PlatformHostApiError.missingPresentationAnchor))
return
}
GIDSignIn.sharedInstance.signIn(withPresenting: viewController) { signInResult, error in
if let error {
let nsError = error as NSError
if nsError.domain == kGIDSignInErrorDomain, nsError.code == -5 {
print("[PlatformHostApiImpl.requestGoogleSignIn] return: nil")
completion(.success(nil))
} else {
print("[PlatformHostApiImpl.requestGoogleSignIn] error: \(error.localizedDescription)")
completion(.failure(error))
}
return
}
guard let user = signInResult?.user else {
print("[PlatformHostApiImpl.requestGoogleSignIn] error: \(PlatformHostApiError.invalidGoogleCredential.localizedDescription)")
completion(.failure(PlatformHostApiError.invalidGoogleCredential))
return
}
guard let token = user.idToken?.tokenString else {
print("[PlatformHostApiImpl.requestGoogleSignIn] error: \(PlatformHostApiError.missingGoogleIDToken.localizedDescription)")
completion(.failure(PlatformHostApiError.missingGoogleIDToken))
return
}
let profilePicUrl = user.profile?.imageURL(withDimension: 240)
let model = GoogleSignInModel(
email: user.profile?.email,
clientID: user.configuration.clientID,
idToken: token,
nickname: user.profile?.name,
avatarUrl: profilePicUrl?.absoluteString
)
print("[PlatformHostApiImpl.requestGoogleSignIn] return: \(model)")
completion(.success(model))
}
}
}
func sendEmail(mailTo: String, title: String, content: String, completion: @escaping (Result<Bool, any Error>) -> Void) {
DispatchQueue.main.async { [weak self] in
guard let self else {
print("[PlatformHostApiImpl.sendEmail] error: \(PlatformHostApiError.deallocated.localizedDescription)")
completion(.failure(PlatformHostApiError.deallocated))
return
}
guard MFMailComposeViewController.canSendMail() else {
UIApplication.openEmailWithSchema(to: mailTo, subject: title, body: content) { opened in
print("[PlatformHostApiImpl.sendEmail] return: \(opened)")
completion(.success(opened))
}
return
}
guard sendEmailCompletion == nil else {
print("[PlatformHostApiImpl.sendEmail] error: \(PlatformHostApiError.mailComposerAlreadyPresented.localizedDescription)")
completion(.failure(PlatformHostApiError.mailComposerAlreadyPresented))
return
}
guard let viewController = Self.topViewController() else {
print("[PlatformHostApiImpl.sendEmail] error: \(PlatformHostApiError.missingPresentationAnchor.localizedDescription)")
completion(.failure(PlatformHostApiError.missingPresentationAnchor))
return
}
sendEmailCompletion = completion
let mailVC = MFMailComposeViewController()
mailVC.mailComposeDelegate = self
mailVC.setToRecipients([mailTo])
mailVC.setSubject(title)
mailVC.setMessageBody(content, isHTML: false)
viewController.present(mailVC, animated: true)
}
}
}
extension PlatformHostApiImpl: MFMailComposeViewControllerDelegate {
func mailComposeController(
_ controller: MFMailComposeViewController,
didFinishWith result: MFMailComposeResult,
error: Error?
) {
controller.dismiss(animated: true) { [weak self] in
guard let self else { return }
let completion = self.sendEmailCompletion
self.sendEmailCompletion = nil
if let error {
print("[PlatformHostApiImpl.sendEmail] error: \(error.localizedDescription)")
completion?(.failure(error))
return
}
let success: Bool
switch result {
case .cancelled:
success = false
case .saved, .sent:
success = true
case .failed:
success = false
@unknown default:
success = false
}
print("[PlatformHostApiImpl.sendEmail] return: \(success)")
completion?(.success(success))
}
}
}
//MARK: - 分享
extension PlatformHostApiImpl{
private func presentShareSheet(
items: [Any],
cleanupURL: URL? = nil,
completion: @escaping (Result<Bool, any Error>) -> Void
) {
DispatchQueue.main.async {
guard let viewController = Self.topViewController() else {
if let cleanupURL {
try? FileManager.default.removeItem(at: cleanupURL)
}
let error = NSError(
domain: "PlatformHostApiImpl.Share",
code: 1,
userInfo: [NSLocalizedDescriptionKey: "Unable to find a view controller for sharing."]
)
print("[PlatformHostApiImpl.share] return error: \(error)")
completion(.failure(error))
return
}
let activityController = UIActivityViewController(
activityItems: items,
applicationActivities: nil
)
activityController.popoverPresentationController?.sourceView = viewController.view
activityController.popoverPresentationController?.sourceRect = CGRect(
x: viewController.view.bounds.midX,
y: viewController.view.bounds.midY,
width: 1,
height: 1
)
activityController.completionWithItemsHandler = { _, completed, _, error in
if let cleanupURL {
try? FileManager.default.removeItem(at: cleanupURL)
}
if let error {
print("[PlatformHostApiImpl.share] return error: \(error)")
completion(.failure(error))
} else {
print("[PlatformHostApiImpl.share] return: \(completed)")
completion(.success(completed))
}
}
viewController.present(activityController, animated: true)
}
}
private static func topViewController(
from rootViewController: UIViewController? = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.first(where: { $0.activationState == .foregroundActive })?
.windows
.first(where: { $0.isKeyWindow })?
.rootViewController
) -> UIViewController? {
if let presented = rootViewController?.presentedViewController {
return topViewController(from: presented)
}
if let navigationController = rootViewController as? UINavigationController {
return topViewController(from: navigationController.visibleViewController)
}
if let tabBarController = rootViewController as? UITabBarController {
return topViewController(from: tabBarController.selectedViewController)
}
return rootViewController
}
}
extension UIApplication{
static func openEmailWithSchema(
to: String,
subject: String,
body: String,
completion: ((Bool) -> Void)? = nil
) {
if let url = createEmailUrl(to: to, subject: subject, body: body),
UIApplication.shared.canOpenURL(url){
UIApplication.shared.open(url, completionHandler: completion)
}else{
let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let defaultUrl = URL(string: "mailto:\(to)?subject=\(subjectEncoded)&body=\(bodyEncoded)")!
UIApplication.shared.open(defaultUrl, completionHandler: completion)
}
}
static func createEmailUrl(to: String, subject: String, body: String) -> URL? {
let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let gmailUrl = URL(string: "googlegmail://co?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let outlookUrl = URL(string: "ms-outlook://compose?to=\(to)&subject=\(subjectEncoded)")
let yahooMail = URL(string: "ymail://mail/compose?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let qqEmail = URL(string: "mqqapi://composeemail/compose?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let defaultUrl = URL(string: "mailto:\(to)?subject=\(subjectEncoded)&body=\(bodyEncoded)")
if let gmailUrl = gmailUrl, UIApplication.shared.canOpenURL(gmailUrl) {
return gmailUrl
} else if let outlookUrl = outlookUrl, UIApplication.shared.canOpenURL(outlookUrl) {
return outlookUrl
} else if let yahooMail = yahooMail,UIApplication.shared.canOpenURL(yahooMail) {
return yahooMail
} else if let sparkUrl = sparkUrl, UIApplication.shared.canOpenURL(sparkUrl) {
return sparkUrl
}else if let qqEmail, UIApplication.shared.canOpenURL(qqEmail) {
return qqEmail
}
return defaultUrl
}
}