Created
October 17, 2024 14:38
-
-
Save lanserxt/1412e9dcd7f9f342031895e56f552301 to your computer and use it in GitHub Desktop.
AdService AAAttribution payload async fetching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//This class demostates how to extract and store payload info if it's available. Compaign ID was valuable for me so that's why only it is stored. | |
import AdServices | |
actor UTMCampaignLoader { | |
// Optional campaignID property | |
var campaignID: Int? | |
// Method to load UTM campaign asynchronously | |
func loadUTMCampaign() async -> Int? { | |
do { | |
// Try to get the attributionToken from AAAttribution | |
let attributionToken = try AAAttribution.attributionToken() | |
// Create a POST request to Apple's ad services API | |
var request = URLRequest(url: URL(string:"https://api-adservices.apple.com/api/v1/")!) | |
request.httpMethod = "POST" | |
request.setValue("text/plain", forHTTPHeaderField: "Content-Type") | |
request.httpBody = Data(attributionToken.utf8) | |
// Use async version of URLSession to fetch data | |
let (data, response) = try await URLSession.shared.data(for: request) | |
// Check if response is an HTTP response and if status code is 200 | |
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 { | |
// Parse response data | |
if let result = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any], | |
let campaignId = result["campaignId"] as? Int { | |
self.campaignID = campaignId | |
print("Campaign ID:", campaignId) | |
return self.campaignID | |
} | |
} else { | |
// Handle non-200 status codes | |
if let httpResponse = response as? HTTPURLResponse { | |
print("Failed with status code: \(httpResponse.statusCode)") | |
} else { | |
print("Failed with unknown response") | |
} | |
} | |
} catch { | |
print("Error:", error) | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment