Flutter - iOS申请IDFA

Date
Created
Feb 3, 2025 12:10 PM
Descrption
好记性不如烂笔头
Tags
iOS
商业化
notion image
本文记录一下在Flutter中如何申请IDFA

1.启用广告追踪权限:

<key>NSUserTrackingUsageDescription</key> <string>我们使用您的广告标识符来个性化广告内容</string>

2.iOS原生Method-Channel

You should import AdSupport and AppTrackingTransparency,
import UIKit import Flutter import AdSupport import AppTrackingTransparency @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // Flutter 的初始化代码 let controller : FlutterViewController = window?.rootViewController as! FlutterViewController let idfaChannel = FlutterMethodChannel(name: "com.example.idfa", binaryMessenger: controller.binaryMessenger) // 设置平台通道的处理器 idfaChannel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in if call.method == "getIDFA" { self.getIDFA(result: result) } else { result(FlutterMethodNotImplemented) } } return super.application(application, didFinishLaunchingWithOptions: launchOptions) } // 请求 ATT 权限并获取 IDFA private func getIDFA(result: @escaping FlutterResult) { if #available(iOS 14, *) { // 请求 App Tracking Transparency 权限 ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in switch status { case .authorized: // 用户授权后获取 IDFA let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString result(idfa) default: result(FlutterError(code: "PERMISSION_DENIED", message: "User denied permission", details: nil)) } }) } else { // 对于 iOS 14 以下版本,直接获取 IDFA let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString result(idfa) } } }
3.Invoke native method from flutter side
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'IDFA Example', home: Scaffold( appBar: AppBar(title: Text('IDFA Example')), body: Center( child: ElevatedButton( onPressed: _getIDFA, child: Text('获取 IDFA'), ), ), ), ); } Future<void> _getIDFA() async { const platform = MethodChannel('com.example.idfa'); try { final String idfa = await platform.invokeMethod('getIDFA'); print('IDFA: $idfa'); } on PlatformException catch (e) { print('获取 IDFA 失败: ${e.message}'); } } }