AsaTool.m 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #import "AsaTool.h"
  2. #import <AdServices/AdServices.h>
  3. #import <AppTrackingTransparency/AppTrackingTransparency.h>
  4. @implementation AsaTool
  5. + (nullable NSString
  6. *)attributionToken {
  7. if (@available
  8. (iOS
  9. 14.3, *)) {
  10. NSError *error;
  11. NSString *token = [AAAttribution attributionTokenWithError:&error];
  12. if (error) {
  13. NSLog(@"[FlutterAsaAttribution]: Failed to retrieve attribution token: %@",
  14. error.localizedDescription);
  15. }
  16. return token;
  17. } else {
  18. NSLog(@"[FlutterAsaAttribution]: Only support iOS 14.3 and later");
  19. return nil;
  20. }
  21. }
  22. + (void)requestAttributionWithComplete:(void (^)(NSDictionary *_Nullable data, NSError *_Nullable
  23. error))complete {
  24. if (@available
  25. (iOS
  26. 14.3, *)) {
  27. NSError *error;
  28. NSString *token = [self attributionToken];
  29. if (token.length > 0) {
  30. [self requestAttributionWithToken:token complete:complete];
  31. } else {
  32. if (complete) {
  33. complete(nil, error ?: [NSError errorWithDomain:@"app" code:-1 userInfo:@{
  34. NSLocalizedDescriptionKey: @"Failed to retrieve attribution token"}]);
  35. }
  36. }
  37. } else {
  38. if (complete) {
  39. complete(nil, [NSError errorWithDomain:@"app" code:-1 userInfo:@{
  40. NSLocalizedDescriptionKey: @"ATTracking Not Allowed"}]);
  41. }
  42. }
  43. }
  44. + (void)requestAttributionWithToken:(NSString *)token complete:(void (^)(NSDictionary *_Nullable
  45. data, NSError *_Nullable
  46. error))complete {
  47. NSString *url = @"https://api-adservices.apple.com/api/v1/";
  48. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  49. request.HTTPMethod = @"POST";
  50. [request addValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
  51. request.HTTPBody = [token dataUsingEncoding:NSUTF8StringEncoding];
  52. NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(
  53. NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
  54. if (error) {
  55. dispatch_async(dispatch_get_main_queue(), ^{
  56. if (complete) complete(nil, error);
  57. });
  58. return;
  59. }
  60. NSError *jsonError;
  61. NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
  62. dispatch_async(dispatch_get_main_queue(), ^{
  63. if (complete) {
  64. complete(result ?: @{}, jsonError);
  65. }
  66. });
  67. }];
  68. [dataTask resume];
  69. }
  70. @end