How to retrieve iPhone IDFA from API?

前端 未结 11 810
深忆病人
深忆病人 2020-12-12 14:37

I would like to get the device IDFA. How to get this info from iOS official API ?

11条回答
  •  天命终不由人
    2020-12-12 14:54

    Here's a commented helper class in Swift that will give you a nil object for the identifier if the user has turned advertisement tracking off:

    import AdSupport
    
    class IDFA {
        // MARK: - Stored Type Properties
        static let shared = IDFA()
    
        // MARK: - Computed Instance Properties
        /// Returns `true` if the user has turned off advertisement tracking, else `false`.
        var limited: Bool {
            return !ASIdentifierManager.shared().isAdvertisingTrackingEnabled
        }
    
        /// Returns the identifier if the user has turned advertisement tracking on, else `nil`.
        var identifier: String? {
            guard !limited else { return nil }
            return ASIdentifierManager.shared().advertisingIdentifier.uuidString
        }
    }
    

    Just add it to your project (for example in a file named IDFA.swift) and link the AdSupport.framework in your target via the "Linked Frameworks and Libraries" section in the General settings tab.

    Then you can use it like this:

    if let identifier = IDFA.shared.identifier {
        // use the identifier
    } else {
        // put any fallback logic in here
    }
    

提交回复
热议问题