AsaTool.m 2.8 KB

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