How to retrieve iPhone IDFA from API?
First of all:
#import <AdSupport/ASIdentifierManager.h>
If you would like to get it as an NSString, use:
[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]
So your code might look like this:
NSString *idfaString = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
You first have to check if user user has decided to opt out from ad tracking. Only if he allowed it you can use the IDFA
.
You can check it by calling isAdvertisingTrackingEnabled
method of ASIdentifierManager
.
isAdvertisingTrackingEnabled
Check the value of this property before performing any advertising tracking. If the value is
NO
, use the advertising identifier only for the following purposes: frequency capping, conversion events, estimating the number of unique users, security and fraud detection, and debugging.
The following code snippet shows how to obtain a string value of IDFA
.
ObjC
@import AdSupport;- (NSString *)identifierForAdvertising { // Check whether advertising tracking is enabled if([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) { NSUUID *identifier = [[ASIdentifierManager sharedManager] advertisingIdentifier]; return [identifier UUIDString]; } // Get and return IDFA return nil;}
Swift
import AdSupportfunc identifierForAdvertising() -> String? { // Check whether advertising tracking is enabled guard ASIdentifierManager.shared().isAdvertisingTrackingEnabled else { return nil } // Get and return IDFA return ASIdentifierManager.shared().advertisingIdentifier.uuidString}
ASIdentifierManager is the official way to garner the Advertising Identification Number from a device running iOS 6+. You can use -[[ASIdentifierManager sharedManager] advertisingIdentifier];
to get it.