QSLInAppReviewmanager.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // QSLInAppReviewmanager.swift
  3. // QuickSearchLocation
  4. //
  5. // Created by Destiny on 2025/7/30.
  6. //
  7. import StoreKit
  8. class QSLInAppReviewmanager {
  9. // 记录应用启动次数
  10. static let launchCountKey = "AppLaunchCount"
  11. // 检查并请求评论
  12. static func requestReviewIfAppropriate() {
  13. // 获取应用启动次数
  14. let defaults = UserDefaults.standard
  15. var launchCount = defaults.integer(forKey: launchCountKey)
  16. launchCount += 1
  17. defaults.set(launchCount, forKey: launchCountKey)
  18. // 在适当的时机请求评论(例如第5次、第20次启动等)
  19. if launchCount == 5 || launchCount == 20 || launchCount == 50 {
  20. requestReview()
  21. }
  22. }
  23. // 直接请求评论(需要满足App Store的条件才会显示)
  24. static func requestReview() {
  25. if #available(iOS 14.0, *) {
  26. // 获取当前窗口场景
  27. if let windowScene = UIApplication.shared.connectedScenes
  28. .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
  29. SKStoreReviewController.requestReview(in: windowScene)
  30. }
  31. } else {
  32. // iOS 14以下版本
  33. SKStoreReviewController.requestReview()
  34. }
  35. }
  36. // 引导用户到App Store评论页面(备用方案)
  37. static func openAppStoreReviewPage() {
  38. guard let appId = Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as? String else { return }
  39. let urlString = "itms-apps://itunes.apple.com/app/id\(appId)?action=write-review"
  40. if let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) {
  41. UIApplication.shared.open(url, options: [:], completionHandler: nil)
  42. }
  43. }
  44. }
  45. /*
  46. // 使用示例
  47. // 在应用启动时调用(通常在AppDelegate或SceneDelegate中)
  48. func applicationDidBecomeActive(_ application: UIApplication) {
  49. InAppReviewManager.requestReviewIfAppropriate()
  50. }
  51. // 或者在用户完成关键操作后调用
  52. func userCompletedSignificantAction() {
  53. InAppReviewManager.requestReview()
  54. }
  55. // 作为备用方案,在用户拒绝原生弹窗后引导到App Store
  56. func showAppStoreReviewPage() {
  57. InAppReviewManager.openAppStoreReviewPage()
  58. }
  59. */