4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SwiftUI】トラッキングの取得タイミングに注意しよう

Last updated at Posted at 2025-05-26

リクエストはアプリがActiveになってから行う

トラッキングのリクエストはアプリがActive状態になってから呼び出さないと表示されない。

Calls to the API only prompt when the application state is UIApplicationStateActive.
https://developer.apple.com/documentation/apptrackingtransparency/attrackingmanager/requesttrackingauthorization(completionhandler:)

ViewがActiveになるタイミング

アプリ起動直後にリクエスト行う場合、AppDelegateクラスが元々ある場合はdidFinishLaunchingWithOptionsに直接定義することが多いと思う。
しかしAppDelegateがない場合はSwiftUIのView内の.onAppear.taskに定義しようと考えてしまうが、それだとリクエストのAlertが表示されない。

というのも、.onAppearの次に.taskが呼ばれ、その後にアプリがActive状態になるためである。

import SwiftUI

struct ContentView: View {
    
    @Environment(\.scenePhase) private var scenePhase
    
    var body: some View {
        EmptyView()
            .onAppear {
                print("onAppear")
            }
            .task {
                print("task")
            }
            .onChange(of: scenePhase) {
                if scenePhase == .active {
                    print("active")
                }
            }
    }
}

↓実行結果

onAppear
task
active

なので.onAppear, taskにリクエストを定義しても、まだActive状態になっていないのでアラートが表示されない。

正しい取得タイミング

ということでscenePhaseがactiveになったタイミングでリクエストすればいい。

import SwiftUI
import AppTrackingTransparency

struct ContentView: View {
    
    @Environment(\.scenePhase) private var scenePhase
    
    var body: some View {
        EmptyView()
            .onChange(of: scenePhase) {
                if scenePhase == .active {
                    Task {
                        guard ATTrackingManager.trackingAuthorizationStatus == .notDetermined else { return }
                        _ = await ATTrackingManager.requestTrackingAuthorization()
                    }
                }
            }
    }
    
}

info.plistへの定義も忘れずに。
スクリーンショット 2025-05-26 12.34.51.png

最後に

自分も.onAppear.taskに定義して少しだけ遅延させて表示させていたが、上記の方法が正しそう。
あとSwift6でrequestTrackingAuthorizationのcompletionの方を呼ぶとクラッシュするというのを見たが、クロージャ内で@Sendableを付与すると回避できる。でも普通にasyncの方を使うので良さそう。

ATTrackingManager.requestTrackingAuthorization { @Sendable status in
    print(status)
}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?