[iOS] Removed PODs libraries from repo.

Signed-off-by: Viktar Havaka viktor.govako@gmail.com
This commit is contained in:
vng 2020-12-20 13:26:55 +03:00 committed by Roman Tsisyk
parent de2ba76f80
commit 029a19914e
1519 changed files with 183 additions and 175590 deletions

View file

@ -1,185 +1,3 @@
PODS:
- AppsFlyerFramework (4.9.0)
- FBAudienceNetwork (5.9.0):
- FBSDKCoreKit/Basics (>= 5.6.0)
- FBSDKCoreKit (5.15.1):
- FBSDKCoreKit/Basics (= 5.15.1)
- FBSDKCoreKit/Core (= 5.15.1)
- FBSDKCoreKit/Basics (5.15.1)
- FBSDKCoreKit/Core (5.15.1):
- FBSDKCoreKit/Basics
- FBSDKLoginKit (5.15.1):
- FBSDKLoginKit/Login (= 5.15.1)
- FBSDKLoginKit/Login (5.15.1):
- FBSDKCoreKit (~> 5.0)
- Firebase/Analytics (6.26.0):
- Firebase/Core
- Firebase/Core (6.26.0):
- Firebase/CoreOnly
- FirebaseAnalytics (= 6.6.0)
- Firebase/CoreOnly (6.26.0):
- FirebaseCore (= 6.7.2)
- Firebase/Crashlytics (6.26.0):
- Firebase/CoreOnly
- FirebaseCrashlytics (~> 4.1.1)
- FirebaseAnalytics (6.6.0):
- FirebaseCore (~> 6.7)
- FirebaseInstallations (~> 1.3)
- GoogleAppMeasurement (= 6.6.0)
- GoogleUtilities/AppDelegateSwizzler (~> 6.0)
- GoogleUtilities/MethodSwizzler (~> 6.0)
- GoogleUtilities/Network (~> 6.0)
- "GoogleUtilities/NSData+zlib (~> 6.0)"
- nanopb (~> 1.30905.0)
- FirebaseAnalyticsInterop (1.5.0)
- FirebaseCore (6.7.2):
- FirebaseCoreDiagnostics (~> 1.3)
- FirebaseCoreDiagnosticsInterop (~> 1.2)
- GoogleUtilities/Environment (~> 6.5)
- GoogleUtilities/Logger (~> 6.5)
- FirebaseCoreDiagnostics (1.4.0):
- GoogleDataTransportCCTSupport (~> 3.1)
- GoogleUtilities/Environment (~> 6.5)
- GoogleUtilities/Logger (~> 6.5)
- nanopb (~> 1.30905.0)
- FirebaseCoreDiagnosticsInterop (1.2.0)
- FirebaseCrashlytics (4.1.1):
- FirebaseAnalyticsInterop (~> 1.2)
- FirebaseCore (~> 6.6)
- FirebaseInstallations (~> 1.1)
- GoogleDataTransport (~> 6.1)
- GoogleDataTransportCCTSupport (~> 3.1)
- nanopb (~> 1.30905.0)
- PromisesObjC (~> 1.2)
- FirebaseInstallations (1.3.0):
- FirebaseCore (~> 6.6)
- GoogleUtilities/Environment (~> 6.6)
- GoogleUtilities/UserDefaults (~> 6.6)
- PromisesObjC (~> 1.2)
- Flurry-iOS-SDK/FlurrySDK (11.1.0)
- GoogleAppMeasurement (6.6.0):
- GoogleUtilities/AppDelegateSwizzler (~> 6.0)
- GoogleUtilities/MethodSwizzler (~> 6.0)
- GoogleUtilities/Network (~> 6.0)
- "GoogleUtilities/NSData+zlib (~> 6.0)"
- nanopb (~> 1.30905.0)
- GoogleDataTransport (6.2.1)
- GoogleDataTransportCCTSupport (3.2.0):
- GoogleDataTransport (~> 6.1)
- nanopb (~> 1.30905.0)
- GoogleUtilities/AppDelegateSwizzler (6.7.1):
- GoogleUtilities/Environment
- GoogleUtilities/Logger
- GoogleUtilities/Network
- GoogleUtilities/Environment (6.7.1):
- PromisesObjC (~> 1.2)
- GoogleUtilities/Logger (6.7.1):
- GoogleUtilities/Environment
- GoogleUtilities/MethodSwizzler (6.7.1):
- GoogleUtilities/Logger
- GoogleUtilities/Network (6.7.1):
- GoogleUtilities/Logger
- "GoogleUtilities/NSData+zlib"
- GoogleUtilities/Reachability
- "GoogleUtilities/NSData+zlib (6.7.1)"
- GoogleUtilities/Reachability (6.7.1):
- GoogleUtilities/Logger
- GoogleUtilities/UserDefaults (6.7.1):
- GoogleUtilities/Logger
- MoPub-FacebookAudienceNetwork-Adapters (5.9.0.0):
- MoPub-FacebookAudienceNetwork-Adapters/MoPub (= 5.9.0.0)
- MoPub-FacebookAudienceNetwork-Adapters/Network (= 5.9.0.0)
- MoPub-FacebookAudienceNetwork-Adapters/MoPub (5.9.0.0):
- mopub-ios-sdk/Core (~> 5.6)
- mopub-ios-sdk/NativeAds (~> 5.6)
- MoPub-FacebookAudienceNetwork-Adapters/Network (5.9.0.0):
- FBAudienceNetwork (= 5.9.0)
- mopub-ios-sdk/Core (~> 5.6)
- mopub-ios-sdk/NativeAds (~> 5.6)
- mopub-ios-sdk (5.12.0):
- mopub-ios-sdk/MoPubSDK (= 5.12.0)
- mopub-ios-sdk/Avid (5.12.0):
- mopub-ios-sdk/Core
- mopub-ios-sdk/Core (5.12.0)
- mopub-ios-sdk/Moat (5.12.0):
- mopub-ios-sdk/Core
- mopub-ios-sdk/MoPubSDK (5.12.0):
- mopub-ios-sdk/Avid
- mopub-ios-sdk/Core
- mopub-ios-sdk/Moat
- mopub-ios-sdk/NativeAds
- mopub-ios-sdk/NativeAds (5.12.0):
- mopub-ios-sdk/Core
- nanopb (1.30905.0):
- nanopb/decode (= 1.30905.0)
- nanopb/encode (= 1.30905.0)
- nanopb/decode (1.30905.0)
- nanopb/encode (1.30905.0)
- PromisesObjC (1.2.9)
- Pushwoosh (5.16.0):
- Pushwoosh/Core (= 5.16.0)
- Pushwoosh/Core (5.16.0)
PODFILE CHECKSUM: deba2253f1e135a82d1d8c1740254e43cd41b1cf
DEPENDENCIES:
- AppsFlyerFramework (= 4.9.0)
- FBSDKCoreKit (= 5.15.1)
- FBSDKLoginKit (= 5.15.1)
- Firebase/Analytics (= 6.26.0)
- Firebase/Crashlytics (= 6.26.0)
- Flurry-iOS-SDK/FlurrySDK (= 11.1)
- MoPub-FacebookAudienceNetwork-Adapters (= 5.9.0)
- mopub-ios-sdk (= 5.12)
- Pushwoosh (= 5.16.0)
SPEC REPOS:
trunk:
- AppsFlyerFramework
- FBAudienceNetwork
- FBSDKCoreKit
- FBSDKLoginKit
- Firebase
- FirebaseAnalytics
- FirebaseAnalyticsInterop
- FirebaseCore
- FirebaseCoreDiagnostics
- FirebaseCoreDiagnosticsInterop
- FirebaseCrashlytics
- FirebaseInstallations
- Flurry-iOS-SDK
- GoogleAppMeasurement
- GoogleDataTransport
- GoogleDataTransportCCTSupport
- GoogleUtilities
- MoPub-FacebookAudienceNetwork-Adapters
- mopub-ios-sdk
- nanopb
- PromisesObjC
- Pushwoosh
SPEC CHECKSUMS:
AppsFlyerFramework: f57e5d590ad3124d3e594a76032a181bc91ec6cd
FBAudienceNetwork: 648648b13d8ea3d39676542dece2b04dbe867497
FBSDKCoreKit: 1d5acf7c9d7a2f92bb1a242dc60cae5b7adb91df
FBSDKLoginKit: f1ea8026a58b52d30c9f2e6a58ca7d813619fb83
Firebase: 7cf5f9c67f03cb3b606d1d6535286e1080e57eb6
FirebaseAnalytics: 96634d356482d4f3af8fe459a0ebf19a99c71b75
FirebaseAnalyticsInterop: 3f86269c38ae41f47afeb43ebf32a001f58fcdae
FirebaseCore: f42e5e5f382cdcf6b617ed737bf6c871a6947b17
FirebaseCoreDiagnostics: 4505e4d4009b1d93f605088ee7d7764d5f0d1c84
FirebaseCoreDiagnosticsInterop: 296e2c5f5314500a850ad0b83e9e7c10b011a850
FirebaseCrashlytics: a87cce5746d3335995bd18b1b60d073cd05a6920
FirebaseInstallations: 6f5f680e65dc374397a483c32d1799ba822a395b
Flurry-iOS-SDK: 88c0399d6d276325dc9f74f6183c1070e6c3f21e
GoogleAppMeasurement: 67458367830514fb20fd9e233496f1eef9d90185
GoogleDataTransport: 9a8a16f79feffc7f42096743de2a7c4815e84020
GoogleDataTransportCCTSupport: 489c1265d2c85b68187a83a911913d190012158d
GoogleUtilities: e121a3867449ce16b0e35ddf1797ea7a389ffdf2
MoPub-FacebookAudienceNetwork-Adapters: c9cbf2549ab2e108086594ab18f1709cc5897300
mopub-ios-sdk: bb61d5741ba16c6a78e5a54e37bc60ef8c9a80a8
nanopb: c43f40fadfe79e8b8db116583945847910cbabc9
PromisesObjC: b48e0338dbbac2207e611750777895f7a5811b75
Pushwoosh: 6cba171e52f3f7b8ccd280f492a5831deac2f594
PODFILE CHECKSUM: 6a5506aaa77abf026437e209f61e422241c8e153
COCOAPODS: 1.9.3
COCOAPODS: 1.10.0

View file

@ -1 +0,0 @@
Versions/Current/AppsFlyerLib

View file

@ -1 +0,0 @@
Versions/Current/Headers

View file

@ -1,6 +0,0 @@
framework module AppsFlyerLib {
umbrella header "AppsFlyerTracker.h"
export *
module * { export * }
}

View file

@ -1,47 +0,0 @@
//
// CrossPromotionHelper.h
// AppsFlyerLib
//
// Created by Gil Meroz on 27/01/2017.
//
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
AppsFlyer allows you to track and attribute installs originating
from cross promotion campaigns of your existing apps.
Afterwards, you can optimize on your cross-promotion traffic to get even better results.
*/
@interface AppsFlyerCrossPromotionHelper : NSObject
/**
To track an impression use the following API call.
Make sure to use the promoted App ID as it appears within the AppsFlyer dashboard.
@param appID Promoted App ID
@param campaign A campaign name
*/
+ (void)trackCrossPromoteImpression:(nonnull NSString*)appID
campaign:(nullable NSString*)campaign;
/**
iOS allows you to utilize the StoreKit component to open
the App Store while remaining in the context of your app.
More details at https://support.appsflyer.com/hc/en-us/articles/115004481946-Cross-Promotion-Tracking#tracking-cross-promotion-impressions
@param appID Promoted App ID
@param campaign A campaign name
@param parameters Additional params like `@{@"af_sub1": @"val", @"custom_param": @"val2" }`
@param openStoreBlock Contains promoted `clickURL`
*/
+ (void)trackAndOpenStore:(nonnull NSString*)appID
campaign:(nullable NSString *)campaign
paramters:(nullable NSDictionary*)parameters
openStore:(void (^)(NSURLSession *urlSession,NSURL *clickURL))openStoreBlock;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,50 +0,0 @@
//
// LinkGenerator.h
// AppsFlyerLib
//
// Created by Gil Meroz on 27/01/2017.
//
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Payload container for the `generateInviteUrlWithLinkGenerator:completionHandler:` from `AppsFlyerShareInviteHelper`
*/
@interface AppsFlyerLinkGenerator: NSObject
/// Instance initialization is not allowed. Use generated instance
/// from `-[AppsFlyerShareInviteHelper generateInviteUrlWithLinkGenerator:completionHandler]`
- (instancetype)init NS_UNAVAILABLE;
/// Instance initialization is not allowed. Use generated instance
/// from `-[AppsFlyerShareInviteHelper generateInviteUrlWithLinkGenerator:completionHandler]`
+ (instancetype)new NS_UNAVAILABLE;
/// The channel through which the invite was sent (e.g. Facebook/Gmail/etc.). Usage: Recommended
- (void)setChannel :(nonnull NSString *)channel;
/// ReferrerCustomerId setter
- (void)setReferrerCustomerId:(nonnull NSString *)referrerCustomerId;
/// A campaign name. Usage: Optional
- (void)setCampaign :(nonnull NSString *)campaign;
/// ReferrerUID setter
- (void)setReferrerUID :(nonnull NSString *)referrerUID;
/// Referrer name
- (void)setReferrerName :(nonnull NSString *)referrerName;
/// The URL to referrer user avatar. Usage: Optional
- (void)setReferrerImageURL :(nonnull NSString *)referrerImageURL;
/// AppleAppID
- (void)setAppleAppID :(nonnull NSString *)appleAppID;
/// Deeplink path
- (void)setDeeplinkPath :(nonnull NSString *)deeplinkPath;
/// Base deeplink path
- (void)setBaseDeeplink :(nonnull NSString *)baseDeeplink;
/// A single key value custom parameter. Usage: Optional
- (void)addParameterValue :(nonnull NSString *)value forKey:(NSString*)key;
/// Multiple key value custom parameters. Usage: Optional
- (void)addParameters :(nonnull NSDictionary *)parameters;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,35 +0,0 @@
//
// ShareInviteHelper.h
// AppsFlyerLib
//
// Created by Gil Meroz on 27/01/2017.
//
//
#import <Foundation/Foundation.h>
#import "AppsFlyerLinkGenerator.h"
/**
AppsFlyerShareInviteHelper
*/
@interface AppsFlyerShareInviteHelper : NSObject
NS_ASSUME_NONNULL_BEGIN
/**
* The AppsFlyerShareInviteHelper class builds the invite URL according to various setter methods
* which allow passing on additional information on the click.
* This information is available through `onConversionDataReceived:` when the user accepts the invite and installs the app.
* In addition, campaign and channel parameters are visible within the AppsFlyer Dashboard.
*/
+ (void) generateInviteUrlWithLinkGenerator:(AppsFlyerLinkGenerator * (^)(AppsFlyerLinkGenerator *generator))generatorCreator
completionHandler:(void (^)(NSURL * _Nullable url))completionHandler;
/**
* It is recommended to generate an in-app event after the invite is sent to track the invites from the senders' perspective.
* This enables you to find the users that tend most to invite friends, and the media sources that get you these users.
*/
+ (void) trackInvite:(nullable NSString *)channel parameters:(nullable NSDictionary *)parameters;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,532 +0,0 @@
//
// AppsFlyerTracker.h
// AppsFlyerLib
//
// AppsFlyer iOS SDK 4.9.0 (813)
// Copyright (c) 2019 AppsFlyer Ltd. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AppsFlyerCrossPromotionHelper.h"
#import "AppsFlyerShareInviteHelper.h"
// In app event names constants
#define AFEventLevelAchieved @"af_level_achieved"
#define AFEventAddPaymentInfo @"af_add_payment_info"
#define AFEventAddToCart @"af_add_to_cart"
#define AFEventAddToWishlist @"af_add_to_wishlist"
#define AFEventCompleteRegistration @"af_complete_registration"
#define AFEventTutorial_completion @"af_tutorial_completion"
#define AFEventInitiatedCheckout @"af_initiated_checkout"
#define AFEventPurchase @"af_purchase"
#define AFEventRate @"af_rate"
#define AFEventSearch @"af_search"
#define AFEventSpentCredits @"af_spent_credits"
#define AFEventAchievementUnlocked @"af_achievement_unlocked"
#define AFEventContentView @"af_content_view"
#define AFEventListView @"af_list_view"
#define AFEventTravelBooking @"af_travel_booking"
#define AFEventShare @"af_share"
#define AFEventInvite @"af_invite"
#define AFEventLogin @"af_login"
#define AFEventReEngage @"af_re_engage"
#define AFEventUpdate @"af_update"
#define AFEventOpenedFromPushNotification @"af_opened_from_push_notification"
#define AFEventLocation @"af_location_coordinates"
#define AFEventCustomerSegment @"af_customer_segment"
#define AFEventSubscribe @"af_subscribe"
#define AFEventStartTrial @"af_start_trial"
#define AFEventAdClick @"af_ad_click"
#define AFEventAdView @"af_ad_view"
// In app event parameter names
#define AFEventParamContent @"af_content"
#define AFEventParamAchievenmentId @"af_achievement_id"
#define AFEventParamLevel @"af_level"
#define AFEventParamScore @"af_score"
#define AFEventParamSuccess @"af_success"
#define AFEventParamPrice @"af_price"
#define AFEventParamContentType @"af_content_type"
#define AFEventParamContentId @"af_content_id"
#define AFEventParamContentList @"af_content_list"
#define AFEventParamCurrency @"af_currency"
#define AFEventParamQuantity @"af_quantity"
#define AFEventParamRegistrationMethod @"af_registration_method"
#define AFEventParamPaymentInfoAvailable @"af_payment_info_available"
#define AFEventParamMaxRatingValue @"af_max_rating_value"
#define AFEventParamRatingValue @"af_rating_value"
#define AFEventParamSearchString @"af_search_string"
#define AFEventParamDateA @"af_date_a"
#define AFEventParamDateB @"af_date_b"
#define AFEventParamDestinationA @"af_destination_a"
#define AFEventParamDestinationB @"af_destination_b"
#define AFEventParamDescription @"af_description"
#define AFEventParamClass @"af_class"
#define AFEventParamEventStart @"af_event_start"
#define AFEventParamEventEnd @"af_event_end"
#define AFEventParamLat @"af_lat"
#define AFEventParamLong @"af_long"
#define AFEventParamCustomerUserId @"af_customer_user_id"
#define AFEventParamValidated @"af_validated"
#define AFEventParamRevenue @"af_revenue"
#define AFEventProjectedParamRevenue @"af_projected_revenue"
#define AFEventParamReceiptId @"af_receipt_id"
#define AFEventParamTutorialId @"af_tutorial_id"
#define AFEventParamAchievenmentId @"af_achievement_id"
#define AFEventParamVirtualCurrencyName @"af_virtual_currency_name"
#define AFEventParamDeepLink @"af_deep_link"
#define AFEventParamOldVersion @"af_old_version"
#define AFEventParamNewVersion @"af_new_version"
#define AFEventParamReviewText @"af_review_text"
#define AFEventParamCouponCode @"af_coupon_code"
#define AFEventParamOrderId @"af_order_id"
#define AFEventParam1 @"af_param_1"
#define AFEventParam2 @"af_param_2"
#define AFEventParam3 @"af_param_3"
#define AFEventParam4 @"af_param_4"
#define AFEventParam5 @"af_param_5"
#define AFEventParam6 @"af_param_6"
#define AFEventParam7 @"af_param_7"
#define AFEventParam8 @"af_param_8"
#define AFEventParam9 @"af_param_9"
#define AFEventParam10 @"af_param_10"
#define AFEventParamDepartingDepartureDate @"af_departing_departure_date"
#define AFEventParamReturningDepartureDate @"af_returning_departure_date"
#define AFEventParamDestinationList @"af_destination_list" //array of string
#define AFEventParamCity @"af_city"
#define AFEventParamRegion @"af_region"
#define AFEventParamCountry @"af_country"
#define AFEventParamDepartingArrivalDate @"af_departing_arrival_date"
#define AFEventParamReturningArrivalDate @"af_returning_arrival_date"
#define AFEventParamSuggestedDestinations @"af_suggested_destinations" //array of string
#define AFEventParamTravelStart @"af_travel_start"
#define AFEventParamTravelEnd @"af_travel_end"
#define AFEventParamNumAdults @"af_num_adults"
#define AFEventParamNumChildren @"af_num_children"
#define AFEventParamNumInfants @"af_num_infants"
#define AFEventParamSuggestedHotels @"af_suggested_hotels" //array of string
#define AFEventParamUserScore @"af_user_score"
#define AFEventParamHotelScore @"af_hotel_score"
#define AFEventParamPurchaseCurrency @"af_purchase_currency"
#define AFEventParamPreferredStarRatings @"af_preferred_star_ratings" //array of int (basically a tuple (min,max) but we'll use array of int and instruct the developer to use two values)
#define AFEventParamPreferredPriceRange @"af_preferred_price_range" //array of int (basically a tuple (min,max) but we'll use array of int and instruct the developer to use two values)
#define AFEventParamPreferredNeighborhoods @"af_preferred_neighborhoods" //array of string
#define AFEventParamPreferredNumStops @"af_preferred_num_stops"
#define AFEventParamAdRevenueAdType @"af_adrev_ad_type"
#define AFEventParamAdRevenueNetworkName @"af_adrev_network_name"
#define AFEventParamAdRevenuePlacementId @"af_adrev_placement_id"
#define AFEventParamAdRevenueAdSize @"af_adrev_ad_size"
#define AFEventParamAdRevenueMediatedNetworkName @"af_adrev_mediated_network_name"
#define kDefaultOneLink @"go.onelink.me"
#define kNoOneLinkFallback @"https://app.appsflyer.com"
#define kINviteAppleAppID @"af_siteid"
/// Mail hashing type
typedef enum {
/// None
EmailCryptTypeNone = 0,
/// SHA1
EmailCryptTypeSHA1 = 1,
/// MD5
EmailCryptTypeMD5 = 2,
/// SHA256
EmailCryptTypeSHA256 = 3
} EmailCryptType;
/**
Conform and subscribe to this protocol to allow getting data about conversion and
install attribution
*/
@protocol AppsFlyerTrackerDelegate <NSObject>
@optional
/**
`installData` contains information about install.
Organic/non-organic, etc.
*/
- (void)onConversionDataReceived:(NSDictionary *)installData;
/**
Any errors that occurred during the conversion request.
*/
- (void)onConversionDataRequestFailure:(NSError *)error;
/**
`attributionData` contains information about OneLink, deeplink.
*/
- (void)onAppOpenAttribution:(NSDictionary *)attributionData;
/**
Any errors that occurred during the attribution request.
*/
- (void)onAppOpenAttributionFailure:(NSError *)error;
@end
/**
You can track installs, app updates, sessions and additional in-app events
(including in-app purchases, game levels, etc.)
to evaluate ROI and user engagement.
The iOS SDK is compatible with all iOS/tvOS devices with iOS version 7 and above.
@see [SDK Integration Validator](https://support.appsflyer.com/hc/en-us/articles/207032066-AppsFlyer-SDK-Integration-iOS)
for more information.
*/
@interface AppsFlyerTracker : NSObject
/**
Gets the singleton instance of the AppsFlyerTracker class, creating it if
necessary.
@return The singleton instance of AppsFlyerTracker.
*/
+ (AppsFlyerTracker *)sharedTracker;
/**
In case you use your own user ID in your app, you can set this property to that ID.
Enables you to cross-reference your own unique ID with AppsFlyers unique ID and the other devices IDs
*/
@property(nonatomic, strong, setter = setCustomerUserID:) NSString * customerUserID;
/**
In case you use custom data and you want to receive it in the raw reports.
@see [Setting additional custom data](https://support.appsflyer.com/hc/en-us/articles/207032066-AppsFlyer-SDK-Integration-iOS#setting-additional-custom-data) for more information.
*/
@property(nonatomic, strong, setter = setAdditionalData:) NSDictionary * customData;
/**
Use this property to set your AppsFlyer's dev key
*/
@property(nonatomic, strong, setter = setAppsFlyerDevKey:) NSString * appsFlyerDevKey;
/**
Use this property to set your app's Apple ID(taken from the app's page on iTunes Connect)
*/
@property(nonatomic, strong, setter = setAppleAppID:) NSString * appleAppID;
/**
In case of in app purchase events, you can set the currency code your user has purchased with.
The currency code is a 3 letter code according to ISO standards
Objective-C:
<pre>
[[AppsFlyerTracker sharedTracker] setCurrencyCode:@"USD"];
</pre>
Swift:
<pre>
AppsFlyerTracker.shared().currencyCode = "USD"
</pre>
*/
@property(nonatomic, strong) NSString *currencyCode;
/**
AppsFlyer SDK collect Apple's `advertisingIdentifier` if the `AdSupport.framework` included in the SDK.
You can disable this behavior by setting the following property to YES
*/
@property(atomic) BOOL disableAppleAdSupportTracking;
/**
Prints SDK messages to the console log. This property should only be used in `DEBUG` mode.
The default value is `NO`
*/
@property(nonatomic, setter = setIsDebug:) BOOL isDebug;
/**
Set this flag to `YES`, to collect the current device name(e.g. "My iPhone"). Default value is `NO`
*/
@property(nonatomic, setter = setShouldCollectDeviceName:) BOOL shouldCollectDeviceName;
/**
Set your `OneLink ID` from OneLink configuration. Used in User Invites to generate a OneLink.
*/
@property(nonatomic, strong, setter = setAppInviteOneLink:) NSString * appInviteOneLinkID;
/**
Opt-out tracking for specific user
*/
@property(atomic) BOOL deviceTrackingDisabled;
/**
Opt-out tracking for Apple Search Ads attributions
*/
@property(atomic) BOOL disableIAdTracking;
/**
AppsFlyer delegate. See `AppsFlyerTrackerDelegate`
*/
@property(weak, nonatomic) id<AppsFlyerTrackerDelegate> delegate;
/**
In app purchase receipt validation Apple environment(production or sandbox). The default value is NO
*/
@property(nonatomic, setter = setUseReceiptValidationSandbox:) BOOL useReceiptValidationSandbox;
/**
Set this flag to test uninstall on Apple environment(production or sandbox). The default value is NO
*/
@property(nonatomic, setter = setUseUninstallSandbox:) BOOL useUninstallSandbox;
/**
Advertising Id(exposed for RemoteDebug)
*/
@property(nonatomic, strong) NSString *advertiserId;
/**
For advertisers who wrap OneLink within another Universal Link.
An advertiser will be able to deeplink from a OneLink wrapped within another Universal Link and also track this retargeting conversion.
Objective-C:
<pre>
[[AppsFlyerTracker sharedTracker] setResolveDeepLinkURLs:@[@"domain.com", @"subdomain.domain.com"]];
</pre>
*/
@property(nonatomic) NSArray<NSString *> *resolveDeepLinkURLs;
/**
Use this to send the user's emails
@param userEmails The list of strings that hold mails
@param type Hash algoritm
*/
- (void)setUserEmails:(NSArray *)userEmails withCryptType:(EmailCryptType)type;
/**
Track application launch(session).
Add the following method at the `applicationDidBecomeActive` in AppDelegate class
*/
- (void)trackAppLaunch;
/**
Use this method to track events in your app like purchases or user actions
@param eventName Contains name of event that could be provided from predefined constants in `AppsFlyerTracker.h`
@param value Contains value for handling by backend
<pre>
[[AppsFlyer sharedTracker] trackEvent:AFEventPurchase withValue:"200"];
</pre>
*/
- (void)trackEvent:(NSString *)eventName withValue:(NSString *)value __attribute__((deprecated));
/**
Use this method to track an events with mulitple values. See AppsFlyer's documentation for details.
Objective-C:
<pre>
[[AppsFlyerTracker sharedTracker] trackEvent:AFEventPurchase
withValues: @{AFEventParamRevenue : @200,
AFEventParamCurrency : @"USD",
AFEventParamQuantity : @2,
AFEventParamContentId: @"092",
AFEventParamReceiptId: @"9277"}];
</pre>
Swift:
<pre>
AppsFlyerTracker.shared().trackEvent(AFEventPurchase,
withValues: [AFEventParamRevenue : "1200",
AFEventParamContent : "shoes",
AFEventParamContentId: "123"])
</pre>
@param eventName Contains name of event that could be provided from predefined constants in `AppsFlyerTracker.h`
@param values Contains dictionary of values for handling by backend
*/
- (void)trackEvent:(NSString *)eventName withValues:(NSDictionary *)values;
/**
To track and validate in app purchases you can call this method from the completeTransaction: method on
your `SKPaymentTransactionObserver`.
@param productIdentifier The product identifier
@param price The product price
@param currency The product currency
@param tranactionId The purchase transaction Id
@param params The additional param, which you want to receive it in the raw reports
@param successBlock The success callback
@param failedBlock The failure callback
*/
- (void)validateAndTrackInAppPurchase:(NSString *)productIdentifier
price:(NSString *)price
currency:(NSString *)currency
transactionId:(NSString *)tranactionId
additionalParameters:(NSDictionary *)params
success:(void (^)(NSDictionary *response))successBlock
failure:(void (^)(NSError *error, id reponse))failedBlock NS_AVAILABLE(10_7, 7_0);
/**
To Track location for geo-fencing. Does the same as code below.
<pre>
AppsFlyerTracker.shared().trackEvent(AFEventLocation, withValues: [AFEventParamLong:longitude, AFEventParamLat:latitude])
</pre>
@param longitude The location longitude
@param latitude The location latitude
*/
- (void)trackLocation:(double)longitude latitude:(double)latitude;
/**
This method returns AppsFlyer's internal id(unique for your app)
@return Internal AppsFlyer Id
*/
- (NSString *)getAppsFlyerUID;
/**
In case you want to use AppsFlyer tracking data in your app you can use the following method set a
delegate with callback buttons for the tracking data. See AppsFlyerTrackerDelegate above.
@param delegate The AppsFlyer delegate reference
*/
- (void)loadConversionDataWithDelegate:(id<AppsFlyerTrackerDelegate>)delegate __attribute__((deprecated));
/**
In case you want to track deep linking. Does the same as `-handleOpenURL:sourceApplication:withAnnotation`.
@warning Prefered to use `-handleOpenURL:sourceApplication:withAnnotation`.
@param url The URL that was passed to your AppDelegate.
@param sourceApplication The sourceApplication that passed to your AppDelegate.
*/
- (void)handleOpenURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication;
/**
In case you want to track deep linking.
Call this method from inside your AppDelegate `-application:openURL:sourceApplication:annotation:`
@param url The URL that was passed to your AppDelegate.
@param sourceApplication The sourceApplication that passed to your AppDelegate.
@param annotation The annotation that passed to your app delegate.
*/
- (void)handleOpenURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
withAnnotation:(id)annotation;
/**
Call this method from inside of your AppDelegate `-application:openURL:options:` method.
This method is functionally the same as calling the AppsFlyer method
`-handleOpenURL:sourceApplication:withAnnotation`.
@param url The URL that was passed to your app delegate
@param options The options dictionary that was passed to your AppDelegate.
*/
- (void)handleOpenUrl:(NSURL *)url options:(NSDictionary *)options;
/**
Allow AppsFlyer to handle restoration from an NSUserActivity.
Use this method to track deep links with OneLink.
@param userActivity The NSUserActivity that caused the app to be opened.
*/
- (BOOL)continueUserActivity:(NSUserActivity *)userActivity
restorationHandler:(void (^)(NSArray *))restorationHandler NS_AVAILABLE_IOS(9_0);
/**
This method is not used anymore. Exist only for backward compatability. Don't use.
@param userActivity The NSUserActivity param.
*/
- (void)didUpdateUserActivity:(NSUserActivity *)userActivity NS_AVAILABLE_IOS(9_0);
/**
Enable AppsFlyer to handle a push notification.
@see [Learn more here](https://support.appsflyer.com/hc/en-us/articles/207364076-Measuring-Push-Notification-Re-Engagement-Campaigns)
@warning To make it work - set data, related to AppsFlyer under key @"af".
@param pushPayload The `userInfo` from received remote notification. One of root keys should be @"af".
*/
- (void)handlePushNotification:(NSDictionary *)pushPayload;
/**
Register uninstall - you should register for remote notification and provide AppsFlyer the push device token.
@param deviceToken The `deviceToken` from `-application:didRegisterForRemoteNotificationsWithDeviceToken:`
*/
- (void)registerUninstall:(NSData *)deviceToken;
/**
Get SDK version.
@return The AppsFlyer SDK version info.
*/
- (NSString *)getSDKVersion;
/**
This is for internal use.
*/
- (void)remoteDebuggingCallWithData:(NSString *)data;
/**
@brief This property accepts a string value representing the host name for all endpoints.
Can be used to Zero rate your applications data usage. Contact your CSM for more information.
@warning To use `default` SDK endpoint set value to `nil`.
Objective-C:
<pre>
[[AppsFlyerTracker sharedTracker] setHost:@"example.com"];
</pre>
Swift:
<pre>
AppsFlyerTracker.shared().host = "example.com"
</pre>
*/
@property(nonatomic, strong) NSString *host;
- (void)setHost:(NSString *)host DEPRECATED_MSG_ATTRIBUTE("Use -[AppsFlyerTracker setHost:withHostPrefix:] instead");
/**
* This function set the host name and prefix host name for all the endpoints
**/
- (void)setHost:(NSString *)host withHostPrefix:(NSString *)hostPrefix;
/**
* This property accepts a string value representing the prefix host name for all endpoints.
* for example "test" prefix with default host name will have the address "host.appsflyer.com"
*/
@property(nonatomic, strong, readonly) NSString *hostPrefix;
/**
This property is responsible for timeout between sessions in seconds.
Default value is 5 seconds.
*/
@property(atomic) NSUInteger minTimeBetweenSessions;
/**
API to shut down all SDK activities.
@warning This will disable all requests from AppsFlyer SDK.
*/
@property(atomic) BOOL isStopTracking;
@end

View file

@ -1,68 +0,0 @@
<p align="center">
<img height="75" src="repository_assets/AF_color_medium.png" />
</p>
-----------
[![Version](https://img.shields.io/cocoapods/v/AppsFlyerFramework.svg?style=flat)](http://cocoapods.org/pods/AppsFlyerFramework)
[AppsFlyer](https://www.appsflyer.com/) helps mobile marketers measure and improve their performance through amazing tools, really big data and over 2,000 integrations.
- Supports iOS 8+
Installation
------------
### CocoaPods
Just add `pod 'AppsFlyerFramework'` into your [Podfile](https://guides.cocoapods.org/syntax/podfile.html).
Then run
```zsh
$ pod install
```
Finally, import the framework:
```swift
// Swift
import AppsFlyerLib
```
```objc
// ObjC
#import <AppsFlyerTracker/AppsFlyerTracker.h>
```
### Carthage
Just add the following into your [Cartfile](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfile):
```
binary "https://raw.githubusercontent.com/AppsFlyerSDK/AppsFlyerFramework/master/AppsFlyerTracker.json"
```
Then run
```zsh
$ carthage bootstrap
```
**Note:**
Old URI referencing `Carthage.json` is deprecated. If you use it please update your Cartfile to the new one to ease dependency management.
Changelog
------------
You can find the release changelog [here](https://support.appsflyer.com/hc/en-us/articles/115001224823-AppsFlyer-iOS-SDK-Release-Notes).
---
In order for us to provide optimal support, we would kindly ask you to submit any issues to support@appsflyer.com
*When submitting an issue please specify your AppsFlyer sign-up (account) email, your app ID, production steps, logs, code snippets and any additional relevant information.*
----------

View file

@ -1,49 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/***
* This is a bridge file for Audience Network Unity SDK.
*
* This file may be used to build your own Audience Network iOS SDK wrapper,
* but note that we don't support customisations of the Audience Network codebase.
*
***/
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdBridgeContainer.h>
#import <FBAudienceNetwork/FBAdDefines.h>
FB_EXTERN_C_BEGIN
// External to this project
typedef NS_ENUM(NSInteger, FBGLViewController) {
FBGLViewControllerNone,
FBGLViewControllerUnity,
FBGLViewControllerCocos2D,
};
__attribute__((weak)) extern UIViewController *UnityGetGLViewController(void);
__attribute__((__always_inline__)) extern FBGLViewController fbad_Cocos2DGetGLViewController(
UIViewController **glViewController);
__attribute__((__always_inline__)) extern UIViewController *fbad_GetGLViewController(void);
__attribute__((__always_inline__)) extern FBGLViewController fbad_UnityGetGLViewController(
UIViewController **glViewController);
FB_EXTERN_C_END

View file

@ -1,103 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/***
* This is a bridge file for Audience Network Unity SDK.
*
* This file may be used to build your own Audience Network iOS SDK wrapper,
* but note that we don't support customisations of the Audience Network codebase.
*
***/
#import <Foundation/Foundation.h>
#import <FBAudienceNetwork/FBAdBridgeCommon.h>
#import <FBAudienceNetwork/FBAdView.h>
#import <FBAudienceNetwork/FBInterstitialAd.h>
#import <FBAudienceNetwork/FBRewardedVideoAd.h>
typedef void (*FBAdBridgeCallback)(uint32_t uniqueId);
typedef void (*FBAdBridgeErrorCallback)(uint32_t uniqueId, char const *error);
@interface FBAdBridgeContainer : NSObject
@property (nonatomic, assign) int32_t uniqueId;
// Explicitly remove callbacks
- (void)dispose;
@end
@interface FBAdViewBridgeContainer : FBAdBridgeContainer <FBAdViewDelegate>
@property (nonatomic, strong) FBAdView *adView;
@property (nonatomic, assign) FBAdBridgeCallback adViewDidClickCallback;
@property (nonatomic, assign) FBAdBridgeCallback adViewDidFinishHandlingClickCallback;
@property (nonatomic, assign) FBAdBridgeCallback adViewDidLoadCallback;
@property (nonatomic, assign) FBAdBridgeErrorCallback adViewDidFailWithErrorCallback;
@property (nonatomic, assign) FBAdBridgeCallback adViewWillLogImpressionCallback;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithAdView:(FBAdView *)adView withUniqueId:(int32_t)uniqueId NS_DESIGNATED_INITIALIZER;
@end
@interface FBInterstitialAdBridgeContainer : FBAdBridgeContainer <FBInterstitialAdDelegate>
@property (nonatomic, strong) FBInterstitialAd *interstitialAd;
@property (nonatomic, assign) FBAdBridgeCallback interstitialAdDidClickCallback;
@property (nonatomic, assign) FBAdBridgeCallback interstitialAdDidCloseCallback;
@property (nonatomic, assign) FBAdBridgeCallback interstitialAdWillCloseCallback;
@property (nonatomic, assign) FBAdBridgeCallback interstitialAdDidLoadCallback;
@property (nonatomic, assign) FBAdBridgeErrorCallback interstitialAdDidFailWithErrorCallback;
@property (nonatomic, assign) FBAdBridgeCallback interstitialAdWillLogImpressionCallback;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithInterstitialAd:(FBInterstitialAd *)interstitialAd
withUniqueId:(int32_t)uniqueId NS_DESIGNATED_INITIALIZER;
@end
@interface FBRewardedVideoAdBridgeContainer : FBAdBridgeContainer <FBRewardedVideoAdDelegate>
@property (nonatomic, strong) FBRewardedVideoAd *rewardedVideoAd;
@property (nonatomic, assign) FBAdBridgeCallback rewardedVideoAdDidClickCallback;
@property (nonatomic, assign) FBAdBridgeCallback rewardedVideoAdDidCloseCallback;
@property (nonatomic, assign) FBAdBridgeCallback rewardedVideoAdWillCloseCallback;
@property (nonatomic, assign) FBAdBridgeCallback rewardedVideoAdDidLoadCallback;
@property (nonatomic, assign) FBAdBridgeErrorCallback rewardedVideoAdDidFailWithErrorCallback;
@property (nonatomic, assign) FBAdBridgeCallback rewardedVideoAdWillLogImpressionCallback;
@property (nonatomic, assign) FBAdBridgeCallback rewardedVideoAdVideoCompleteCallback;
@property (nonatomic, assign) FBAdBridgeCallback rewardedVideoAdServerRewardDidSucceedCallback;
@property (nonatomic, assign) FBAdBridgeCallback rewardedVideoAdServerRewardDidFailCallback;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithRewardedVideoAd:(FBRewardedVideoAd *)rewardedVideoAd
withUniqueId:(int32_t)uniqueId NS_DESIGNATED_INITIALIZER;
@end

View file

@ -1,125 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/UIView+FBNativeAdViewTag.h>
NS_ASSUME_NONNULL_BEGIN
@class FBAdImage;
@class FBNativeAdBase;
@class FBNativeAdViewAttributes;
/**
FBAdChoicesView offers a simple way to display a sponsored or AdChoices icon.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBAdChoicesView : UIView
/**
Access to the text label contained in this view.
*/
@property (nonatomic, weak, readonly, nullable) UILabel *label;
/**
Determines whether the background mask is shown, or a transparent mask is used.
*/
@property (nonatomic, assign, getter=isBackgroundShown) BOOL backgroundShown;
/**
Determines whether the view can be expanded upon being tapped, or defaults to fullsize. Defaults to NO.
*/
@property (nonatomic, assign, readonly, getter=isExpandable) BOOL expandable;
/**
The native ad that provides AdChoices info, such as the image url, and click url. Setting this updates the nativeAd.
*/
@property (nonatomic, weak, readwrite, nullable) FBNativeAdBase *nativeAd;
/**
Affects background mask rendering. Setting this property updates the rendering.
*/
@property (nonatomic, assign, readwrite) UIRectCorner corner;
/**
Affects background mask rendering. Setting this property updates the rendering.
*/
@property (nonatomic, assign, readwrite) UIEdgeInsets insets;
/**
The view controller to present the ad choices info from. If nil, the top view controller is used.
*/
@property (nonatomic, weak, readwrite, null_resettable) UIViewController *rootViewController;
/**
The tag for AdChoices view. It always returns FBNativeAdViewTagChoicesIcon.
*/
@property (nonatomic, assign, readonly) FBNativeAdViewTag nativeAdViewTag;
/**
Initialize this view with a given native ad. Configuration is pulled from the native ad.
@param nativeAd The native ad to initialize with.
*/
- (instancetype)initWithNativeAd:(FBNativeAdBase *)nativeAd;
/**
Initialize this view with a given native ad. Configuration is pulled from the native ad.
@param nativeAd The native ad to initialize with.
@param expandable Controls whether view defaults to expanded or not, see property documentation
*/
- (instancetype)initWithNativeAd:(FBNativeAdBase *)nativeAd expandable:(BOOL)expandable;
/**
Initialize this view with a given native ad. Configuration is pulled from the native ad.
@param nativeAd The native ad to initialize with.
@param expandable Controls whether view defaults to expanded or not, see property documentation
@param attributes Attributes to configure look and feel.
*/
- (instancetype)initWithNativeAd:(FBNativeAdBase *)nativeAd
expandable:(BOOL)expandable
attributes:(nullable FBNativeAdViewAttributes *)attributes;
/**
Using the superview, this updates the frame of this view, positioning the icon in the top right corner by default.
*/
- (void)updateFrameFromSuperview;
/**
Using the superview, this updates the frame of this view, positioning the icon in the corner specified.
UIRectCornerAllCorners not supported.
@param corner The corner to display this view from.
*/
- (void)updateFrameFromSuperview:(UIRectCorner)corner;
/**
Using the superview, this updates the frame of this view, positioning the icon in the corner specified.
UIRectCornerAllCorners not supported.
@param corner The corner to display this view from.
@param insets Insets to take into account when positioning the view. Only respective insets are applied to corners.
*/
- (void)updateFrameFromSuperview:(UIRectCorner)corner insets:(UIEdgeInsets)insets;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,72 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef FBAudienceNetwork_FBAdDefines_h
#define FBAudienceNetwork_FBAdDefines_h
#ifdef __cplusplus
#define FB_EXTERN_C_BEGIN extern "C" {
#define FB_EXTERN_C_END }
#else
#define FB_EXTERN_C_BEGIN
#define FB_EXTERN_C_END
#endif
#ifdef __cplusplus
#define FB_EXPORT extern "C" __attribute__((visibility("default")))
#else
#define FB_EXPORT extern __attribute__((visibility("default")))
#endif
#define FB_CLASS_EXPORT __attribute__((visibility("default")))
#define FB_DEPRECATED __attribute__((deprecated))
#define FB_DEPRECATED_WITH_MESSAGE(M) __attribute__((deprecated(M)))
#if __has_feature(objc_generics)
#define FB_NSArrayOf(x) NSArray<x>
#define FB_NSMutableArrayOf(x) NSMutableArray<x>
#define FB_NSDictionaryOf(x, y) NSDictionary<x, y>
#define FB_NSMutableDictionaryOf(x, y) NSMutableDictionary<x, y>
#define FB_NSSetOf(x) NSSet<x>
#define FB_NSMutableSetOf(x) NSMutableSet<x>
#else
#define FB_NSArrayOf(x) NSArray
#define FB_NSMutableArrayOf(x) NSMutableArray
#define FB_NSDictionaryOf(x, y) NSDictionary
#define FB_NSMutableDictionaryOf(x, y) NSMutableDictionary
#define FB_NSSetOf(x) NSSet
#define FB_NSMutableSetOf(x) NSMutableSet
#define __covariant
#endif
#if !__has_feature(nullability)
#define NS_ASSUME_NONNULL_BEGIN
#define NS_ASSUME_NONNULL_END
#define nullable
#define __nullable
#endif
#ifndef FB_SUBCLASSING_RESTRICTED
#if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted)
#define FB_SUBCLASSING_RESTRICTED __attribute__((objc_subclassing_restricted))
#else
#define FB_SUBCLASSING_RESTRICTED
#endif
#endif
#endif

View file

@ -1,52 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <FBAudienceNetwork/FBAdDefines.h>
NS_ASSUME_NONNULL_BEGIN
typedef NSString *FBAdExperienceType NS_STRING_ENUM;
extern FBAdExperienceType const FBAdExperienceTypeRewarded;
extern FBAdExperienceType const FBAdExperienceTypeInterstitial;
extern FBAdExperienceType const FBAdExperienceTypeRewardedInterstitial;
FB_CLASS_EXPORT
/**
FBAdExperienceConfig is class designed to add some configuration to ad experience
*/
@interface FBAdExperienceConfig : NSObject
/**
Ad experience type to set up
*/
@property (nonatomic, strong, readwrite, nonnull) FBAdExperienceType adExperienceType;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
/**
Creates an FBAdExperienceConfig with a specified type of experience
*/
- (instancetype)initWithAdExperienceType:(FBAdExperienceType)adExperienceType NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,100 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <FBAudienceNetwork/FBAdDefines.h>
NS_ASSUME_NONNULL_BEGIN
typedef NSString *FBAdExtraHintKeyword NS_STRING_ENUM;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordAccessories;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordArtHistory;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordAutomotive;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordBeauty;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordBiology;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordBoardGames;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordBusinessSoftware;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordBuyingSellingHomes;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordCats;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordCelebrities;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordClothing;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordComicBooks;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordDesktopVideo;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordDogs;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordEducation;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordEmail;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordEntertainment;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordFamilyParenting;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordFashion;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordFineArt;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordFoodDrink;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordFrenchCuisine;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordGovernment;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordHealthFitness;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordHobbies;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordHomeGarden;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordHumor;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordInternetTechnology;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordLargeAnimals;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordLaw;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordLegalIssues;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordLiterature;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordMarketing;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordMovies;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordMusic;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordNews;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordPersonalFinance;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordPets;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordPhotography;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordPolitics;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordRealEstate;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordRoleplayingGames;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordScience;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordShopping;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordSociety;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordSports;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordTechnology;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordTelevision;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordTravel;
extern FBAdExtraHintKeyword const FBAdExtraHintKeywordVideoComputerGames;
FB_CLASS_EXPORT
@interface FBAdExtraHint : NSObject
@property (nonatomic, copy, nullable)
NSString *contentURL FB_DEPRECATED_WITH_MESSAGE("Extra hints are no longer used in Audience Network");
@property (nonatomic, copy, nullable)
NSString *extraData FB_DEPRECATED_WITH_MESSAGE("Extra hints are no longer used in Audience Network");
@property (nonatomic, copy, nullable)
NSString *mediationData FB_DEPRECATED_WITH_MESSAGE("Extra hints are no longer used in Audience Network");
- (instancetype)initWithKeywords:(NSArray<FBAdExtraHintKeyword> *)keywords
FB_DEPRECATED_WITH_MESSAGE("Keywords are no longer used in Audience Network");
- (void)addKeyword:(FBAdExtraHintKeyword)keyword
FB_DEPRECATED_WITH_MESSAGE("Keywords are no longer used in Audience Network");
- (void)removeKeyword:(FBAdExtraHintKeyword)keyword
FB_DEPRECATED_WITH_MESSAGE("Keywords are no longer used in Audience Network");
@end
NS_ASSUME_NONNULL_END

View file

@ -1,38 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBMediaView.h>
#import <FBAudienceNetwork/UIView+FBNativeAdViewTag.h>
NS_ASSUME_NONNULL_BEGIN
FB_CLASS_EXPORT
FB_DEPRECATED_WITH_MESSAGE("This class will be removed in a future release. Use FBMediaView instead.")
@interface FBAdIconView : FBMediaView
/**
The tag for the icon view. It always returns FBNativeAdViewTagIcon.
*/
@property (nonatomic, assign, readonly) FBNativeAdViewTag nativeAdViewTag;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,62 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
NS_ASSUME_NONNULL_BEGIN
/**
Represents an image creative.
*/
FB_CLASS_EXPORT
@interface FBAdImage : NSObject
/**
Typed access to the image url.
*/
@property (nonatomic, copy, readonly) NSURL *url;
/**
Typed access to the image width.
*/
@property (nonatomic, assign, readonly) NSInteger width;
/**
Typed access to the image height.
*/
@property (nonatomic, assign, readonly) NSInteger height;
/**
This is a method to initialize an FBAdImage.
@param url the image url.
@param width the image width.
@param height the image height.
*/
- (instancetype)initWithURL:(NSURL *)url width:(NSInteger)width height:(NSInteger)height NS_DESIGNATED_INITIALIZER;
/**
Loads an image from self.url over the network, or returns the cached image immediately.
@param block Block to handle the loaded image.
*/
- (void)loadImageAsyncWithBlock:(nullable void (^)(UIImage *__nullable image))block;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,54 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class FBNativeAdBase;
/**
Minimum dimensions of the view.
*/
extern const CGFloat FBAdOptionsViewWidth;
extern const CGFloat FBAdOptionsViewHeight;
@interface FBAdOptionsView : UIView
/**
The native ad that provides AdChoices info, such as click url. Setting this updates the nativeAd.
*/
@property (nonatomic, weak, readwrite, nullable) FBNativeAdBase *nativeAd;
/**
The color to be used when drawing the AdChoices view.
*/
@property (nonatomic, strong, nullable) UIColor *foregroundColor;
/**
Only show the ad choices triangle icon. Default is NO.
Sizing note:
- Single icon is rendered in a square frame, it will default to the smallest dimension.
- Non single icon requires aspect ratio of the view to be 2.4 or less.
*/
@property (nonatomic, assign) BOOL useSingleIcon;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,227 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <FBAudienceNetwork/FBAdDefines.h>
NS_ASSUME_NONNULL_BEGIN
/**
Audience Network error domain
*/
FB_EXPORT NSString *const FBAudienceNetworkErrorDomain;
/**
Audience Network error FBMediaView error domain
*/
FB_EXPORT NSString *const FBAudienceNetworkMediaViewErrorDomain;
/**
Audience Network SDK logging levels
*/
typedef NS_ENUM(NSInteger, FBAdLogLevel) {
/// No logging
FBAdLogLevelNone,
/// Notifications
FBAdLogLevelNotification,
/// Errors only
FBAdLogLevelError,
/// Warnings only
FBAdLogLevelWarning,
/// Standard log level
FBAdLogLevelLog,
/// Debug logging
FBAdLogLevelDebug,
/// Log everything (verbose)
FBAdLogLevelVerbose
};
/**
Test Ad type to be injected when test mode is on
*/
typedef NS_ENUM(NSInteger, FBAdTestAdType) {
/// This will return a random ad type when test mode is on.
FBAdTestAdType_Default,
/// 16x9 image ad with app install CTA option
FBAdTestAdType_Img_16_9_App_Install,
/// 16x9 image ad with link CTA option
FBAdTestAdType_Img_16_9_Link,
/// 16x9 HD video 46 sec ad with app install CTA option
FBAdTestAdType_Vid_HD_16_9_46s_App_Install,
/// 16x9 HD video 46 sec ad with link CTA option
FBAdTestAdType_Vid_HD_16_9_46s_Link,
/// 16x9 HD video 15 sec ad with app install CTA option
FBAdTestAdType_Vid_HD_16_9_15s_App_Install,
/// 16x9 HD video 15 sec ad with link CTA option
FBAdTestAdType_Vid_HD_16_9_15s_Link,
/// 9x16 HD video 39 sec ad with app install CTA option
FBAdTestAdType_Vid_HD_9_16_39s_App_Install,
/// 9x16 HD video 39 sec ad with link CTA option
FBAdTestAdType_Vid_HD_9_16_39s_Link,
/// carousel ad with square image and app install CTA option
FBAdTestAdType_Carousel_Img_Square_App_Install,
/// carousel ad with square image and link CTA option
FBAdTestAdType_Carousel_Img_Square_Link,
/// carousel ad with square video and link CTA option
FBAdTestAdType_Carousel_Vid_Square_Link,
/// sample playable ad with app install CTA
FBAdTestAdType_Playable
};
@protocol FBAdLoggingDelegate;
/**
AdSettings contains global settings for all ad controls.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBAdSettings : NSObject
/**
Controls support for audio-only video playback when the app is backgrounded. Note that this is only supported
when using FBMediaViewVideoRenderer, and requires corresponding support for background audio to be added to
the app. Default value is NO.
*/
@property (class, nonatomic, assign, getter=isBackgroundVideoPlaybackAllowed) BOOL backgroundVideoPlaybackAllowed;
/**
When test mode is on, setting a non default value for testAdType will
requests the specified type of ad.
*/
@property (class, nonatomic, assign) FBAdTestAdType testAdType;
/**
When this delegate is set, logs will be redirected to the delegate instead of being logged directly to the console with
NSLog. This can be used in combination with external logging frameworks.
*/
@property (class, nonatomic, weak, nullable) id<FBAdLoggingDelegate> loggingDelegate;
/**
Generates bidder token that needs to be included in the server side bid request to Facebook endpoint.
*/
@property (class, nonatomic, copy, readonly) NSString *bidderToken;
/**
Generates routing token needed for requests routing in reverse-proxy, since we don't have cookies in app environments.
*/
@property (class, nonatomic, copy, readonly) NSString *routingToken;
/**
Returns test mode on/off.
*/
+ (BOOL)isTestMode;
/**
Returns the hashid of the device to use test mode on.
*/
+ (NSString *)testDeviceHash;
/**
Adds a test device.
@param deviceHash The id of the device to use test mode, can be obtained from debug log or testDeviceHash
Copy the current device Id from debug log and add it as a test device to get test ads. Apps
running on emulator will automatically get test ads. Test devices should be added before loadAd is called.
*/
+ (void)addTestDevice:(NSString *)deviceHash;
/**
Add a collection of test devices. See `+addTestDevices:` for details.
@param devicesHash The array of the device id to use test mode, can be obtained from debug log or testDeviceHash
*/
+ (void)addTestDevices:(FB_NSArrayOf(NSString *) *)devicesHash;
/**
Clear all the added test devices
*/
+ (void)clearTestDevices;
/**
Clears the added test device
@param deviceHash The id of the device using test mode, can be obtained from debug log or testDeviceHash
*/
+ (void)clearTestDevice:(NSString *)deviceHash;
/**
Configures the ad control for treatment as child-directed.
@param isChildDirected Indicates whether you would like your ad control to be treated as child-directed
Note that you may have other legal obligations under the Children's Online Privacy Protection Act (COPPA).
Please review the FTC's guidance and consult with your own legal counsel.
*/
+ (void)setIsChildDirected:(BOOL)isChildDirected
FB_DEPRECATED_WITH_MESSAGE(
"isChildDirected method is no longer supported in Audience Network. Use +mixedAudience instead");
/**
Configures the ad control for treatment as mixed audience directed.
Information for Mixed Audience Apps and Services: https://developers.facebook.com/docs/audience-network/coppa
*/
@property (class, nonatomic, assign, getter=isMixedAudience) BOOL mixedAudience;
/**
If an ad provided service is mediating Audience Network in their sdk, it is required to set the name of the mediation
service
@param service Representing the name of the mediation that is mediation Audience Network
*/
+ (void)setMediationService:(NSString *)service;
/**
Gets the url prefix to use when making ad requests.
This method should never be used in production.
*/
+ (nullable NSString *)urlPrefix;
/**
Sets the url prefix to use when making ad requests.
This method should never be used in production.
*/
+ (void)setUrlPrefix:(nullable NSString *)urlPrefix;
/**
Gets the current SDK logging level
*/
+ (FBAdLogLevel)getLogLevel;
/**
Sets the current SDK logging level
*/
+ (void)setLogLevel:(FBAdLogLevel)level;
@end
@protocol FBAdLoggingDelegate <NSObject>
- (void)logAtLevel:(FBAdLogLevel)level
withFileName:(NSString *)fileName
withLineNumber:(int)lineNumber
withThreadId:(long)threadId
withBody:(NSString *)body;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,43 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/***
* This is a bridge file for Audience Network Unity SDK.
*
* Please refer to FBAdSettings.h for full documentation of the API.
*
* This file may be used to build your own Audience Network iOS SDK wrapper,
* but note that we don't support customisations of the Audience Network codebase.
*
***/
#import <FBAudienceNetwork/FBAdBridgeCommon.h>
NS_ASSUME_NONNULL_BEGIN
FB_EXTERN_C_BEGIN
FB_EXPORT void FBAdSettingsBridgeAddTestDevice(char const *deviceID);
FB_EXPORT void FBAdSettingsBridgeSetURLPrefix(char const *urlPrefix);
FB_EXPORT void FBAdSettingsBridgeSetIsChildDirected(bool isChildDirected);
FB_EXPORT void FBAdSettingsBridgeSetMixedAudience(bool mixedAudience);
FB_EXPORT char const *__nullable FBAdSettingsBridgeGetBidderToken(void);
FB_EXTERN_C_END
NS_ASSUME_NONNULL_END

View file

@ -1,62 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
NS_ASSUME_NONNULL_BEGIN
/// Represents the ad size.
struct FBAdSize {
/// Internal size
CGSize size;
};
/// Represents the ad size.
typedef struct FBAdSize FBAdSize;
/**
DEPRECATED - Represents the fixed banner ad size - 320pt by 50pt.
*/
FB_EXPORT FBAdSize const kFBAdSize320x50;
/**
Represents the flexible banner ad size, where banner width depends on
its container width, and banner height is fixed as 50pt.
*/
FB_EXPORT FBAdSize const kFBAdSizeHeight50Banner;
/**
Represents the flexible banner ad size, where banner width depends on
its container width, and banner height is fixed as 90pt.
*/
FB_EXPORT FBAdSize const kFBAdSizeHeight90Banner;
/**
Represents the interstitial ad size.
*/
FB_EXPORT FBAdSize const kFBAdSizeInterstitial;
/**
Represents the flexible rectangle ad size, where width depends on
its container width, and height is fixed as 250pt.
*/
FB_EXPORT FBAdSize const kFBAdSizeHeight250Rectangle;
NS_ASSUME_NONNULL_END

View file

@ -1,40 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/***
* This is a bridge file for Audience Network Unity SDK.
*
* Please refer to FBAdScreen.h for full documentation of the API.
*
* This file may be used to build your own Audience Network iOS SDK wrapper,
* but note that we don't support customisations of the Audience Network codebase.
*
***/
#import <FBAudienceNetwork/FBAdBridgeCommon.h>
FB_EXTERN_C_BEGIN
FB_EXPORT double FBAdUtilityBridgeGetDeviceWidth(void);
FB_EXPORT double FBAdUtilityBridgeGetDeviceHeight(void);
FB_EXPORT double FBAdUtilityBridgeGetWidth(void);
FB_EXPORT double FBAdUtilityBridgeGetHeight(void);
FB_EXPORT double FBAdUtilityBridgeConvertFromDeviceSize(double deviceSize);
FB_EXTERN_C_END

View file

@ -1,161 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdExtraHint.h>
#import <FBAudienceNetwork/FBAdSize.h>
NS_ASSUME_NONNULL_BEGIN
@protocol FBAdViewDelegate;
/**
A customized UIView to represent a Facebook ad (a.k.a. banner ad).
*/
FB_CLASS_EXPORT
@interface FBAdView : UIView
/**
This is a method to initialize an FBAdView matching the given placement id.
@param placementID The id of the ad placement. You can create your placement id from Facebook developers page.
@param adSize The size of the ad; for example, kFBAdSizeHeight50Banner or kFBAdSizeHeight90Banner.
@param rootViewController The view controller that will be used to present the ad and the app store view.
*/
- (instancetype)initWithPlacementID:(NSString *)placementID
adSize:(FBAdSize)adSize
rootViewController:(nullable UIViewController *)rootViewController NS_DESIGNATED_INITIALIZER;
/**
This is a method to initialize an FBAdView matching the given placement id with a given bidding payload.
@param placementID The id of the ad placement. You can create your placement id from Facebook developers page.
@param bidPayload The bid payload sent from the server.
@param rootViewController The view controller that will be used to present the ad and the app store view.
@param error An out value that returns any error encountered during init.
*/
- (nullable instancetype)initWithPlacementID:(NSString *)placementID
bidPayload:(NSString *)bidPayload
rootViewController:(nullable UIViewController *)rootViewController
error:(NSError *__autoreleasing *)error;
/**
Begins loading the FBAdView content.
You can implement `adViewDidLoad:` and `adView:didFailWithError:` methods
of `FBAdViewDelegate` if you would like to be notified as loading succeeds or fails.
*/
- (void)loadAd;
/**
Begins loading the FBAdView content from a bid payload attained through a server side bid.
You can implement `adViewDidLoad:` and `adView:didFailWithError:` methods
of `FBAdViewDelegate` if you would like to be notified as loading succeeds or fails.
@param bidPayload The payload of the ad bid. You can get your bid id from Facebook bidder endpoint.
*/
- (void)loadAdWithBidPayload:(NSString *)bidPayload;
/**
There is no reason to call this method anymore. Autorefresh is disabled by default.
*/
- (void)disableAutoRefresh FB_DEPRECATED;
/**
Typed access to the id of the ad placement.
*/
@property (nonatomic, copy, readonly) NSString *placementID;
/**
Typed access to the app's root view controller.
*/
@property (nonatomic, weak, readonly, nullable) UIViewController *rootViewController;
/**
Call isAdValid to check whether ad is valid
*/
@property (nonatomic, getter=isAdValid, readonly) BOOL adValid;
/**
the delegate
*/
@property (nonatomic, weak, nullable) id<FBAdViewDelegate> delegate;
/**
FBAdExtraHint to provide extra info
*/
@property (nonatomic, strong, nullable) FBAdExtraHint *extraHint;
@end
/**
The methods declared by the FBAdViewDelegate protocol allow the adopting delegate to respond
to messages from the FBAdView class and thus respond to operations such as whether the ad has
been loaded, the person has clicked the ad.
*/
@protocol FBAdViewDelegate <NSObject>
@optional
/**
Sent after an ad has been clicked by the person.
@param adView An FBAdView object sending the message.
*/
- (void)adViewDidClick:(FBAdView *)adView;
/**
When an ad is clicked, the modal view will be presented. And when the user finishes the
interaction with the modal view and dismiss it, this message will be sent, returning control
to the application.
@param adView An FBAdView object sending the message.
*/
- (void)adViewDidFinishHandlingClick:(FBAdView *)adView;
/**
Sent when an ad has been successfully loaded.
@param adView An FBAdView object sending the message.
*/
- (void)adViewDidLoad:(FBAdView *)adView;
/**
Sent after an FBAdView fails to load the ad.
@param adView An FBAdView object sending the message.
@param error An error object containing details of the error.
*/
- (void)adView:(FBAdView *)adView didFailWithError:(NSError *)error;
/**
Sent immediately before the impression of an FBAdView object will be logged.
@param adView An FBAdView object sending the message.
*/
- (void)adViewWillLogImpression:(FBAdView *)adView;
/**
Asks the delegate for a view controller to present modal content, such as the in-app
browser that can appear when an ad is clicked.
@return A view controller that is used to present modal content.
*/
@property (nonatomic, readonly, strong) UIViewController *viewControllerForPresentingModalView;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,62 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/***
* This is a bridge file for Audience Network Unity SDK.
*
* Please refer to FBAdView.h and FBAdExtraHint.h for full documentation of the API.
*
* This file may be used to build your own Audience Network iOS SDK wrapper,
* but note that we don't support customisations of the Audience Network codebase.
*
***/
#import <FBAudienceNetwork/FBAdBridgeCommon.h>
FB_EXTERN_C_BEGIN
typedef NS_ENUM(int32_t, FBAdViewBridgeSize) {
FBAdViewBridgeSizeHeight50BannerKey,
FBAdViewBridgeSizeHeight90BannerKey,
FBAdViewBridgeSizeInterstitalKey,
FBAdViewBridgeSizeHeight250RectangleKey
};
FB_EXPORT int32_t FBAdViewBridgeSizeHeight50Banner(void);
FB_EXPORT int32_t FBAdViewBridgeSizeHeight90Banner(void);
FB_EXPORT int32_t FBAdViewBridgeSizeInterstital(void);
FB_EXPORT int32_t FBAdViewBridgeSizeHeight250Rectangle(void);
FB_EXPORT int32_t FBAdViewBridgeCreate(char const *placementID, FBAdViewBridgeSize size);
FB_EXPORT int32_t FBAdViewBridgeLoad(int32_t uniqueId);
FB_EXPORT int32_t FBAdViewBridgeLoadWithBidPayload(int32_t uniqueId, char *bidPayload);
FB_EXPORT bool FBAdViewBridgeIsValid(int32_t uniqueId);
FB_EXPORT void FBAdViewBridgeShow(int32_t uniqueId, double x, double y, double width, double height);
FB_EXPORT char const *FBAdViewBridgeGetPlacementId(int32_t uniqueId);
FB_EXPORT void FBAdViewBridgeDisableAutoRefresh(int32_t uniqueId);
FB_EXPORT void FBAdViewBridgeSetExtraHints(int32_t uniqueId, char const *extraHints);
FB_EXPORT void FBAdViewBridgeRelease(int32_t uniqueId);
FB_EXPORT void FBAdViewBridgeOnLoad(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBAdViewBridgeOnImpression(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBAdViewBridgeOnClick(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBAdViewBridgeOnError(int32_t uniqueId, FBAdBridgeErrorCallback callback);
FB_EXPORT void FBAdViewBridgeOnFinishedClick(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXTERN_C_END

View file

@ -1,60 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdChoicesView.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdExperienceConfig.h>
#import <FBAudienceNetwork/FBAdExtraHint.h>
#import <FBAudienceNetwork/FBAdIconView.h>
#import <FBAudienceNetwork/FBAdOptionsView.h>
#import <FBAudienceNetwork/FBAdSettings.h>
#import <FBAudienceNetwork/FBAdView.h>
#import <FBAudienceNetwork/FBAudienceNetworkAds.h>
#import <FBAudienceNetwork/FBInstreamAdView.h>
#import <FBAudienceNetwork/FBInterstitialAd.h>
#import <FBAudienceNetwork/FBMediaView.h>
#import <FBAudienceNetwork/FBMediaViewVideoRenderer.h>
#import <FBAudienceNetwork/FBNativeAd.h>
#import <FBAudienceNetwork/FBNativeAdCollectionViewAdProvider.h>
#import <FBAudienceNetwork/FBNativeAdCollectionViewCellProvider.h>
#import <FBAudienceNetwork/FBNativeAdScrollView.h>
#import <FBAudienceNetwork/FBNativeAdTableViewAdProvider.h>
#import <FBAudienceNetwork/FBNativeAdTableViewCellProvider.h>
#import <FBAudienceNetwork/FBNativeAdView.h>
#import <FBAudienceNetwork/FBNativeAdsManager.h>
#import <FBAudienceNetwork/FBNativeBannerAd.h>
#import <FBAudienceNetwork/FBNativeBannerAdView.h>
#import <FBAudienceNetwork/FBRewardedVideoAd.h>
#import <FBAudienceNetwork/UIView+FBNativeAdViewTag.h>
// Unity Bridge
#import <FBAudienceNetwork/FBAdBridgeCommon.h>
#import <FBAudienceNetwork/FBAdBridgeContainer.h>
#import <FBAudienceNetwork/FBAdSettingsBridge.h>
#import <FBAudienceNetwork/FBAdUtilityBridge.h>
#import <FBAudienceNetwork/FBAdViewBridge.h>
#import <FBAudienceNetwork/FBInterstitialAdBridge.h>
#import <FBAudienceNetwork/FBRewardedVideoAdBridge.h>
// NOTE: Any changes should also be made to the module.modulemap
// to ensure comptability with Swift apps using Cocoapods
#define FB_AD_SDK_VERSION @"5.9.0"

View file

@ -1,103 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <FBAudienceNetwork/FBAdDefines.h>
NS_ASSUME_NONNULL_BEGIN
/**
FBAdInitSettings is an object to incapsulate all the settings you can pass to SDK on initialization call.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBAdInitSettings : NSObject
/**
Designated initializer for FBAdInitSettings
If an ad provided service is mediating Audience Network in their sdk, it is required to set the name of the mediation
service
@param placementIDs An array of placement identifiers.
@param mediationService String to identify mediation provider.
*/
- (instancetype)initWithPlacementIDs:(NSArray<NSString *> *)placementIDs mediationService:(NSString *)mediationService;
/**
An array of placement identifiers.
*/
@property (nonatomic, copy, readonly) NSArray<NSString *> *placementIDs;
/**
String to identify mediation provider.
*/
@property (nonatomic, copy, readonly) NSString *mediationService;
@end
/**
FBAdInitResults is an object to incapsulate all the results you'll get as a result of SDK initialization call.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBAdInitResults : NSObject
/**
Boolean which says whether initialization was successful
*/
@property (nonatomic, assign, readonly, getter=isSuccess) BOOL success;
/**
Message which provides more details about initialization result
*/
@property (nonatomic, copy, readonly) NSString *message;
@end
/**
FBAudienceNetworkAds is an entry point to AN SDK.
*/
typedef NS_ENUM(NSInteger, FBAdFormatTypeName) {
FBAdFormatTypeNameUnknown = 0,
FBAdFormatTypeNameBanner,
FBAdFormatTypeNameInterstitial,
FBAdFormatTypeNameInstream,
FBAdFormatTypeNameNative,
FBAdFormatTypeNameNativeBanner,
FBAdFormatTypeNameRewardedVideo,
};
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBAudienceNetworkAds : NSObject
/**
Initialize Audience Network SDK at any given point of time. It will be called automatically with default settigs when
you first touch AN related code otherwise.
@param settings The settings to initialize with
@param completionHandler The block which will be called when initialization finished
*/
+ (void)initializeWithSettings:(nullable FBAdInitSettings *)settings
completionHandler:(nullable void (^)(FBAdInitResults *results))completionHandler;
/**
Returns ad format type name for a given placement id.
@param placementId Placement id that is configured for the current app.
*/
+ (FBAdFormatTypeName)adFormatTypeNameForPlacementId:(NSString *)placementId;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,147 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdExtraHint.h>
NS_ASSUME_NONNULL_BEGIN
@protocol FBInstreamAdViewDelegate;
/**
A customized UIView to display an instream video ad by Facebook.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBInstreamAdView : UIView
/**
Returns YES if the instream ad has been successfully loaded.
Note that the `adView:didFailWithError:` delegate method will be also be called
instead of `adViewDidLoad:` if the ad fails to load for any reason.
*/
@property (nonatomic, getter=isAdValid, readonly) BOOL adValid;
/**
This property must be set prior to calling `loadAd`, so that delegate method calls
are received and handled.
*/
@property (nonatomic, weak, nullable) id<FBInstreamAdViewDelegate> delegate;
/**
Typed access to the id of the ad placement.
*/
@property (nonatomic, copy, readonly) NSString *placementID;
/**
FBAdExtraHint to provide extra info
*/
@property (nonatomic, strong, nullable) FBAdExtraHint *extraHint;
/**
Initializes and returns a newly allocated FBInstreamAdView object with the
given placement id.
@param placementID The id of the ad placement. You can create your placement id from Facebook developers page.
*/
- (nullable instancetype)initWithPlacementID:(NSString *)placementID NS_DESIGNATED_INITIALIZER;
/**
Begins loading ad content.
You should implement `adViewDidLoad:` and `adView:didFailWithError:` methods
of `FBInstreamAdViewDelegate` to be notified when loading succeeds or fails.
*/
- (void)loadAd;
/**
Begins loading ad content from a bid payload attained through a server side bid.
You can implement `adViewDidLoad:` and `adView:didFailWithError:` methods
of `FBInstreamAdViewDelegate` to be notified when loading succeeds or fails.
@param bidPayload The payload of the ad bid. You can get your bid id from Facebook bidder endpoint.
*/
- (void)loadAdWithBidPayload:(NSString *)bidPayload;
/**
Begins ad playback. This method should only be called after an `adViewDidLoad:` call
has been received.
@param rootViewController The view controller that will be used to modally
present additional view controllers, to render the ad's landing page for example.
*/
- (BOOL)showAdFromRootViewController:(nullable UIViewController *)rootViewController;
@end
/**
The FBInstreamAdViewDelegate protocol defines methods that allow the owner of an
FBInstreamAdView to respond to various stages of ad operation.
*/
@protocol FBInstreamAdViewDelegate <NSObject>
/**
Sent when an FBInstreamAdView instance successfully loads an ad.
@param adView The FBInstreamAdView object sending the message.
*/
- (void)adViewDidLoad:(FBInstreamAdView *)adView;
/**
Sent when ad playback has completed and the FBInstreamAdView is ready to be
deallocated. This method is mutually exclusive to `adView:didFailWithError:`, and
it is impossible for both methods to be received for a single ad session.
@param adView The FBInstreamAdView object sending the message.
*/
- (void)adViewDidEnd:(FBInstreamAdView *)adView;
/**
Sent when ad playback has failed to load or play an ad, and the FBInstreamAdView
is ready to be deallocated. It is possible for this method to be called after
`loadAd` (if they ad fails to load) or after `showAdFromRootViewController:`
(if the ad has a playback failure).
@param adView The FBInstreamAdView object sending the message.
@param error An NSError object containing details of the error.
*/
- (void)adView:(FBInstreamAdView *)adView didFailWithError:(NSError *)error;
@optional
/**
Sent when the user has touched the click-through interface element. The ad's
landing page will be shown.
@param adView The FBInstreamAdView object sending the message.
*/
- (void)adViewDidClick:(FBInstreamAdView *)adView;
/**
Sent immediately before the impression of an FBInstreamAdView object will be logged.
@param adView The FBInstreamAdView object sending the message.
*/
- (void)adViewWillLogImpression:(FBInstreamAdView *)adView;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,152 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdExtraHint.h>
#import <FBAudienceNetwork/FBAdView.h>
NS_ASSUME_NONNULL_BEGIN
@protocol FBInterstitialAdDelegate;
/**
A modal view controller to represent a Facebook interstitial ad. This
is a full-screen ad shown in your application.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBInterstitialAd : NSObject
/**
Typed access to the id of the ad placement.
*/
@property (nonatomic, copy, readonly) NSString *placementID;
/**
the delegate
*/
@property (nonatomic, weak, nullable) id<FBInterstitialAdDelegate> delegate;
/**
FBAdExtraHint to provide extra info
*/
@property (nonatomic, strong, nullable) FBAdExtraHint *extraHint;
/**
This is a method to initialize an FBInterstitialAd matching the given placement id.
@param placementID The id of the ad placement. You can create your placement id from Facebook developers page.
*/
- (instancetype)initWithPlacementID:(NSString *)placementID NS_DESIGNATED_INITIALIZER;
/**
Returns true if the interstitial ad has been successfully loaded.
You should check `isAdValid` before trying to show the ad.
*/
@property (nonatomic, getter=isAdValid, readonly) BOOL adValid;
/**
Begins loading the FBInterstitialAd content.
You can implement `interstitialAdDidLoad:` and `interstitialAd:didFailWithError:` methods
of `FBInterstitialAdDelegate` if you would like to be notified as loading succeeds or fails.
*/
- (void)loadAd;
/**
Begins loading the FBInterstitialAd content from a bid payload attained through a server side bid.
You can implement `adViewDidLoad:` and `adView:didFailWithError:` methods
of `FBAdViewDelegate` if you would like to be notified as loading succeeds or fails.
@param bidPayload The payload of the ad bid. You can get your bid id from Facebook bidder endpoint.
*/
- (void)loadAdWithBidPayload:(NSString *)bidPayload;
/**
Presents the interstitial ad modally from the specified view controller.
@param rootViewController The view controller that will be used to present the interstitial ad.
You can implement `interstitialAdDidClick:`, `interstitialAdWillClose:` and `interstitialAdWillClose`
methods of `FBInterstitialAdDelegate` if you would like to stay informed for thoses events
*/
- (BOOL)showAdFromRootViewController:(nullable UIViewController *)rootViewController;
@end
/**
The methods declared by the FBInterstitialAdDelegate protocol allow the adopting delegate to respond
to messages from the FBInterstitialAd class and thus respond to operations such as whether the
interstitial ad has been loaded, user has clicked or closed the interstitial.
*/
@protocol FBInterstitialAdDelegate <NSObject>
@optional
/**
Sent after an ad in the FBInterstitialAd object is clicked. The appropriate app store view or
app browser will be launched.
@param interstitialAd An FBInterstitialAd object sending the message.
*/
- (void)interstitialAdDidClick:(FBInterstitialAd *)interstitialAd;
/**
Sent after an FBInterstitialAd object has been dismissed from the screen, returning control
to your application.
@param interstitialAd An FBInterstitialAd object sending the message.
*/
- (void)interstitialAdDidClose:(FBInterstitialAd *)interstitialAd;
/**
Sent immediately before an FBInterstitialAd object will be dismissed from the screen.
@param interstitialAd An FBInterstitialAd object sending the message.
*/
- (void)interstitialAdWillClose:(FBInterstitialAd *)interstitialAd;
/**
Sent when an FBInterstitialAd successfully loads an ad.
@param interstitialAd An FBInterstitialAd object sending the message.
*/
- (void)interstitialAdDidLoad:(FBInterstitialAd *)interstitialAd;
/**
Sent when an FBInterstitialAd failes to load an ad.
@param interstitialAd An FBInterstitialAd object sending the message.
@param error An error object containing details of the error.
*/
- (void)interstitialAd:(FBInterstitialAd *)interstitialAd didFailWithError:(NSError *)error;
/**
Sent immediately before the impression of an FBInterstitialAd object will be logged.
@param interstitialAd An FBInterstitialAd object sending the message.
*/
- (void)interstitialAdWillLogImpression:(FBInterstitialAd *)interstitialAd;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,50 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/***
* This is a bridge file for Audience Network Unity SDK.
*
* Please refer to FBInterstitialAd.h and FBAdExtraHint.h for full documentation of the API.
*
* This file may be used to build your own Audience Network iOS SDK wrapper,
* but note that we don't support customisations of the Audience Network codebase.
*
***/
#import <FBAudienceNetwork/FBAdBridgeCommon.h>
FB_EXTERN_C_BEGIN
FB_EXPORT int32_t FBInterstitialAdBridgeCreate(char const *placementID);
FB_EXPORT int32_t FBInterstitialAdBridgeLoad(int32_t uniqueId);
FB_EXPORT int32_t FBInterstitialAdBridgeLoadWithBidPayload(int32_t uniqueId, char *bidPayload);
FB_EXPORT bool FBInterstitialAdBridgeIsValid(int32_t uniqueId);
FB_EXPORT char const *FBInterstitialAdBridgeGetPlacementId(int32_t uniqueId);
FB_EXPORT bool FBInterstitialAdBridgeShow(int32_t uniqueId);
FB_EXPORT void FBInterstitialAdBridgeSetExtraHints(int32_t uniqueId, char const *extraHints);
FB_EXPORT void FBInterstitialAdBridgeRelease(int32_t uniqueId);
FB_EXPORT void FBInterstitialAdBridgeOnLoad(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBInterstitialAdBridgeOnImpression(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBInterstitialAdBridgeOnClick(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBInterstitialAdBridgeOnError(int32_t uniqueId, FBAdBridgeErrorCallback callback);
FB_EXPORT void FBInterstitialAdBridgeOnDidClose(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBInterstitialAdBridgeOnWillClose(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXTERN_C_END

View file

@ -1,140 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBMediaViewVideoRenderer.h>
#import <FBAudienceNetwork/UIView+FBNativeAdViewTag.h>
NS_ASSUME_NONNULL_BEGIN
@protocol FBMediaViewDelegate;
@class FBNativeAd;
/**
The FBMediaView loads media content from a given FBNativeAd. This view takes the place of manually loading a cover
image.
*/
FB_CLASS_EXPORT
@interface FBMediaView : UIView
/**
the delegate
*/
@property (nonatomic, weak, nullable) id<FBMediaViewDelegate> delegate;
/**
A custom FBMediaViewVideoRenderer instance, used to override the default user experience of video ads.
The video renderer can only be set prior to registering the mediaView to a nativeAd
*/
@property (nonatomic, strong) FBMediaViewVideoRenderer *videoRenderer;
/**
The current volume of the media view, ranging from 0.0 through 1.0.
*/
@property (nonatomic, assign, readonly) float volume;
/**
Shows if the video will autoplay or not
*/
@property (nonatomic, readonly, getter=isAutoplayEnabled) BOOL autoplayEnabled;
/**
The aspect ratio of the media view visual content. Returns a positive CGFloat, or 0.0 if no ad is currently loaded.
*/
@property (nonatomic, assign, readonly) CGFloat aspectRatio;
/**
The tag for media view. It always returns FBNativeAdViewTagMedia.
*/
@property (nonatomic, assign, readonly) FBNativeAdViewTag nativeAdViewTag;
/**
Changes the width of the FBMediaView's frame based on the current height, respecting aspectRatio.
*/
- (void)applyNaturalWidth;
/**
Changes the height of the FBMediaView's frame based on the current width, respecting aspectRatio.
*/
- (void)applyNaturalHeight;
@end
/**
The methods declared by the FBMediaViewDelegate protocol allow the adopting delegate to respond to messages from the
FBMediaView class and thus respond to operations such as whether the media content has been loaded.
*/
@protocol FBMediaViewDelegate <NSObject>
@optional
/**
Sent when an FBMediaView has been successfully loaded.
@param mediaView An FBMediaView object sending the message.
*/
- (void)mediaViewDidLoad:(FBMediaView *)mediaView;
/**
Sent just before an FBMediaView will enter the fullscreen layout.
@param mediaView An FBMediaView object sending the message.
*/
- (void)mediaViewWillEnterFullscreen:(FBMediaView *)mediaView;
/**
Sent after an FBMediaView has exited the fullscreen layout.
@param mediaView An FBMediaView object sending the message.
*/
- (void)mediaViewDidExitFullscreen:(FBMediaView *)mediaView;
/**
Sent when an FBMediaView has changed the playback volume of a video ad.
@param mediaView An FBMediaView object sending the message.
@param volume The current ad video volume (after the volume change).
*/
- (void)mediaView:(FBMediaView *)mediaView videoVolumeDidChange:(float)volume;
/**
Sent after a video ad in an FBMediaView enters a paused state.
@param mediaView An FBMediaView object sending the message.
*/
- (void)mediaViewVideoDidPause:(FBMediaView *)mediaView;
/**
Sent after a video ad in an FBMediaView enters a playing state.
@param mediaView An FBMediaView object sending the message.
*/
- (void)mediaViewVideoDidPlay:(FBMediaView *)mediaView;
/**
Sent when a video ad in an FBMediaView reaches the end of playback.
@param mediaView An FBMediaView object sending the message.
*/
- (void)mediaViewVideoDidComplete:(FBMediaView *)mediaView;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,149 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
NS_ASSUME_NONNULL_BEGIN
/**
The FBMediaViewVideoRenderer class allows for customization of the user experience for video ads in FBMediaView. This
class should be subclassed, and an instance of that subclass should be passed to the videoRenderer property of an
FBMediaView instance.
*/
FB_CLASS_EXPORT
@interface FBMediaViewVideoRenderer : UIView
/**
The aspect ratio of the video content. Returns a positive CGFloat, or 0.0 if no ad is currently loaded.
*/
@property (nonatomic, assign, readonly) CGFloat aspectRatio;
/**
The current video playback time, as a CMTime value.
*/
@property (nonatomic, assign, readonly) CMTime currentTime;
/**
The duration of the video, as a CMTime value. Returns kCMTimeIndefinite if no video is loaded.
*/
@property (nonatomic, assign, readonly) CMTime duration;
/**
Indicates whether the video is currently playing.
*/
@property (nonatomic, assign, readonly, getter=isPlaying) BOOL playing;
/**
The current volume of the video, ranging from 0.0 through 1.0.
*/
@property (nonatomic, assign) float volume;
/**
Starts or resumes video playback.
*/
- (void)playVideo;
/**
Pauses video playback.
*/
- (void)pauseVideo;
/**
Used to put the video into seek mode. Video playback halts, and one or more calls to seekVideoToTime: can be made
before calling disengageVideoSeek.
*/
- (void)engageVideoSeek;
/**
Take the video out of seek mode.
*/
- (void)disengageVideoSeek;
/**
Seeks the video to a particular time location. Only works after calling `engageVideoSeek`.
@param time The requested time location, expressed as a CMTime value.
*/
- (void)seekVideoToTime:(CMTime)time;
/**
Requests the periodic invocation of a given block during playback to report changing time.
@param interval The time interval at which the block should be invoked during normal playback, according to progress of
the player's current time.
@param queue A serial dispatch queue onto which block should be enqueued.
@param block The block to be invoked periodically.
*/
- (nullable id)addPeriodicTimeObserverForInterval:(CMTime)interval
queue:(dispatch_queue_t)queue
usingBlock:(void (^)(CMTime time))block;
/**
Cancels a previously registered periodic time observer.
*/
- (void)removeTimeObserver:(id)observer;
/**
Called when the video volume has changed.
*/
- (void)videoDidChangeVolume;
/**
Called when video content has loaded.
*/
- (void)videoDidLoad;
/**
Called when video playback was paused.
*/
- (void)videoDidPause;
/**
Called when video playback has begun or was resumed.
*/
- (void)videoDidPlay;
/**
Called when seek mode was engaged.
*/
- (void)videoDidEngageSeek;
/**
Called when a video seek was performed.
*/
- (void)videoDidSeek;
/**
Called when seek mode was disengaged.
*/
- (void)videoDidDisengageSeek;
/**
Called when video playback ends.
*/
- (void)videoDidEnd;
/**
Called when video playback encounters an error.
*/
- (void)videoDidFailWithError:(NSError *)error;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,171 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdSettings.h>
#import <FBAudienceNetwork/FBNativeAdBase.h>
#import "FBAdImage.h"
NS_ASSUME_NONNULL_BEGIN
@protocol FBNativeAdDelegate;
/**
The FBNativeAd represents ad metadata to allow you to construct custom ad views.
See the AdUnitsSample in the sample apps section of the Audience Network framework.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBNativeAd : FBNativeAdBase
/**
the delegate
*/
@property (nonatomic, weak, nullable) id<FBNativeAdDelegate> delegate;
- (instancetype)initWithPlacementID:(NSString *)placementID;
/**
This is a method to associate a FBNativeAd with the UIView you will use to display the native ads.
@param view The UIView you created to render all the native ads data elements.
@param mediaView The FBMediaView you created to render the media (cover image / video / carousel)
@param iconView The FBMediaView you created to render the icon
@param viewController The UIViewController that will be used to present SKStoreProductViewController
(iTunes Store product information) or the in-app browser. If nil is passed, the top view controller currently shown
will be used. The whole area of the UIView will be clickable.
*/
- (void)registerViewForInteraction:(UIView *)view
mediaView:(FBMediaView *)mediaView
iconView:(nullable FBMediaView *)iconView
viewController:(nullable UIViewController *)viewController;
/**
This is a method to associate FBNativeAd with the UIView you will use to display the native ads
and set clickable areas.
@param view The UIView you created to render all the native ads data elements.
@param mediaView The FBMediaView you created to render the media (cover image / video / carousel)
@param iconView The FBMediaView you created to render the icon
@param viewController The UIViewController that will be used to present SKStoreProductViewController
(iTunes Store product information). If nil is passed, the top view controller currently shown will be used.
@param clickableViews An array of UIView you created to render the native ads data element, e.g.
CallToAction button, Icon image, which you want to specify as clickable.
*/
- (void)registerViewForInteraction:(UIView *)view
mediaView:(FBMediaView *)mediaView
iconView:(nullable FBMediaView *)iconView
viewController:(nullable UIViewController *)viewController
clickableViews:(nullable NSArray<UIView *> *)clickableViews;
/**
This is a method to associate a FBNativeAd with the UIView you will use to display the native ads.
@param view The UIView you created to render all the native ads data elements.
@param mediaView The FBMediaView you created to render the media (cover image / video / carousel)
@param iconImageView The UIImageView you created to render the icon
@param viewController The UIViewController that will be used to present SKStoreProductViewController
(iTunes Store product information) or the in-app browser. If nil is passed, the top view controller currently shown
will be used. The whole area of the UIView will be clickable.
*/
- (void)registerViewForInteraction:(UIView *)view
mediaView:(FBMediaView *)mediaView
iconImageView:(nullable UIImageView *)iconImageView
viewController:(nullable UIViewController *)viewController;
/**
This is a method to associate FBNativeAd with the UIView you will use to display the native ads
and set clickable areas.
@param view The UIView you created to render all the native ads data elements.
@param mediaView The FBMediaView you created to render the media (cover image / video / carousel)
@param iconImageView The UIImageView you created to render the icon. Image will be set
@param viewController The UIViewController that will be used to present SKStoreProductViewController
(iTunes Store product information). If nil is passed, the top view controller currently shown will be used.
@param clickableViews An array of UIView you created to render the native ads data element, e.g.
CallToAction button, Icon image, which you want to specify as clickable.
*/
- (void)registerViewForInteraction:(UIView *)view
mediaView:(FBMediaView *)mediaView
iconImageView:(nullable UIImageView *)iconImageView
viewController:(nullable UIViewController *)viewController
clickableViews:(nullable NSArray<UIView *> *)clickableViews;
/**
This is a method to use to download all media for the ad (adChoicesIcon, icon, image, video).
This is only needed to be called if the mediaCachePolicy is set to FBNativeAdsCachePolicyNone.
*/
- (void)downloadMedia;
@end
/**
The methods declared by the FBNativeAdDelegate protocol allow the adopting delegate to respond to messages
from the FBNativeAd class and thus respond to operations such as whether the native ad has been loaded.
*/
@protocol FBNativeAdDelegate <NSObject>
@optional
/**
Sent when an FBNativeAd has been successfully loaded.
@param nativeAd An FBNativeAd object sending the message.
*/
- (void)nativeAdDidLoad:(FBNativeAd *)nativeAd;
/**
Sent when an FBNativeAd has succesfully downloaded all media
*/
- (void)nativeAdDidDownloadMedia:(FBNativeAd *)nativeAd;
/**
Sent immediately before the impression of an FBNativeAd object will be logged.
@param nativeAd An FBNativeAd object sending the message.
*/
- (void)nativeAdWillLogImpression:(FBNativeAd *)nativeAd;
/**
Sent when an FBNativeAd is failed to load.
@param nativeAd An FBNativeAd object sending the message.
@param error An error object containing details of the error.
*/
- (void)nativeAd:(FBNativeAd *)nativeAd didFailWithError:(NSError *)error;
/**
Sent after an ad has been clicked by the person.
@param nativeAd An FBNativeAd object sending the message.
*/
- (void)nativeAdDidClick:(FBNativeAd *)nativeAd;
/**
When an ad is clicked, the modal view will be presented. And when the user finishes the
interaction with the modal view and dismiss it, this message will be sent, returning control
to the application.
@param nativeAd An FBNativeAd object sending the message.
*/
- (void)nativeAdDidFinishHandlingClick:(FBNativeAd *)nativeAd;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,206 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdExtraHint.h>
#import "FBAdSettings.h"
typedef NS_ENUM(NSInteger, FBAdFormatType) {
FBAdFormatTypeUnknown = 0,
FBAdFormatTypeImage,
FBAdFormatTypeVideo,
FBAdFormatTypeCarousel
};
NS_ASSUME_NONNULL_BEGIN
@class FBAdIconView;
@class FBAdImage;
@class FBAdPlacementDefinition;
@class FBAdProvider;
@class FBMediaView;
@class FBNativeAdDataModel;
@class FBNativeAdViewAttributes;
/**
Determines if caching of the ad's assets should be done before calling adDidLoad
*/
typedef NS_ENUM(NSInteger, FBNativeAdsCachePolicy) {
/// No ad content is cached
FBNativeAdsCachePolicyNone,
/// All content is cached
FBNativeAdsCachePolicyAll,
};
/**
The Internal representation of an Ad
*/
@interface FBNativeAdBase : NSObject
/**
Typed access to the id of the ad placement.
*/
@property (nonatomic, copy, readonly) NSString *placementID;
/**
Typed access to the headline that the advertiser entered when they created their ad. This is usually the ad's main
title.
*/
@property (nonatomic, copy, readonly, nullable) NSString *headline;
/**
Typed access to the link description which is additional information that the advertiser may have entered.
*/
@property (nonatomic, copy, readonly, nullable) NSString *linkDescription;
/**
Typed access to the name of the Facebook Page or mobile app that represents the business running the ad.
*/
@property (nonatomic, copy, readonly, nullable) NSString *advertiserName;
/**
Typed access to the ad social context, for example "Over half a million users".
*/
@property (nonatomic, copy, readonly, nullable) NSString *socialContext;
/**
Typed access to the call to action phrase of the ad, for example "Install Now".
*/
@property (nonatomic, copy, readonly, nullable) NSString *callToAction;
/**
Typed access to the body raw untruncated text, Contains the text that the advertiser entered when they created their
ad. This often tells people what the ad is promoting.
*/
@property (nonatomic, copy, readonly, nullable) NSString *rawBodyText;
/**
Typed access to the body text, truncated at length 90, which contains the text that the advertiser entered when they
created their ad. This often tells people what the ad is promoting.
*/
@property (nonatomic, copy, readonly, nullable) NSString *bodyText;
/**
Typed access to the word 'sponsored', translated into the language being used by the person viewing the ad.
*/
@property (nonatomic, copy, readonly, nullable) NSString *sponsoredTranslation;
/**
Typed access to the word 'ad', translated into the language being used by the person viewing the ad.
*/
@property (nonatomic, copy, readonly, nullable) NSString *adTranslation;
/**
Typed access to the word 'promoted', translated into the language being used by the person viewing the ad.
*/
@property (nonatomic, copy, readonly, nullable) NSString *promotedTranslation;
/**
Typed access to the AdChoices icon. See `FBAdImage` for details. See `FBAdChoicesView` for an included implementation.
*/
@property (nonatomic, strong, readonly, nullable) FBAdImage *adChoicesIcon;
/**
Typed access to the icon image. Only available after ad is successfully loaded.
*/
@property (nonatomic, strong, readonly, nullable) UIImage *iconImage;
/**
Aspect ratio of the ad creative.
*/
@property (nonatomic, assign, readonly) CGFloat aspectRatio;
/**
Typed access to the AdChoices URL. Navigate to this link when the icon is tapped. See `FBAdChoicesView` for an included
implementation.
*/
@property (nonatomic, copy, readonly, nullable) NSURL *adChoicesLinkURL;
/**
Typed access to the AdChoices text, usually a localized version of "AdChoices". See `FBAdChoicesView` for an included
implementation.
*/
@property (nonatomic, copy, readonly, nullable) NSString *adChoicesText;
/**
Typed access to the ad format type. See `FBAdFormatType` enum for more details.
*/
@property (nonatomic, assign, readonly) FBAdFormatType adFormatType;
/**
Read only access to native ad caching policy, it is set in loadAWithMediaCachePolicy:
*/
@property (nonatomic, readonly) FBNativeAdsCachePolicy mediaCachePolicy;
/**
Call isAdValid to check whether native ad is valid & internal consistent prior rendering using its properties. If
rendering is done as part of the loadAd callback, it is guarantee to be consistent
*/
@property (nonatomic, getter=isAdValid, readonly) BOOL adValid;
@property (nonatomic, getter=isRegistered, readonly) BOOL registered;
/**
FBAdExtraHint to provide extra info
*/
@property (nonatomic, strong, nullable) FBAdExtraHint *extraHint;
/**
This is a method to disconnect a FBNativeAd with the UIView you used to display the native ads.
*/
- (void)unregisterView;
/**
Begins loading the FBNativeAd content.
You can implement `nativeAdDidLoad:` and `nativeAd:didFailWithError:` methods
of `FBNativeAdDelegate` if you would like to be notified as loading succeeds or fails.
*/
- (void)loadAd;
/**
Begins loading the FBNativeAd content.
You can implement `nativeAdDidLoad:` and `nativeAd:didFailWithError:` methods
of `FBNativeAdDelegate` if you would like to be notified as loading succeeds or fails.
@param mediaCachePolicy controls which media (images, video, etc) from the native ad are cached before the native ad
calls nativeAdLoaded on its delegate. The default is to cache everything. Note that impression is not logged until the
media for the ad is visible on screen (Video or Image for FBNativeAd / Icon for FBNativeBannerAd) and setting this to
anything else than FBNativeAdsCachePolicyAll will delay the impression call.
*/
- (void)loadAdWithMediaCachePolicy:(FBNativeAdsCachePolicy)mediaCachePolicy;
/**
Begins loading the FBNativeAd content from a bid payload attained through a server side bid.
@param bidPayload The payload of the ad bid. You can get your bid payload from Facebook bidder endpoint.
*/
- (void)loadAdWithBidPayload:(NSString *)bidPayload;
/**
Begins loading the FBNativeAd content from a bid payload attained through a server side bid.
@param bidPayload The payload of the ad bid. You can get your bid payload from Facebook bidder endpoint.
@param mediaCachePolicy controls which media (images, video, etc) from the native ad are cached before the native ad
calls nativeAdLoaded on its delegate. The default is to cache everything. Note that impression is not logged until the
media for the ad is visible on screen (Video or Image for FBNativeAd / Icon for FBNativeBannerAd) and setting this to
anything else than FBNativeAdsCachePolicyAll will delay the impression call.
*/
- (void)loadAdWithBidPayload:(NSString *)bidPayload mediaCachePolicy:(FBNativeAdsCachePolicy)mediaCachePolicy;
/**
Creates a new instance of a FBNativeAdBase from a bid payload. The actual subclass returned will depend on the contents
of the payload.
@param placementId The placement ID of the ad.
@param bidPayload The bid payload received from the server.
@param error An out value that returns any error encountered during init.
*/
+ (nullable instancetype)nativeAdWithPlacementId:(NSString *)placementId
bidPayload:(NSString *)bidPayload
error:(NSError *__autoreleasing *)error;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,41 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBNativeAd.h>
NS_ASSUME_NONNULL_BEGIN
@class FBNativeAdViewAttributes;
/**
The FBNativeAdBaseView creates prebuilt native ad base template views and manages native ads.
*/
FB_CLASS_EXPORT
@interface FBNativeAdBaseView : UIView
/**
A view controller that is used to present modal content. If nil, the view searches for a view controller.
*/
@property (nonatomic, weak, nullable) UIViewController *rootViewController;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,96 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdExtraHint.h>
#import <FBAudienceNetwork/FBNativeAd.h>
#import <FBAudienceNetwork/FBNativeAdsManager.h>
NS_ASSUME_NONNULL_BEGIN
/**
Additional functionality on top of FBNativeAdsManager to assist in using native ads within a UICollectionView. This
class contains a mechanism to map indexPaths to native ads in a stable manner as well as helpers which assist in doing
the math to include ads at a regular interval within a collection view.
*/
FB_CLASS_EXPORT
@interface FBNativeAdCollectionViewAdProvider : NSObject
/**
Passes delegate methods from FBNativeAd. Separate delegate calls will be made for each native ad contained.
*/
@property (nonatomic, weak, nullable) id<FBNativeAdDelegate> delegate;
/**
FBAdExtraHint to provide extra info
*/
@property (nonatomic, strong, nullable) FBAdExtraHint *extraHint;
/**
Create a FBNativeAdCollectionViewAdProvider.
@param manager The FBNativeAdsManager which is consumed by this class.
*/
- (instancetype)initWithManager:(FBNativeAdsManager *)manager NS_DESIGNATED_INITIALIZER;
/**
Retrieve a native ad for an indexPath, will return the same ad for a given indexPath until the native ads manager is
refreshed. This method is intended for usage with a collection view and specifically the caller is recommended to wait
until collectionView:cellForRowAtIndexPath: to ensure getting the best native ad for the given collection cell.
@param collectionView The collectionView where native ad will be used
@param indexPath The indexPath to use as a key for this native ad
@return A FBNativeAd which is loaded and ready to be used.
*/
- (FBNativeAd *)collectionView:(UICollectionView *)collectionView nativeAdForRowAtIndexPath:(NSIndexPath *)indexPath;
/**
Support for evenly distributed native ads within a collection view. Computes whether this cell is an ad or not.
@param indexPath The indexPath of the cell within the collection view
@param stride The frequency that native ads are to appear within the collection view
@return Boolean indicating whether the cell at the path is an ad
*/
- (BOOL)isAdCellAtIndexPath:(NSIndexPath *)indexPath forStride:(NSUInteger)stride;
/**
Support for evenly distributed native ads within a collection view. Adjusts a non-ad cell indexPath to the indexPath
it would be in a collection with no ads.
@param indexPath The indexPath to of the non-ad cell
@param stride The frequency that native ads are to appear within the collection view
@return An indexPath adjusted to what it would be in a collection view with no ads
*/
- (nullable NSIndexPath *)adjustNonAdCellIndexPath:(NSIndexPath *)indexPath forStride:(NSUInteger)stride;
/**
Support for evenly distributed native ads within a collection view. Adjusts the total count of cells within the
collection view to account for the ad cells.
@param count The count of cells in the collection view not including ads
@param stride The frequency that native ads are to appear within the collection view
@return The total count of cells within the collection view including both ad and non-ad cells
*/
- (NSUInteger)adjustCount:(NSUInteger)count forStride:(NSUInteger)stride;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,72 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBNativeAd.h>
#import <FBAudienceNetwork/FBNativeAdCollectionViewAdProvider.h>
#import <FBAudienceNetwork/FBNativeAdView.h>
#import <FBAudienceNetwork/FBNativeAdsManager.h>
NS_ASSUME_NONNULL_BEGIN
/**
Class which assists in putting FBNativeAdViews into UICollectionViews. This class manages the creation of
UICollectionViewCells which host native ad views. Functionality is provided to create UICollectionCellViews as needed
for a given indexPath as well as computing the height of the cells.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBNativeAdCollectionViewCellProvider
: FBNativeAdCollectionViewAdProvider
/**
Method to create a FBNativeAdCollectionViewCellProvider.
@param manager The naitve ad manager consumed by this provider
@param type The type of this native ad template. For more information, consult FBNativeAdViewType.
*/
- (instancetype)initWithManager:(FBNativeAdsManager *)manager forType:(FBNativeAdViewType)type;
/**
Method to create a FBNativeAdCollectionViewCellProvider.
@param manager The naitve ad manager consumed by this provider
@param type The type of this native ad template. For more information, consult FBNativeAdViewType.
@param attributes The layout of this native ad template. For more information, consult FBNativeAdViewLayout.
*/
- (instancetype)initWithManager:(FBNativeAdsManager *)manager
forType:(FBNativeAdViewType)type
forAttributes:(FBNativeAdViewAttributes *)attributes NS_DESIGNATED_INITIALIZER;
/**
Helper method for implementors of UICollectionViewDataSource who would like to host native ad UICollectionViewCells in
their collection view.
*/
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath;
/**
Helper method for implementors of UICollectionViewDelegate who would like to host native ad UICollectionViewCells in
their collection view.
*/
- (CGFloat)collectionView:(UICollectionView *)collectionView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,130 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBNativeAdView.h>
#import <FBAudienceNetwork/FBNativeAdsManager.h>
NS_ASSUME_NONNULL_BEGIN
@protocol FBNativeAdView;
/**
Contains multiple ads in a scroll view.
If adding this view to a XIB or Storyboard, you may recieve the error "Unknown class FBNativeAdScrollView in Interface
Builder file" in some cases. This error is caused by the linker failing to include FBNativeAdScrollView in your build.
To resolve this, call [FBNativeAdScrollView class] in your project, or add "-all_load -ObjC" to "Other Linker Flags" in
your project settings.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBNativeAdScrollView : UIView
/**
Maximum native ads that this scroll view will load. Defaults to 10. If changed after calling loadAds, all current ads
will be discarded and loadAds must be called again.
*/
@property (nonatomic, assign, readonly) NSUInteger maximumNativeAdCount;
/**
Toggles animating the loaded views. Default is YES.
*/
@property (nonatomic, assign, getter=isAnimationEnabled) BOOL animationEnabled;
/**
Horizontal inset for views in the scroll view. Defaults to 8 points.
*/
@property (nonatomic, assign) CGFloat xInset;
/**
Reloads the same ads for the same manager. Default is NO.
*/
@property (nonatomic, assign, getter=isAdPersistenceEnabled) BOOL adPersistenceEnabled;
/**
A view controller that is used to present modal content. If nil, the view searches for a view controller.
*/
@property (nonatomic, weak, nullable) UIViewController *rootViewController;
/**
Passes delegate methods from FBNativeAd. Separate delegate calls will be made for each native ad contained.
*/
@property (nonatomic, weak, nullable) id<FBNativeAdDelegate> delegate;
/**
Creates a native ad horizontal scroll view for a given native ads manager and native ad template. The manager can be
preloaded with ads, and loadAds will use the preloaded ads from the manager. Otherwise, the scroll view uses the
manager to load ads normally.
@param manager An instance of FBNativeAdManager. Can be preloaded with ads.
@param type The type of this native ad template. For more information, consult FBNativeAdViewType.
*/
- (instancetype)initWithNativeAdsManager:(FBNativeAdsManager *)manager withType:(FBNativeAdViewType)type;
/**
Creates a native ad horizontal scroll view for a given native ads manager and native ad template. The manager can be
preloaded with ads, and loadAds will use the preloaded ads from the manager. Otherwise, the scroll view uses the
manager to load ads normally.
@param manager An instance of FBNativeAdManager. Can be preloaded with ads.
@param type The type of this native ad template. For more information, consult FBNativeAdViewType.
@param attributes The layout of this native ad template. For more information, consult FBNativeAdViewLayout.
*/
- (instancetype)initWithNativeAdsManager:(FBNativeAdsManager *)manager
withType:(FBNativeAdViewType)type
withAttributes:(FBNativeAdViewAttributes *)attributes;
/**
Creates a native ad horizontal scroll view for a given native ads manager and native ad template. The manager can be
preloaded with ads, and loadAds will use the preloaded ads from the manager. Otherwise, the scroll view uses the
manager to load ads normally.
@param manager An instance of FBNativeAdManager. Can be preloaded with ads.
@param type The type of this native ad template. For more information, consult FBNativeAdViewType.
@param attributes The layout of this native ad template. For more information, consult FBNativeAdViewLayout.
@param maximumNativeAdCount Maximum native ads to show at once.
*/
- (instancetype)initWithNativeAdsManager:(FBNativeAdsManager *)manager
withType:(FBNativeAdViewType)type
withAttributes:(FBNativeAdViewAttributes *)attributes
withMaximum:(NSUInteger)maximumNativeAdCount;
/**
This is a method to create a native ad horizontal scroll view from a user provided view.
@param manager An instance of FBNativeAdManager. Can be preloaded with ads.
@param childViewProvider Block that creates new views for each loaded native ad. Must not reuse the same instance, but
return a new view for each call. Views may be arbitrarily resized and should support resizing their content through
Auto Layout constraints, autoresizing masks, or manual resizing.
*/
- (instancetype)initWithNativeAdsManager:(FBNativeAdsManager *)manager
withViewProvider:(UIView * (^)(FBNativeAd *nativeAd, NSUInteger position))childViewProvider;
/**
This is a method to create a native ad horizontal scroll view from a user provided view.
@param manager An instance of FBNativeAdManager. Can be preloaded with ads.
@param childViewProvider Block that creates new views for each loaded native ad. Must not reuse the same instance, but
return a new view for each call. Views may be arbitrarily resized and should support resizing their content through
Auto Layout constraints, autoresizing masks, or manual resizing.
@param maximumNativeAdCount Maximum native ads to show at once.
*/
- (instancetype)initWithNativeAdsManager:(FBNativeAdsManager *)manager
withViewProvider:(UIView * (^)(FBNativeAd *nativeAd, NSUInteger position))childViewProvider
withMaximum:(NSUInteger)maximumNativeAdCount NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,96 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdExtraHint.h>
#import <FBAudienceNetwork/FBNativeAd.h>
#import <FBAudienceNetwork/FBNativeAdsManager.h>
NS_ASSUME_NONNULL_BEGIN
/**
Additional functionality on top of FBNativeAdsManager to assist in using native ads within a UITableView. This class
contains a mechanism to map indexPaths to native ads in a stable manner as well as helpers which assist in doing the
math to include ads at a regular interval within a table view.
*/
FB_CLASS_EXPORT
@interface FBNativeAdTableViewAdProvider : NSObject
/**
Passes delegate methods from FBNativeAd. Separate delegate calls will be made for each native ad contained.
*/
@property (nonatomic, weak, nullable) id<FBNativeAdDelegate> delegate;
/**
FBAdExtraHint to provide extra info
*/
@property (nonatomic, strong, nullable) FBAdExtraHint *extraHint;
/**
Create a FBNativeAdTableViewAdProvider.
@param manager The FBNativeAdsManager which is consumed by this class.
*/
- (instancetype)initWithManager:(FBNativeAdsManager *)manager NS_DESIGNATED_INITIALIZER;
/**
Retrieve a native ad for an indexPath, will return the same ad for a given indexPath until the native ads manager is
refreshed. This method is intended for usage with a table view and specifically the caller is recommended to wait until
tableView:cellForRowAtIndexPath: to ensure getting the best native ad for the given table cell.
@param tableView The tableView where native ad will be used
@param indexPath The indexPath to use as a key for this native ad
@return A FBNativeAd which is loaded and ready to be used.
*/
- (FBNativeAd *)tableView:(UITableView *)tableView nativeAdForRowAtIndexPath:(NSIndexPath *)indexPath;
/**
Support for evenly distributed native ads within a table view. Computes whether this cell is an ad or not.
@param indexPath The indexPath of the cell within the table view
@param stride The frequency that native ads are to appear within the table view
@return Boolean indicating whether the cell at the path is an ad
*/
- (BOOL)isAdCellAtIndexPath:(NSIndexPath *)indexPath forStride:(NSUInteger)stride;
/**
Support for evenly distributed native ads within a table view. Adjusts a non-ad cell indexPath to the indexPath it
would be in a collection with no ads.
@param indexPath The indexPath to of the non-ad cell
@param stride The frequency that native ads are to appear within the table view
@return An indexPath adjusted to what it would be in a table view with no ads
*/
- (nullable NSIndexPath *)adjustNonAdCellIndexPath:(NSIndexPath *)indexPath forStride:(NSUInteger)stride;
/**
Support for evenly distributed native ads within a table view. Adjusts the total count of cells within the table view
to account for the ad cells.
@param count The count of cells in the table view not including ads
@param stride The frequency that native ads are to appear within the table view
@return The total count of cells within the table view including both ad and non-ad cells
*/
- (NSUInteger)adjustCount:(NSUInteger)count forStride:(NSUInteger)stride;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,77 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBNativeAd.h>
#import <FBAudienceNetwork/FBNativeAdTableViewAdProvider.h>
#import <FBAudienceNetwork/FBNativeAdView.h>
#import <FBAudienceNetwork/FBNativeAdsManager.h>
NS_ASSUME_NONNULL_BEGIN
/**
Class which assists in putting FBNativeAdViews into UITableViews. This class manages the creation of UITableViewCells
which host native ad views. Functionality is provided to create UITableCellViews as needed for a given indexPath as
well as computing the height of the cells.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBNativeAdTableViewCellProvider
: FBNativeAdTableViewAdProvider<UITableViewDataSource>
/**
Method to create a FBNativeAdTableViewCellProvider.
@param manager The naitve ad manager consumed by this provider
@param type The type of this native ad template. For more information, consult FBNativeAdViewType.
*/
- (instancetype)initWithManager:(FBNativeAdsManager *)manager forType:(FBNativeAdViewType)type;
/**
Method to create a FBNativeAdTableViewCellProvider.
@param manager The naitve ad manager consumed by this provider
@param type The type of this native ad template. For more information, consult FBNativeAdViewType.
@param attributes The layout of this native ad template. For more information, consult FBNativeAdViewLayout.
*/
- (instancetype)initWithManager:(FBNativeAdsManager *)manager
forType:(FBNativeAdViewType)type
forAttributes:(FBNativeAdViewAttributes *)attributes NS_DESIGNATED_INITIALIZER;
/**
Helper method for implementors of UITableViewDataSource who would like to host native ad UITableViewCells in their
table view.
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
/**
Helper method for implementors of UITableViewDelegate who would like to host native ad UITableViewCells in their table
view.
*/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
/**
Helper method for implementors of UITableViewDelegate who would like to host native ad UITableViewCells in their table
view.
*/
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,94 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBNativeAd.h>
#import <FBAudienceNetwork/FBNativeAdBaseView.h>
#import <FBAudienceNetwork/FBNativeAdViewAttributes.h>
NS_ASSUME_NONNULL_BEGIN
/**
Determines the type of native ad template. Different views are created
for different values of FBNativeAdViewType
*/
typedef NS_ENUM(NSInteger, FBNativeAdViewType) {
/// Fixed height view, 300 points
FBNativeAdViewTypeGenericHeight300 = 3,
/// Fixed height view, 400 points
FBNativeAdViewTypeGenericHeight400 = 4,
/// Dynamic height, will be rendered to make the best use of the size set.
FBNativeAdViewTypeDynamic = 6,
};
/**
The FBNativeAdView creates prebuilt native ad template views and manages native ads.
*/
FB_CLASS_EXPORT
@interface FBNativeAdView : FBNativeAdBaseView
/**
The type of the view, specifies which template to use
*/
@property (nonatomic, assign, readonly) FBNativeAdViewType type;
/**
This is a method to create a native ad template using the given native ad and using default ad view attributes.
@param nativeAd The native ad to use to create this view.
*/
+ (instancetype)nativeAdViewWithNativeAd:(FBNativeAd *)nativeAd;
/**
This is a method to create a native ad template using the given native ad and ad view attributes.
@param nativeAd The native ad to use to create this view.
*/
+ (instancetype)nativeAdViewWithNativeAd:(FBNativeAd *)nativeAd withAttributes:(FBNativeAdViewAttributes *)attributes;
/**
This is a method to create a native ad template using the given placement id and type.
@param nativeAd The native ad to use to create this view.
@param type The type of this native ad template. For more information, consult FBNativeAdViewType.
*/
+ (instancetype)nativeAdViewWithNativeAd:(FBNativeAd *)nativeAd withType:(FBNativeAdViewType)type;
/**
This is a method to create a native ad template using the given placement id and type.
@param nativeAd The native ad to use to create this view.
@param type The type of this native ad template. For more information, consult FBNativeAdViewType.
@param attributes The attributes to render this native ad template with.
*/
+ (instancetype)nativeAdViewWithNativeAd:(FBNativeAd *)nativeAd
withType:(FBNativeAdViewType)type
withAttributes:(FBNativeAdViewAttributes *)attributes;
@end
@interface FBNativeAdViewAttributes (FBNativeAdView)
/**
Returns default attributes for a given type.
@param type The type for this layout.
*/
+ (instancetype)defaultAttributesForType:(FBNativeAdViewType)type;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,85 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Describes the look and feel of a native ad view.
*/
@interface FBNativeAdViewAttributes : NSObject <NSCopying>
/**
This is a method to create native ad view attributes with a dictionary
*/
- (instancetype)initWithDictionary:(NSDictionary<id, id> *)dict NS_DESIGNATED_INITIALIZER;
/**
Background color of the native ad view.
*/
@property (nonatomic, copy, nullable) UIColor *backgroundColor;
/**
Color of the title label.
*/
@property (nonatomic, copy, nullable) UIColor *titleColor;
/**
Color of the advertiser name label.
*/
@property (nonatomic, copy, nullable) UIColor *advertiserNameColor;
/**
Color of the ad choices icon.
*/
@property (nonatomic, copy, nullable) UIColor *adChoicesForegroundColor;
/**
Font of the title label.
*/
@property (nonatomic, copy, nullable) UIFont *titleFont;
/**
Color of the description label.
*/
@property (nonatomic, copy, nullable) UIColor *descriptionColor;
/**
Font of the description label.
*/
@property (nonatomic, copy, nullable) UIFont *descriptionFont;
/**
Background color of the call to action button.
*/
@property (nonatomic, copy, nullable) UIColor *buttonColor;
/**
Color of the call to action button's title label.
*/
@property (nonatomic, copy, nullable) UIColor *buttonTitleColor;
/**
Font of the call to action button's title label.
*/
@property (nonatomic, copy, nullable) UIFont *buttonTitleFont;
/**
Border color of the call to action button. If nil, no border is shown.
*/
@property (nonatomic, copy, nullable) UIColor *buttonBorderColor;
/**
Enables or disables autoplay for some types of media. Defaults to YES.
*/
@property (nonatomic, assign, getter=isAutoplayEnabled) BOOL autoplayEnabled
__attribute((deprecated("This attribute is no longer used.")));
@end
NS_ASSUME_NONNULL_END

View file

@ -1,120 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdExtraHint.h>
#import <FBAudienceNetwork/FBNativeAd.h>
NS_ASSUME_NONNULL_BEGIN
/**
@protocol FBNativeAdsManagerDelegate
Messages from FBNativeAdsManager indicating success or failure loading ads.
*/
@protocol FBNativeAdsManagerDelegate <NSObject>
/**
When the FBNativeAdsManager has finished loading a batch of ads this message will be sent. A batch of ads may be
loaded in response to calling loadAds or due to an automatic refresh by the FBNativeAdsManager. At the point this
message is fired all of the native ads will already be loaded and will not hence send their own nativeAdLoad: or
nativeAd:didFailWithError: message.
*/
- (void)nativeAdsLoaded;
/**
When the FBNativeAdsManager has reached a failure while attempting to load a batch of ads this message will be sent to
the application.
@param error An NSError object with information about the failure.
*/
- (void)nativeAdsFailedToLoadWithError:(NSError *)error;
@end
/**
This class provides a mechanism to fetch a set of ads and then use them within your application. The recommended usage
is to call nextNativeAd: at the moment when you are about to render an ad. The native ads manager supports giving out
as many ads as needed by cloning over the set of ads it got back from the server which can be useful for feed
scenarios.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBNativeAdsManager : NSObject
/**
The delegate
*/
@property (nonatomic, weak, nullable) id<FBNativeAdsManagerDelegate> delegate;
/**
Set the native ads manager caching policy. This controls which media from the native ads are cached before the native
ads manager calls nativeAdsLoaded on its delegate. The default is to not block on caching.
*/
@property (nonatomic, assign) FBNativeAdsCachePolicy mediaCachePolicy;
/**
Number of unique native ads that can be accessed through nextNativeAd:. This is not valid until the nativeAdsLoaded:
message has been sent.
*/
@property (nonatomic, assign, readonly) NSUInteger uniqueNativeAdCount;
/**
Returns YES after nativeAdsLoaded: message has been sent.
*/
@property (nonatomic, assign, getter=isValid, readonly) BOOL valid;
/**
FBAdExtraHint to provide extra info
*/
@property (nonatomic, strong, nullable) FBAdExtraHint *extraHint;
/**
Initialize the native ads manager.
@param placementID The id of the ad placement. You can create your placement id from Facebook developers page.
@param numAdsRequested The number of ads you would like the native ads manager to retrieve.
*/
- (instancetype)initWithPlacementID:(NSString *)placementID
forNumAdsRequested:(NSUInteger)numAdsRequested NS_DESIGNATED_INITIALIZER;
/**
The method that kicks off the loading of ads. It may be called again in the future to refresh the ads manually.
*/
- (void)loadAds;
/**
By default the native ads manager will refresh its ads periodically. This does not mean that any ads which are shown
in the application's UI will be refreshed but simply that calling nextNativeAd: may return different ads at different
times. This method disables that functionality.
*/
- (void)disableAutoRefresh;
/**
Retrieve the next native ad to be used from the batch. It is highly recommended that the caller wait until immediately
before rendering the ad content to call this method to ensure the best ad for the given context is used. If more than
uniqueNativeAdCount ads are requested cloned ads will be returned. Periodically the native ads manager will refresh and
new ads will be returned.
@return A FBNativeAd which is loaded and ready to be used.
*/
@property (nonatomic, readonly, strong, nullable) FBNativeAd *nextNativeAd;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,168 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdSettings.h>
#import <FBAudienceNetwork/FBNativeAdBase.h>
#import "FBAdImage.h"
NS_ASSUME_NONNULL_BEGIN
@protocol FBNativeBannerAdDelegate;
@class FBMediaView;
/**
The FBNativeBannerAd represents ad metadata to allow you to construct custom ad views.
See the AdUnitsSample in the sample apps section of the Audience Network framework.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBNativeBannerAd : FBNativeAdBase
@property (nonatomic, weak, nullable) id<FBNativeBannerAdDelegate> delegate;
- (instancetype)initWithPlacementID:(NSString *)placementID;
/**
This is a method to associate a FBNativeBannerAd with the UIView you will use to display the native ads.
@param view The UIView you created to render all the native ads data elements.
@param iconView The FBMediaView you created to render the icon
@param viewController The UIViewController that will be used to present SKStoreProductViewController
(iTunes Store product information) or the in-app browser. If nil is passed, the top view controller currently shown
will be used.
The whole area of the UIView will be clickable.
*/
- (void)registerViewForInteraction:(UIView *)view
iconView:(FBMediaView *)iconView
viewController:(nullable UIViewController *)viewController;
/**
This is a method to associate FBNativeBannerAd with the UIView you will use to display the native ads
and set clickable areas.
@param view The UIView you created to render all the native ads data elements.
@param iconView The FBMediaView you created to render the icon
@param viewController The UIViewController that will be used to present SKStoreProductViewController
(iTunes Store product information). If nil is passed, the top view controller currently shown will be used.
@param clickableViews An array of UIView you created to render the native ads data element, e.g.
CallToAction button, Icon image, which you want to specify as clickable.
*/
- (void)registerViewForInteraction:(UIView *)view
iconView:(FBMediaView *)iconView
viewController:(nullable UIViewController *)viewController
clickableViews:(nullable NSArray<UIView *> *)clickableViews;
/**
This is a method to associate a FBNativeBannerAd with the UIView you will use to display the native ads.
@param view The UIView you created to render all the native ads data elements.
@param iconImageView The UIImageView you created to render the icon
@param viewController The UIViewController that will be used to present SKStoreProductViewController
(iTunes Store product information) or the in-app browser. If nil is passed, the top view controller currently shown
will be used.
The whole area of the UIView will be clickable.
*/
- (void)registerViewForInteraction:(UIView *)view
iconImageView:(UIImageView *)iconImageView
viewController:(nullable UIViewController *)viewController;
/**
This is a method to associate FBNativeBannerAd with the UIView you will use to display the native ads
and set clickable areas.
@param view The UIView you created to render all the native ads data elements.
@param iconImageView The UIImageView you created to render the icon
@param viewController The UIViewController that will be used to present SKStoreProductViewController
(iTunes Store product information). If nil is passed, the top view controller currently shown will be used.
@param clickableViews An array of UIView you created to render the native ads data element, e.g.
CallToAction button, Icon image, which you want to specify as clickable.
*/
- (void)registerViewForInteraction:(UIView *)view
iconImageView:(UIImageView *)iconImageView
viewController:(nullable UIViewController *)viewController
clickableViews:(nullable NSArray<UIView *> *)clickableViews;
/**
This is a method to use to download all media for the ad (adChoicesIcon, icon).
This is only needed to be called if the mediaCachePolicy is set to FBNativeAdsCachePolicyNone.
*/
- (void)downloadMedia;
@end
/**
The methods declared by the FBNativeBannerAdDelegate protocol allow the adopting delegate to respond to messages
from the FBNativeBannerAd class and thus respond to operations such as whether the native banner ad has been loaded.
*/
@protocol FBNativeBannerAdDelegate <NSObject>
@optional
/**
Sent when an FBNativeBannerAd has been successfully loaded.
@param nativeBannerAd An FBNativeBannerAd object sending the message.
*/
- (void)nativeBannerAdDidLoad:(FBNativeBannerAd *)nativeBannerAd;
/**
Sent when an FBNativeBannerAd has succesfully downloaded all media
*/
- (void)nativeBannerAdDidDownloadMedia:(FBNativeBannerAd *)nativeBannerAd;
/**
Sent immediately before the impression of an FBNativeBannerAd object will be logged.
@param nativeBannerAd An FBNativeBannerAd object sending the message.
*/
- (void)nativeBannerAdWillLogImpression:(FBNativeBannerAd *)nativeBannerAd;
/**
Sent when an FBNativeBannerAd is failed to load.
@param nativeBannerAd An FBNativeBannerAd object sending the message.
@param error An error object containing details of the error.
*/
- (void)nativeBannerAd:(FBNativeBannerAd *)nativeBannerAd didFailWithError:(NSError *)error;
/**
Sent after an ad has been clicked by the person.
@param nativeBannerAd An FBNativeBannerAd object sending the message.
*/
- (void)nativeBannerAdDidClick:(FBNativeBannerAd *)nativeBannerAd;
/**
When an ad is clicked, the modal view will be presented. And when the user finishes the
interaction with the modal view and dismiss it, this message will be sent, returning control
to the application.
@param nativeBannerAd An FBNativeBannerAd object sending the message.
*/
- (void)nativeBannerAdDidFinishHandlingClick:(FBNativeBannerAd *)nativeBannerAd;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,83 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBNativeAdBaseView.h>
#import <FBAudienceNetwork/FBNativeAdViewAttributes.h>
#import <FBAudienceNetwork/FBNativeBannerAd.h>
NS_ASSUME_NONNULL_BEGIN
/**
Determines the type of native banner ad template. Different views are created
for different values of FBNativeAdBannerViewType
*/
typedef NS_ENUM(NSInteger, FBNativeBannerAdViewType) {
/// Fixed height view, 100 points (banner equivalent)
FBNativeBannerAdViewTypeGenericHeight100 = 1,
/// Fixed height view, 120 points (banner equivalent)
FBNativeBannerAdViewTypeGenericHeight120 = 2,
/// Fixed height view, 50 points (banner equivalent)
FBNativeBannerAdViewTypeGenericHeight50 = 5,
};
/**
The FBNativeBannerAdView creates prebuilt native banner ad template views and manages native banner ads.
*/
FB_CLASS_EXPORT
@interface FBNativeBannerAdView : FBNativeAdBaseView
/**
The type of the view, specifies which template to use
*/
@property (nonatomic, assign, readonly) FBNativeBannerAdViewType type;
/**
This is a method to create a native ad template using the given placement id and type.
@param nativeBannerAd The native banner ad to use to create this view.
@param type The type of this native banner ad template. For more information, consult FBNativeAdBannerViewType.
*/
+ (instancetype)nativeBannerAdViewWithNativeBannerAd:(FBNativeBannerAd *)nativeBannerAd
withType:(FBNativeBannerAdViewType)type;
/**
This is a method to create a native ad template using the given placement id and type.
@param nativeBannerAd The native banner ad to use to create this view.
@param type The type of this native banner ad template. For more information, consult FBNativeAdBannerViewType.
@param attributes The attributes to render this native ad template with.
*/
+ (instancetype)nativeBannerAdViewWithNativeBannerAd:(FBNativeBannerAd *)nativeBannerAd
withType:(FBNativeBannerAdViewType)type
withAttributes:(FBNativeAdViewAttributes *)attributes;
@end
@interface FBNativeAdViewAttributes (FBNativeBannerAdView)
/**
Returns default attributes for a given type.
@param type The type for this layout.
*/
+ (instancetype)defaultAttributesForBannerType:(FBNativeBannerAdViewType)type;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,217 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <CoreMedia/CoreMedia.h>
#import <Foundation/Foundation.h>
#import <FBAudienceNetwork/FBAdDefines.h>
#import <FBAudienceNetwork/FBAdExperienceConfig.h>
#import <FBAudienceNetwork/FBAdExtraHint.h>
NS_ASSUME_NONNULL_BEGIN
@protocol FBRewardedVideoAdDelegate;
/**
A modal view controller to represent a Facebook rewarded video ad. This
is a full-screen ad shown in your application.
*/
FB_CLASS_EXPORT FB_SUBCLASSING_RESTRICTED @interface FBRewardedVideoAd : NSObject
/**
Typed access to the id of the ad placement.
*/
@property (nonatomic, copy, readonly) NSString *placementID;
/**
The duration of the video, as a CMTime value. Returns kCMTimeIndefinite if no video is loaded.
*/
@property (nonatomic, assign, readonly) CMTime duration;
/**
the delegate
*/
@property (nonatomic, weak, nullable) id<FBRewardedVideoAdDelegate> delegate;
/**
Returns true if the rewarded video ad has been successfully loaded.
You should check `isAdValid` before trying to show the ad.
*/
@property (nonatomic, getter=isAdValid, readonly) BOOL adValid;
/**
FBAdExtraHint to provide extra info
*/
@property (nonatomic, strong, nullable) FBAdExtraHint *extraHint;
/**
FBAdExperiencConfig to provide additional ad configuration
*/
@property (nonatomic, copy, nullable) FBAdExperienceConfig *adExperienceConfig;
/**
This is a method to initialize an FBRewardedVideoAd matching the given placement id.
@param placementID The id of the ad placement. You can create your placement id from Facebook developers page.
*/
- (instancetype)initWithPlacementID:(NSString *)placementID;
/**
This is a method to initialize an FBRewardedVideoAd matching the given placement id and allows the publisher to set
the reward to give to a user.
- Parameter placementID The id of the ad placement. You can create your placement id from Facebook developers page.
- Parameter userID the id of the user
- Parameter currency reward currency type
*/
- (instancetype)initWithPlacementID:(NSString *)placementID
withUserID:(nullable NSString *)userID
withCurrency:(nullable NSString *)currency;
/**
Begins loading the FBRewardedVideoAd content.
You can implement `rewardedVideoAdDidLoad:` and `rewardedVideoAd:didFailWithError:` methods
of `FBRewardedVideoAdDelegate` if you would like to be notified as loading succeeds or fails.
*/
- (void)loadAd;
/**
Begins loading the FBRewardedVideoAd content from a bid payload attained through a server side bid.
You can implement `rewardedVideoAdDidLoad:` and `rewardedVideoAd:didFailWithError:` methods
of `FBRewardedVideoAdDelegate` if you would like to be notified as loading succeeds or fails.
*/
- (void)loadAdWithBidPayload:(NSString *)bidPayload;
/**
This method allows the publisher to set the reward to give to a user. Returns NO if it was not able
to set Reward Data.
- Parameter userID the id of the user
- Parameter currency reward currency type
*/
- (BOOL)setRewardDataWithUserID:(NSString *)userID withCurrency:(NSString *)currency;
/**
Presents the rewarded video ad modally from the specified view controller.
@param rootViewController The view controller that will be used to present the rewarded video ad.
You can implement `rewardedVideoAdDidClick:` and `rewardedVideoAdWillClose:`
methods of `FBRewardedVideoAdDelegate` if you would like to stay informed for those events.
*/
- (BOOL)showAdFromRootViewController:(UIViewController *)rootViewController;
/**
Presents the rewarded video ad modally from the specified view controller.
@param rootViewController The view controller that will be used to present the rewarded video ad.
@param flag Pass YES to animate the presentation; otherwise, pass NO.
You can implement `rewardedVideoAdDidClick:` and `rewardedVideoAdWillClose:`
methods of `FBRewardedVideoAdDelegate` if you would like to stay informed for those events.
*/
- (BOOL)showAdFromRootViewController:(UIViewController *)rootViewController animated:(BOOL)flag;
@end
/**
The methods declared by the FBRewardedVideoAdDelegate protocol allow the adopting delegate to respond
to messages from the FBRewardedVideoAd class and thus respond to operations such as whether the ad has
been loaded, the person has clicked the ad or closed video/end card.
*/
@protocol FBRewardedVideoAdDelegate <NSObject>
@optional
/**
Sent after an ad has been clicked by the person.
@param rewardedVideoAd An FBRewardedVideoAd object sending the message.
*/
- (void)rewardedVideoAdDidClick:(FBRewardedVideoAd *)rewardedVideoAd;
/**
Sent when an ad has been successfully loaded.
@param rewardedVideoAd An FBRewardedVideoAd object sending the message.
*/
- (void)rewardedVideoAdDidLoad:(FBRewardedVideoAd *)rewardedVideoAd;
/**
Sent after an FBRewardedVideoAd object has been dismissed from the screen, returning control
to your application.
@param rewardedVideoAd An FBRewardedVideoAd object sending the message.
*/
- (void)rewardedVideoAdDidClose:(FBRewardedVideoAd *)rewardedVideoAd;
/**
Sent immediately before an FBRewardedVideoAd object will be dismissed from the screen.
@param rewardedVideoAd An FBRewardedVideoAd object sending the message.
*/
- (void)rewardedVideoAdWillClose:(FBRewardedVideoAd *)rewardedVideoAd;
/**
Sent after an FBRewardedVideoAd fails to load the ad.
@param rewardedVideoAd An FBRewardedVideoAd object sending the message.
@param error An error object containing details of the error.
*/
- (void)rewardedVideoAd:(FBRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *)error;
/**
Sent after the FBRewardedVideoAd object has finished playing the video successfully.
Reward the user on this callback.
@param rewardedVideoAd An FBRewardedVideoAd object sending the message.
*/
- (void)rewardedVideoAdVideoComplete:(FBRewardedVideoAd *)rewardedVideoAd;
/**
Sent immediately before the impression of an FBRewardedVideoAd object will be logged.
@param rewardedVideoAd An FBRewardedVideoAd object sending the message.
*/
- (void)rewardedVideoAdWillLogImpression:(FBRewardedVideoAd *)rewardedVideoAd;
/**
Sent if server call to publisher's reward endpoint returned HTTP status code 200.
@param rewardedVideoAd An FBRewardedVideoAd object sending the message.
*/
- (void)rewardedVideoAdServerRewardDidSucceed:(FBRewardedVideoAd *)rewardedVideoAd;
/**
Sent if server call to publisher's reward endpoint did not return HTTP status code 200
or if the endpoint timed out.
@param rewardedVideoAd An FBRewardedVideoAd object sending the message.
*/
- (void)rewardedVideoAdServerRewardDidFail:(FBRewardedVideoAd *)rewardedVideoAd;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,58 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/***
* This is a bridge file for Audience Network Unity SDK.
*
* Please refer to FBRewardedVideoAd.h and FBAdExtraHint.h for full documentation of the API.
*
* This file may be used to build your own Audience Network iOS SDK wrapper,
* but note that we don't support customisations of the Audience Network codebase.
*
***/
#import <FBAudienceNetwork/FBAdBridgeCommon.h>
FB_EXTERN_C_BEGIN
FB_EXPORT int32_t FBRewardedVideoAdBridgeCreate(char const *placementID);
FB_EXPORT int32_t FBRewardedVideoAdBridgeCreateWithReward(char const *placementID,
char const *userID,
char const *currency);
FB_EXPORT int32_t FBRewardedVideoAdBridgeLoad(int32_t uniqueId);
FB_EXPORT int32_t FBRewardedVideoAdBridgeLoadWithBidPayload(int32_t uniqueId, char *bidPayload);
FB_EXPORT bool FBRewardedVideoAdBridgeIsValid(int32_t uniqueId);
FB_EXPORT char const *FBRewardedVideoAdBridgeGetPlacementId(int32_t uniqueId);
FB_EXPORT bool FBRewardedVideoAdBridgeShow(int32_t uniqueId);
FB_EXPORT bool FBRewardedVideoAdBridgeShowAnimated(int32_t uniqueId, bool isAnimated);
FB_EXPORT void FBRewardedVideoAdBridgeSetExtraHints(int32_t uniqueId, char const *extraHints);
FB_EXPORT void FBRewardedVideoAdBridgeRelease(int32_t uniqueId);
FB_EXPORT void FBRewardedVideoAdBridgeOnLoad(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBRewardedVideoAdBridgeOnImpression(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBRewardedVideoAdBridgeOnClick(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBRewardedVideoAdBridgeOnError(int32_t uniqueId, FBAdBridgeErrorCallback callback);
FB_EXPORT void FBRewardedVideoAdBridgeOnDidClose(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBRewardedVideoAdBridgeOnWillClose(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBRewardedVideoAdBridgeOnVideoComplete(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBRewardedVideoAdBridgeOnServerRewardSuccess(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXPORT void FBRewardedVideoAdBridgeOnServerRewardFailure(int32_t uniqueId, FBAdBridgeCallback callback);
FB_EXTERN_C_END

View file

@ -1,46 +0,0 @@
// Copyright 2004-present Facebook. All Rights Reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Determines the possible tags for native ad views.
*/
typedef NS_ENUM(NSUInteger, FBNativeAdViewTag) {
FBNativeAdViewTagIcon = 5,
FBNativeAdViewTagTitle,
FBNativeAdViewTagCoverImage,
FBNativeAdViewTagSubtitle,
FBNativeAdViewTagBody,
FBNativeAdViewTagCallToAction,
FBNativeAdViewTagSocialContext,
FBNativeAdViewTagChoicesIcon,
FBNativeAdViewTagMedia,
};
/**
Use this category to set tags for views you are using for native ad.
This will enable better analytics.
*/
@interface UIView (FBNativeAdViewTag)
@property (nonatomic, assign) FBNativeAdViewTag nativeAdViewTag;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,58 +0,0 @@
framework module FBAudienceNetwork {
umbrella header "FBAudienceNetwork.h"
export *
module * {
export *
}
requires objc, blocks
link framework "AdSupport"
link framework "AudioToolbox"
link framework "AVFoundation"
link framework "CFNetwork"
link framework "CoreGraphics"
link framework "CoreImage"
link framework "CoreMedia"
link framework "CoreMotion"
link framework "CoreTelephony"
link framework "Foundation"
link framework "LocalAuthentication"
link framework "SafariServices"
link framework "Security"
link framework "StoreKit"
link framework "SystemConfiguration"
link framework "UIKit"
link framework "WebKit"
link framework "VideoToolbox"
link "c++"
link "xml2"
header "FBAdChoicesView.h"
header "FBAdDefines.h"
header "FBAdExperienceConfig.h"
header "FBAdSettings.h"
header "FBAdView.h"
header "FBInstreamAdView.h"
header "FBInterstitialAd.h"
header "FBMediaView.h"
header "FBNativeAd.h"
header "FBNativeAdScrollView.h"
header "FBNativeAdTableViewAdProvider.h"
header "FBNativeAdTableViewCellProvider.h"
header "FBNativeAdCollectionViewAdProvider.h"
header "FBNativeAdCollectionViewCellProvider.h"
header "FBNativeAdView.h"
header "FBNativeAdsManager.h"
header "FBRewardedVideoAd.h"
header "FBAdBridgeCommon.h"
header "FBAdBridgeContainer.h"
header "FBAdSettingsBridge.h"
header "FBAdUtilityBridge.h"
header "FBAdViewBridge.h"
header "FBInterstitialAdBridge.h"
header "FBRewardedVideoAdBridge.h"
}

View file

@ -1,12 +0,0 @@
This software may contain the following third party software:
ZipArchive
Copyright (c) 2010-2015, Sam Soffes, https://soff.es
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,865 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#if !TARGET_OS_TV
#import <WebKit/WebKit.h>
#endif
#ifdef BUCK
#import <FBSDKCoreKit/FBSDKGraphRequestConnection.h>
#else
#import "FBSDKGraphRequestConnection.h"
#endif
NS_ASSUME_NONNULL_BEGIN
@class FBSDKAccessToken;
@class FBSDKGraphRequest;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
/** NSNotificationCenter name indicating a result of a failed log flush attempt. The posted object will be an NSError instance. */
FOUNDATION_EXPORT NSNotificationName const FBSDKAppEventsLoggingResultNotification
NS_SWIFT_NAME(AppEventsLoggingResult);
#else
/** NSNotificationCenter name indicating a result of a failed log flush attempt. The posted object will be an NSError instance. */
FOUNDATION_EXPORT NSString *const FBSDKAppEventsLoggingResultNotification
NS_SWIFT_NAME(AppEventsLoggingResultNotification);
#endif
/** optional plist key ("FacebookLoggingOverrideAppID") for setting `loggingOverrideAppID` */
FOUNDATION_EXPORT NSString *const FBSDKAppEventsOverrideAppIDBundleKey
NS_SWIFT_NAME(AppEventsOverrideAppIDBundleKey);
/**
NS_ENUM (NSUInteger, FBSDKAppEventsFlushBehavior)
Specifies when `FBSDKAppEvents` sends log events to the server.
*/
typedef NS_ENUM(NSUInteger, FBSDKAppEventsFlushBehavior)
{
/** Flush automatically: periodically (once a minute or every 100 logged events) and always at app reactivation. */
FBSDKAppEventsFlushBehaviorAuto = 0,
/** Only flush when the `flush` method is called. When an app is moved to background/terminated, the
events are persisted and re-established at activation, but they will only be written with an
explicit call to `flush`. */
FBSDKAppEventsFlushBehaviorExplicitOnly,
} NS_SWIFT_NAME(AppEvents.FlushBehavior);
/**
NS_ENUM(NSUInteger, FBSDKProductAvailability)
Specifies product availability for Product Catalog product item update
*/
typedef NS_ENUM(NSUInteger, FBSDKProductAvailability)
{
/**
* Item ships immediately
*/
FBSDKProductAvailabilityInStock = 0,
/**
* No plan to restock
*/
FBSDKProductAvailabilityOutOfStock,
/**
* Available in future
*/
FBSDKProductAvailabilityPreOrder,
/**
* Ships in 1-2 weeks
*/
FBSDKProductAvailabilityAvailableForOrder,
/**
* Discontinued
*/
FBSDKProductAvailabilityDiscontinued,
} NS_SWIFT_NAME(AppEvents.ProductAvailability);
/**
NS_ENUM(NSUInteger, FBSDKProductCondition)
Specifies product condition for Product Catalog product item update
*/
typedef NS_ENUM(NSUInteger, FBSDKProductCondition)
{
FBSDKProductConditionNew = 0,
FBSDKProductConditionRefurbished,
FBSDKProductConditionUsed,
} NS_SWIFT_NAME(AppEvents.ProductCondition);
/**
@methodgroup Predefined event names for logging events common to many apps. Logging occurs through the `logEvent` family of methods on `FBSDKAppEvents`.
Common event parameters are provided in the `FBSDKAppEventsParameterNames*` constants.
*/
/// typedef for FBSDKAppEventName
typedef NSString *const FBSDKAppEventName NS_TYPED_EXTENSIBLE_ENUM NS_SWIFT_NAME(AppEvents.Name);
/** Log this event when the user has achieved a level in the app. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameAchievedLevel;
/** Log this event when the user has entered their payment info. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameAddedPaymentInfo;
/** Log this event when the user has added an item to their cart. The valueToSum passed to logEvent should be the item's price. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameAddedToCart;
/** Log this event when the user has added an item to their wishlist. The valueToSum passed to logEvent should be the item's price. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameAddedToWishlist;
/** Log this event when a user has completed registration with the app. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameCompletedRegistration;
/** Log this event when the user has completed a tutorial in the app. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameCompletedTutorial;
/** Log this event when the user has entered the checkout process. The valueToSum passed to logEvent should be the total price in the cart. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameInitiatedCheckout;
/** Log this event when the user has completed a transaction. The valueToSum passed to logEvent should be the total price of the transaction. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNamePurchased;
/** Log this event when the user has rated an item in the app. The valueToSum passed to logEvent should be the numeric rating. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameRated;
/** Log this event when a user has performed a search within the app. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameSearched;
/** Log this event when the user has spent app credits. The valueToSum passed to logEvent should be the number of credits spent. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameSpentCredits;
/** Log this event when the user has unlocked an achievement in the app. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameUnlockedAchievement;
/** Log this event when a user has viewed a form of content in the app. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameViewedContent;
/** A telephone/SMS, email, chat or other type of contact between a customer and your business. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameContact;
/** The customization of products through a configuration tool or other application your business owns. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameCustomizeProduct;
/** The donation of funds to your organization or cause. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameDonate;
/** When a person finds one of your locations via web or application, with an intention to visit (example: find product at a local store). */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameFindLocation;
/** The booking of an appointment to visit one of your locations. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameSchedule;
/** The subsequent subscriptions after the start of a paid subscription for a product or service you offer. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameSubscriptionHeartbeat __attribute((deprecated("This attribute is no longer used.")));
/** The start of a free trial of a product or service you offer (example: trial subscription). */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameStartTrial;
/** The submission of an application for a product, service or program you offer (example: credit card, educational program or job). */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameSubmitApplication;
/** The start of a paid subscription for a product or service you offer. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameSubscribe;
/** Log this event when the user views an ad. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameAdImpression;
/** Log this event when the user clicks an ad. */
FOUNDATION_EXPORT FBSDKAppEventName FBSDKAppEventNameAdClick;
/**
@methodgroup Predefined event name parameters for common additional information to accompany events logged through the `logEvent` family
of methods on `FBSDKAppEvents`. Common event names are provided in the `FBAppEventName*` constants.
*/
/// typedef for FBSDKAppEventParameterName
typedef NSString *const FBSDKAppEventParameterName NS_TYPED_EXTENSIBLE_ENUM NS_SWIFT_NAME(AppEvents.ParameterName);
/**
* Parameter key used to specify data for the one or more pieces of content being logged about.
* Data should be a JSON encoded string.
* Example:
* "[{\"id\": \"1234\", \"quantity\": 2, \"item_price\": 5.99}, {\"id\": \"5678\", \"quantity\": 1, \"item_price\": 9.99}]"
*/
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameContent;
/** Parameter key used to specify an ID for the specific piece of content being logged about. Could be an EAN, article identifier, etc., depending on the nature of the app. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameContentID;
/** Parameter key used to specify a generic content type/family for the logged event, e.g. "music", "photo", "video". Options to use will vary based upon what the app is all about. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameContentType;
/** Parameter key used to specify currency used with logged event. E.g. "USD", "EUR", "GBP". See ISO-4217 for specific values. One reference for these is <http://en.wikipedia.org/wiki/ISO_4217>. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameCurrency;
/** Parameter key used to specify a description appropriate to the event being logged. E.g., the name of the achievement unlocked in the `FBAppEventNameAchievementUnlocked` event. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameDescription;
/** Parameter key used to specify the level achieved in a `FBAppEventNameAchieved` event. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameLevel;
/** Parameter key used to specify the maximum rating available for the `FBAppEventNameRate` event. E.g., "5" or "10". */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameMaxRatingValue;
/** Parameter key used to specify how many items are being processed for an `FBAppEventNameInitiatedCheckout` or `FBAppEventNamePurchased` event. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameNumItems;
/** Parameter key used to specify whether payment info is available for the `FBAppEventNameInitiatedCheckout` event. `FBSDKAppEventParameterValueYes` and `FBSDKAppEventParameterValueNo` are good canonical values to use for this parameter. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNamePaymentInfoAvailable;
/** Parameter key used to specify method user has used to register for the app, e.g., "Facebook", "email", "Twitter", etc */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameRegistrationMethod;
/** Parameter key used to specify the string provided by the user for a search operation. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameSearchString;
/** Parameter key used to specify whether the activity being logged about was successful or not. `FBSDKAppEventParameterValueYes` and `FBSDKAppEventParameterValueNo` are good canonical values to use for this parameter. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameSuccess;
/**
@methodgroup Predefined event name parameters for common additional information to accompany events logged through the `logProductItem` method on `FBSDKAppEvents`.
*/
/// typedef for FBSDKAppEventParameterProduct
typedef NSString *const FBSDKAppEventParameterProduct NS_TYPED_EXTENSIBLE_ENUM NS_SWIFT_NAME(AppEvents.ParameterProduct);
/** Parameter key used to specify the product item's category. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductCategory;
/** Parameter key used to specify the product item's custom label 0. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductCustomLabel0;
/** Parameter key used to specify the product item's custom label 1. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductCustomLabel1;
/** Parameter key used to specify the product item's custom label 2. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductCustomLabel2;
/** Parameter key used to specify the product item's custom label 3. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductCustomLabel3;
/** Parameter key used to specify the product item's custom label 4. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductCustomLabel4;
/** Parameter key used to specify the product item's AppLink app URL for iOS. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkIOSUrl;
/** Parameter key used to specify the product item's AppLink app ID for iOS App Store. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkIOSAppStoreID;
/** Parameter key used to specify the product item's AppLink app name for iOS. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkIOSAppName;
/** Parameter key used to specify the product item's AppLink app URL for iPhone. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkIPhoneUrl;
/** Parameter key used to specify the product item's AppLink app ID for iPhone App Store. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkIPhoneAppStoreID;
/** Parameter key used to specify the product item's AppLink app name for iPhone. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkIPhoneAppName;
/** Parameter key used to specify the product item's AppLink app URL for iPad. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkIPadUrl;
/** Parameter key used to specify the product item's AppLink app ID for iPad App Store. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkIPadAppStoreID;
/** Parameter key used to specify the product item's AppLink app name for iPad. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkIPadAppName;
/** Parameter key used to specify the product item's AppLink app URL for Android. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkAndroidUrl;
/** Parameter key used to specify the product item's AppLink fully-qualified package name for intent generation. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkAndroidPackage;
/** Parameter key used to specify the product item's AppLink app name for Android. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkAndroidAppName;
/** Parameter key used to specify the product item's AppLink app URL for Windows Phone. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkWindowsPhoneUrl;
/** Parameter key used to specify the product item's AppLink app ID, as a GUID, for App Store. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkWindowsPhoneAppID;
/** Parameter key used to specify the product item's AppLink app name for Windows Phone. */
FOUNDATION_EXPORT FBSDKAppEventParameterProduct FBSDKAppEventParameterProductAppLinkWindowsPhoneAppName;
/*
@methodgroup Predefined values to assign to event parameters that accompany events logged through the `logEvent` family
of methods on `FBSDKAppEvents`. Common event parameters are provided in the `FBSDKAppEventParameterName*` constants.
*/
/// typedef for FBSDKAppEventParameterValue
typedef NSString *const FBSDKAppEventParameterValue NS_TYPED_EXTENSIBLE_ENUM NS_SWIFT_NAME(AppEvents.ParameterValue);
/** Yes-valued parameter value to be used with parameter keys that need a Yes/No value */
FOUNDATION_EXPORT FBSDKAppEventParameterValue FBSDKAppEventParameterValueYes;
/** No-valued parameter value to be used with parameter keys that need a Yes/No value */
FOUNDATION_EXPORT FBSDKAppEventParameterValue FBSDKAppEventParameterValueNo;
/** Parameter key used to specify the type of ad in an FBSDKAppEventNameAdImpression
* or FBSDKAppEventNameAdClick event.
* E.g. "banner", "interstitial", "rewarded_video", "native" */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameAdType;
/** Parameter key used to specify the unique ID for all events within a subscription
* in an FBSDKAppEventNameSubscribe or FBSDKAppEventNameStartTrial event. */
FOUNDATION_EXPORT FBSDKAppEventParameterName FBSDKAppEventParameterNameOrderID;
/*
@methodgroup Predefined values to assign to user data store
*/
/// typedef for FBSDKAppEventUserDataType
typedef NSString *const FBSDKAppEventUserDataType NS_TYPED_EXTENSIBLE_ENUM NS_SWIFT_NAME(AppEvents.UserDataType);
/** Parameter key used to specify user's email. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventEmail;
/** Parameter key used to specify user's first name. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventFirstName;
/** Parameter key used to specify user's last name. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventLastName;
/** Parameter key used to specify user's phone. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventPhone;
/** Parameter key used to specify user's date of birth. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventDateOfBirth;
/** Parameter key used to specify user's gender. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventGender;
/** Parameter key used to specify user's city. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventCity;
/** Parameter key used to specify user's state. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventState;
/** Parameter key used to specify user's zip. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventZip;
/** Parameter key used to specify user's country. */
FOUNDATION_EXPORT FBSDKAppEventUserDataType FBSDKAppEventCountry;
/**
Client-side event logging for specialized application analytics available through Facebook App Insights
and for use with Facebook Ads conversion tracking and optimization.
The `FBSDKAppEvents` static class has a few related roles:
+ Logging predefined and application-defined events to Facebook App Insights with a
numeric value to sum across a large number of events, and an optional set of key/value
parameters that define "segments" for this event (e.g., 'purchaserStatus' : 'frequent', or
'gamerLevel' : 'intermediate')
+ Logging events to later be used for ads optimization around lifetime value.
+ Methods that control the way in which events are flushed out to the Facebook servers.
Here are some important characteristics of the logging mechanism provided by `FBSDKAppEvents`:
+ Events are not sent immediately when logged. They're cached and flushed out to the Facebook servers
in a number of situations:
- when an event count threshold is passed (currently 100 logged events).
- when a time threshold is passed (currently 15 seconds).
- when an app has gone to background and is then brought back to the foreground.
+ Events will be accumulated when the app is in a disconnected state, and sent when the connection is
restored and one of the above 'flush' conditions are met.
+ The `FBSDKAppEvents` class is thread-safe in that events may be logged from any of the app's threads.
+ The developer can set the `flushBehavior` on `FBSDKAppEvents` to force the flushing of events to only
occur on an explicit call to the `flush` method.
+ The developer can turn on console debug output for event logging and flushing to the server by using
the `FBSDKLoggingBehaviorAppEvents` value in `[FBSettings setLoggingBehavior:]`.
Some things to note when logging events:
+ There is a limit on the number of unique event names an app can use, on the order of 1000.
+ There is a limit to the number of unique parameter names in the provided parameters that can
be used per event, on the order of 25. This is not just for an individual call, but for all
invocations for that eventName.
+ Event names and parameter names (the keys in the NSDictionary) must be between 2 and 40 characters, and
must consist of alphanumeric characters, _, -, or spaces.
+ The length of each parameter value can be no more than on the order of 100 characters.
*/
NS_SWIFT_NAME(AppEvents)
@interface FBSDKAppEvents : NSObject
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
/*
* Control over event batching/flushing
*/
/**
The current event flushing behavior specifying when events are sent back to Facebook servers.
*/
@property (class, nonatomic, assign) FBSDKAppEventsFlushBehavior flushBehavior;
/**
Set the 'override' App ID for App Event logging.
In some cases, apps want to use one Facebook App ID for login and social presence and another
for App Event logging. (An example is if multiple apps from the same company share an app ID for login, but
want distinct logging.) By default, this value is `nil`, and defers to the `FBSDKAppEventsOverrideAppIDBundleKey`
plist value. If that's not set, it defaults to `[FBSDKSettings appID]`.
This should be set before any other calls are made to `FBSDKAppEvents`. Thus, you should set it in your application
delegate's `application:didFinishLaunchingWithOptions:` delegate.
*/
@property (class, nonatomic, copy, nullable) NSString *loggingOverrideAppID;
/*
The custom user ID to associate with all app events.
The userID is persisted until it is cleared by passing nil.
*/
@property (class, nonatomic, copy, nullable) NSString *userID;
/*
* Basic event logging
*/
/**
Log an event with just an eventName.
@param eventName The name of the event to record. Limitations on number of events and name length
are given in the `FBSDKAppEvents` documentation.
*/
+ (void)logEvent:(FBSDKAppEventName)eventName;
/**
Log an event with an eventName and a numeric value to be aggregated with other events of this name.
@param eventName The name of the event to record. Limitations on number of events and name length
are given in the `FBSDKAppEvents` documentation. Common event names are provided in `FBAppEventName*` constants.
@param valueToSum Amount to be aggregated into all events of this eventName, and App Insights will report
the cumulative and average value of this amount.
*/
+ (void)logEvent:(FBSDKAppEventName)eventName
valueToSum:(double)valueToSum;
/**
Log an event with an eventName and a set of key/value pairs in the parameters dictionary.
Parameter limitations are described above.
@param eventName The name of the event to record. Limitations on number of events and name construction
are given in the `FBSDKAppEvents` documentation. Common event names are provided in `FBAppEventName*` constants.
@param parameters Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
*/
+ (void)logEvent:(FBSDKAppEventName)eventName
parameters:(NSDictionary<FBSDKAppEventParameterName, id> *)parameters;
/**
Log an event with an eventName, a numeric value to be aggregated with other events of this name,
and a set of key/value pairs in the parameters dictionary.
@param eventName The name of the event to record. Limitations on number of events and name construction
are given in the `FBSDKAppEvents` documentation. Common event names are provided in `FBAppEventName*` constants.
@param valueToSum Amount to be aggregated into all events of this eventName, and App Insights will report
the cumulative and average value of this amount.
@param parameters Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
*/
+ (void)logEvent:(FBSDKAppEventName)eventName
valueToSum:(double)valueToSum
parameters:(NSDictionary<FBSDKAppEventParameterName, id> *)parameters;
/**
Log an event with an eventName, a numeric value to be aggregated with other events of this name,
and a set of key/value pairs in the parameters dictionary. Providing session lets the developer
target a particular <FBSession>. If nil is provided, then `[FBSession activeSession]` will be used.
@param eventName The name of the event to record. Limitations on number of events and name construction
are given in the `FBSDKAppEvents` documentation. Common event names are provided in `FBAppEventName*` constants.
@param valueToSum Amount to be aggregated into all events of this eventName, and App Insights will report
the cumulative and average value of this amount. Note that this is an NSNumber, and a value of `nil` denotes
that this event doesn't have a value associated with it for summation.
@param parameters Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
@param accessToken The optional access token to log the event as.
*/
+ (void)logEvent:(FBSDKAppEventName)eventName
valueToSum:(nullable NSNumber *)valueToSum
parameters:(NSDictionary<FBSDKAppEventParameterName, id> *)parameters
accessToken:(nullable FBSDKAccessToken *)accessToken;
/*
* Purchase logging
*/
/**
Log a purchase of the specified amount, in the specified currency.
@param purchaseAmount Purchase amount to be logged, as expressed in the specified currency. This value
will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).
@param currency Currency, is denoted as, e.g. "USD", "EUR", "GBP". See ISO-4217 for
specific values. One reference for these is <http://en.wikipedia.org/wiki/ISO_4217>.
This event immediately triggers a flush of the `FBSDKAppEvents` event queue, unless the `flushBehavior` is set
to `FBSDKAppEventsFlushBehaviorExplicitOnly`.
*/
+ (void)logPurchase:(double)purchaseAmount
currency:(NSString *)currency;
/**
Log a purchase of the specified amount, in the specified currency, also providing a set of
additional characteristics describing the purchase.
@param purchaseAmount Purchase amount to be logged, as expressed in the specified currency.This value
will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).
@param currency Currency, is denoted as, e.g. "USD", "EUR", "GBP". See ISO-4217 for
specific values. One reference for these is <http://en.wikipedia.org/wiki/ISO_4217>.
@param parameters Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
This event immediately triggers a flush of the `FBSDKAppEvents` event queue, unless the `flushBehavior` is set
to `FBSDKAppEventsFlushBehaviorExplicitOnly`.
*/
+ (void)logPurchase:(double)purchaseAmount
currency:(NSString *)currency
parameters:(NSDictionary<NSString *, id> *)parameters;
/**
Log a purchase of the specified amount, in the specified currency, also providing a set of
additional characteristics describing the purchase, as well as an <FBSession> to log to.
@param purchaseAmount Purchase amount to be logged, as expressed in the specified currency.This value
will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346).
@param currency Currency, is denoted as, e.g. "USD", "EUR", "GBP". See ISO-4217 for
specific values. One reference for these is <http://en.wikipedia.org/wiki/ISO_4217>.
@param parameters Arbitrary parameter dictionary of characteristics. The keys to this dictionary must
be NSString's, and the values are expected to be NSString or NSNumber. Limitations on the number of
parameters and name construction are given in the `FBSDKAppEvents` documentation. Commonly used parameter names
are provided in `FBSDKAppEventParameterName*` constants.
@param accessToken The optional access token to log the event as.
This event immediately triggers a flush of the `FBSDKAppEvents` event queue, unless the `flushBehavior` is set
to `FBSDKAppEventsFlushBehaviorExplicitOnly`.
*/
+ (void)logPurchase:(double)purchaseAmount
currency:(NSString *)currency
parameters:(NSDictionary<NSString *, id> *)parameters
accessToken:(nullable FBSDKAccessToken *)accessToken;
/*
* Push Notifications Logging
*/
/**
Log an app event that tracks that the application was open via Push Notification.
@param payload Notification payload received via `UIApplicationDelegate`.
*/
+ (void)logPushNotificationOpen:(NSDictionary *)payload;
/**
Log an app event that tracks that a custom action was taken from a push notification.
@param payload Notification payload received via `UIApplicationDelegate`.
@param action Name of the action that was taken.
*/
+ (void)logPushNotificationOpen:(NSDictionary *)payload action:(NSString *)action;
/**
Uploads product catalog product item as an app event
@param itemID Unique ID for the item. Can be a variant for a product.
Max size is 100.
@param availability If item is in stock. Accepted values are:
in stock - Item ships immediately
out of stock - No plan to restock
preorder - Available in future
available for order - Ships in 1-2 weeks
discontinued - Discontinued
@param condition Product condition: new, refurbished or used.
@param description Short text describing product. Max size is 5000.
@param imageLink Link to item image used in ad.
@param link Link to merchant's site where someone can buy the item.
@param title Title of item.
@param priceAmount Amount of purchase, in the currency specified by the 'currency'
parameter. This value will be rounded to the thousandths place
(e.g., 12.34567 becomes 12.346).
@param currency Currency used to specify the amount.
E.g. "USD", "EUR", "GBP". See ISO-4217 for specific values. One reference for these is <http://en.wikipedia.org/wiki/ISO_4217>
@param gtin Global Trade Item Number including UPC, EAN, JAN and ISBN
@param mpn Unique manufacture ID for product
@param brand Name of the brand
Note: Either gtin, mpn or brand is required.
@param parameters Optional fields for deep link specification.
*/
+ (void)logProductItem:(NSString *)itemID
availability:(FBSDKProductAvailability)availability
condition:(FBSDKProductCondition)condition
description:(NSString *)description
imageLink:(NSString *)imageLink
link:(NSString *)link
title:(NSString *)title
priceAmount:(double)priceAmount
currency:(NSString *)currency
gtin:(nullable NSString *)gtin
mpn:(nullable NSString *)mpn
brand:(nullable NSString *)brand
parameters:(nullable NSDictionary<NSString *, id> *)parameters;
/**
Notifies the events system that the app has launched and, when appropriate, logs an "activated app" event.
This function is called automatically from FBSDKApplicationDelegate applicationDidBecomeActive, unless
one overrides 'FacebookAutoLogAppEventsEnabled' key to false in the project info plist file.
In case 'FacebookAutoLogAppEventsEnabled' is set to false, then it should typically be placed in the
app delegates' `applicationDidBecomeActive:` method.
This method also takes care of logging the event indicating the first time this app has been launched, which, among other things, is used to
track user acquisition and app install ads conversions.
`activateApp` will not log an event on every app launch, since launches happen every time the app is backgrounded and then foregrounded.
"activated app" events will be logged when the app has not been active for more than 60 seconds. This method also causes a "deactivated app"
event to be logged when sessions are "completed", and these events are logged with the session length, with an indication of how much
time has elapsed between sessions, and with the number of background/foreground interruptions that session had. This data
is all visible in your app's App Events Insights.
*/
+ (void)activateApp;
/*
* Push Notifications Registration and Uninstall Tracking
*/
/**
Sets and sends device token to register the current application for push notifications.
Sets and sends a device token from `NSData` representation that you get from `UIApplicationDelegate.-application:didRegisterForRemoteNotificationsWithDeviceToken:`.
@param deviceToken Device token data.
*/
+ (void)setPushNotificationsDeviceToken:(NSData *)deviceToken;
/**
Sets and sends device token string to register the current application for push notifications.
Sets and sends a device token string
@param deviceTokenString Device token string.
*/
+ (void)setPushNotificationsDeviceTokenString:(NSString *)deviceTokenString
NS_SWIFT_NAME(setPushNotificationsDeviceToken(_:));
/**
Explicitly kick off flushing of events to Facebook. This is an asynchronous method, but it does initiate an immediate
kick off. Server failures will be reported through the NotificationCenter with notification ID `FBSDKAppEventsLoggingResultNotification`.
*/
+ (void)flush;
/**
Creates a request representing the Graph API call to retrieve a Custom Audience "third party ID" for the app's Facebook user.
Callers will send this ID back to their own servers, collect up a set to create a Facebook Custom Audience with,
and then use the resultant Custom Audience to target ads.
The JSON in the request's response will include an "custom_audience_third_party_id" key/value pair, with the value being the ID retrieved.
This ID is an encrypted encoding of the Facebook user's ID and the invoking Facebook app ID.
Multiple calls with the same user will return different IDs, thus these IDs cannot be used to correlate behavior
across devices or applications, and are only meaningful when sent back to Facebook for creating Custom Audiences.
The ID retrieved represents the Facebook user identified in the following way: if the specified access token is valid,
the ID will represent the user associated with that token; otherwise the ID will represent the user logged into the
native Facebook app on the device. If there is no native Facebook app, no one is logged into it, or the user has opted out
at the iOS level from ad tracking, then a `nil` ID will be returned.
This method returns `nil` if either the user has opted-out (via iOS) from Ad Tracking, the app itself has limited event usage
via the `[FBSDKSettings limitEventAndDataUsage]` flag, or a specific Facebook user cannot be identified.
@param accessToken The access token to use to establish the user's identity for users logged into Facebook through this app.
If `nil`, then the `[FBSDKAccessToken currentAccessToken]` is used.
*/
+ (nullable FBSDKGraphRequest *)requestForCustomAudienceThirdPartyIDWithAccessToken:(nullable FBSDKAccessToken *)accessToken;
/*
Clears the custom user ID to associate with all app events.
*/
+ (void)clearUserID;
/*
Sets custom user data to associate with all app events. All user data are hashed
and used to match Facebook user from this instance of an application.
The user data will be persisted between application instances.
@param email user's email
@param firstName user's first name
@param lastName user's last name
@param phone user's phone
@param dateOfBirth user's date of birth
@param gender user's gender
@param city user's city
@param state user's state
@param zip user's zip
@param country user's country
*/
+ (void)setUserEmail:(nullable NSString *)email
firstName:(nullable NSString *)firstName
lastName:(nullable NSString *)lastName
phone:(nullable NSString *)phone
dateOfBirth:(nullable NSString *)dateOfBirth
gender:(nullable NSString *)gender
city:(nullable NSString *)city
state:(nullable NSString *)state
zip:(nullable NSString *)zip
country:(nullable NSString *)country
NS_SWIFT_NAME(setUser(email:firstName:lastName:phone:dateOfBirth:gender:city:state:zip:country:));
/*
Returns the set user data else nil
*/
+ (nullable NSString *)getUserData;
/*
Clears the current user data
*/
+ (void)clearUserData;
/*
Sets custom user data to associate with all app events. All user data are hashed
and used to match Facebook user from this instance of an application.
The user data will be persisted between application instances.
@param data data
@param type data type, e.g. FBSDKAppEventEmail, FBSDKAppEventPhone
*/
+ (void)setUserData:(nullable NSString *)data
forType:(FBSDKAppEventUserDataType)type;
/*
Clears the current user data of certain type
*/
+ (void)clearUserDataForType:(FBSDKAppEventUserDataType)type;
/*
Sends a request to update the properties for the current user, set by `setUserID:`
You must call `FBSDKAppEvents setUserID:` before making this call.
@param properties the custom user properties
@param handler the optional completion handler
*/
+ (void)updateUserProperties:(NSDictionary<NSString *, id> *)properties handler:(nullable FBSDKGraphRequestBlock)handler;
#if !TARGET_OS_TV
/*
Intended to be used as part of a hybrid webapp.
If you call this method, the FB SDK will inject a new JavaScript object into your webview.
If the FB Pixel is used within the webview, and references the app ID of this app,
then it will detect the presence of this injected JavaScript object
and pass Pixel events back to the FB SDK for logging using the AppEvents framework.
@param webView The webview to augment with the additional JavaScript behaviour
*/
+ (void)augmentHybridWKWebView:(WKWebView *)webView;
#endif
/*
* Unity helper functions
*/
/**
Set if the Unity is already initialized
@param isUnityInit whether Unity is initialized.
*/
+ (void)setIsUnityInit:(BOOL)isUnityInit;
/*
Send event binding to Unity
*/
+ (void)sendEventBindingsToUnity;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,35 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface FBSDKMetadataIndexer : NSObject
+ (void)enable;
@end
NS_ASSUME_NONNULL_END
#endif

View file

@ -1,329 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKMetadataIndexer.h"
#import <objc/runtime.h>
#import <sys/sysctl.h>
#import <sys/utsname.h>
#import <UIKit/UIKit.h>
#import "FBSDKCoreKit+Internal.h"
static const int FBSDKMetadataIndexerMaxTextLength = 100;
static const int FBSDKMetadataIndexerMaxIndicatorLength = 100;
static const int FBSDKMetadataIndexerMaxValue = 5;
static NSString * const FIELD_K = @"k";
static NSString * const FIELD_V = @"v";
static NSString * const FIELD_K_DELIMITER = @",";
FBSDKAppEventUserDataType FBSDKAppEventRule1 = @"r1";
FBSDKAppEventUserDataType FBSDKAppEventRule2 = @"r2";
static NSArray<FBSDKAppEventUserDataType> *FBSDKMetadataIndexerKeys;
static NSMutableDictionary<NSString *, NSDictionary<NSString *, NSString *> *> *_rules;
static NSMutableDictionary<NSString *, NSMutableArray<NSString *> *> *_store;
static dispatch_queue_t serialQueue;
@implementation FBSDKMetadataIndexer
+ (void)initialize
{
FBSDKMetadataIndexerKeys = @[FBSDKAppEventRule1, FBSDKAppEventRule2];
serialQueue = dispatch_queue_create("com.facebook.appevents.MetadataIndexer", DISPATCH_QUEUE_SERIAL);
}
+ (void)enable
{
if (FBSDKAdvertisingTrackingAllowed != [FBSDKAppEventsUtility advertisingTrackingStatus]) {
return;
}
[FBSDKServerConfigurationManager loadServerConfigurationWithCompletionBlock:^(FBSDKServerConfiguration *serverConfiguration, NSError *error) {
if (error) {
return;
}
[FBSDKMetadataIndexer setupWithRules:serverConfiguration.AAMRules];
}];
}
+ (void)setupWithRules:(NSDictionary<NSString *, id> * _Nullable)rules
{
if (0 == rules.count) {
return;
}
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[FBSDKMetadataIndexer constructRules:rules];
[FBSDKMetadataIndexer initStore];
BOOL isEnabled = NO;
for (NSString *key in FBSDKMetadataIndexerKeys) {
BOOL isRuleEnabled = (nil != [_rules objectForKey:key]);
if (isRuleEnabled) {
isEnabled = YES;
}
if (!isRuleEnabled) {
[_store removeObjectForKey:key];
[FBSDKUserDataStore setHashData:nil forType:key];
}
}
if (isEnabled) {
[FBSDKMetadataIndexer setupMetadataIndexing];
}
});
}
+ (void)initStore
{
_store = [[NSMutableDictionary alloc] init];
for (NSString *key in FBSDKMetadataIndexerKeys) {
NSString *data = [FBSDKUserDataStore getHashedDataForType:key];
if (data.length > 0) {
_store[key] = [NSMutableArray arrayWithArray:[data componentsSeparatedByString:FIELD_K_DELIMITER]];
}
}
for (NSString *key in FBSDKMetadataIndexerKeys) {
if (!_store[key]) {
_store[key] = [[NSMutableArray alloc] init];
}
}
}
+ (void)constructRules:(NSDictionary<NSString *, id> * _Nullable)rules
{
if (!_rules) {
_rules = [[NSMutableDictionary alloc] init];
}
for (NSString *key in rules) {
NSDictionary<NSString *, NSString *> *value = [FBSDKTypeUtility dictionaryValue:rules[key]];
if (value && value[FIELD_K].length > 0 && value[FIELD_V].length > 0) {
_rules[key] = value;
}
}
}
+ (void)setupMetadataIndexing
{
void (^block)(UIView *) = ^(UIView *view) {
// Indexing when the view is removed from window and conforms to UITextInput, and skip UIFieldEditor, which is an internval view of UITextField
if (![view window] && ![NSStringFromClass([view class]) isEqualToString:@"UIFieldEditor"] && [view conformsToProtocol:@protocol(UITextInput)]) {
NSString *text = [FBSDKViewHierarchy getText:view];
NSString *placeholder = [FBSDKViewHierarchy getHint:view];
BOOL secureTextEntry = [self checkSecureTextEntry:view];
NSArray<NSString *> *labels = [self getLabelsOfView:view];
UIKeyboardType keyboardType = [self getKeyboardType:view];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
[self getMetadataWithText:[self normalizedValue:text]
placeholder:[self normalizeField:placeholder]
labels:labels
secureTextEntry:secureTextEntry
inputType:keyboardType];
});
}
};
[FBSDKSwizzler swizzleSelector:@selector(didMoveToWindow) onClass:[UIView class] withBlock:block named:@"metadataIndexingUIView"];
// iOS 12: UITextField implements didMoveToWindow without calling parent implementation
if (@available(iOS 12, *)) {
[FBSDKSwizzler swizzleSelector:@selector(didMoveToWindow) onClass:[UITextField class] withBlock:block named:@"metadataIndexingUITextField"];
} else {
[FBSDKSwizzler swizzleSelector:@selector(didMoveToWindow) onClass:[UIControl class] withBlock:block named:@"metadataIndexingUIControl"];
}
}
+ (NSArray<UIView *> *)getSiblingViewsOfView:(UIView *)view
{
NSObject *parent = [FBSDKViewHierarchy getParent:view];
if (parent) {
NSArray<id> *views = [FBSDKViewHierarchy getChildren:parent];
if (views) {
NSMutableArray<id> *siblings = [NSMutableArray arrayWithArray:views];
[siblings removeObject:view];
return [siblings copy];
}
}
return nil;
}
+ (NSArray<NSString *> *)getLabelsOfView:(UIView *)view
{
NSMutableArray<NSString *> *labels = [[NSMutableArray alloc] init];
NSString *placeholder = [self normalizeField:[FBSDKViewHierarchy getHint:view]];
if (placeholder) {
[labels addObject:placeholder];
}
NSArray<id> *siblingViews = [self getSiblingViewsOfView:view];
for (id sibling in siblingViews) {
if ([sibling isKindOfClass:[UILabel class]]) {
NSString *text = [self normalizeField:[FBSDKViewHierarchy getText:sibling]];
if (text) {
[labels addObject:text];
}
}
}
return [labels copy];
}
+ (BOOL)checkSecureTextEntry:(UIView *)view
{
if ([view isKindOfClass:[UITextField class]]) {
return ((UITextField *)view).secureTextEntry;
}
if ([view isKindOfClass:[UITextView class]]) {
return ((UITextView *)view).secureTextEntry;
}
return NO;
}
+ (UIKeyboardType)getKeyboardType:(UIView *)view
{
if ([view isKindOfClass:[UITextField class]]) {
return ((UITextField *)view).keyboardType;
}
if ([view isKindOfClass:[UITextView class]]) {
return ((UITextView *)view).keyboardType;
}
return UIKeyboardTypeDefault;
}
+ (void)getMetadataWithText:(NSString *)text
placeholder:(NSString *)placeholder
labels:(NSArray<NSString *> *)labels
secureTextEntry:(BOOL)secureTextEntry
inputType:(UIKeyboardType)inputType
{
if (secureTextEntry ||
[placeholder containsString:@"password"] ||
text.length == 0 ||
text.length > FBSDKMetadataIndexerMaxTextLength ||
placeholder.length >= FBSDKMetadataIndexerMaxIndicatorLength) {
return;
}
for (NSString *key in _rules) {
NSDictionary<NSString *, NSString *> *rule = _rules[key];
BOOL isRuleKMatched = [self checkMetadataHint:placeholder matchRuleK:rule[FIELD_K]]
|| [self checkMetadataLabels:labels matchRuleK:rule[FIELD_K]];
BOOL isRuleVMatched = [self checkMetadataText:text matchRuleV:rule[FIELD_V]];
if (isRuleKMatched && isRuleVMatched) {
[FBSDKMetadataIndexer checkAndAppendData:text forKey:key];
}
}
}
#pragma mark - Helper Methods
+ (void)checkAndAppendData:(NSString *)data
forKey:(NSString *)key
{
NSString *hashData = [FBSDKUtility SHA256Hash:data];
dispatch_async(serialQueue, ^{
if (hashData.length == 0 || [_store[key] containsObject:hashData]) {
return;
}
while (_store[key].count >= FBSDKMetadataIndexerMaxValue) {
[_store[key] removeObjectAtIndex:0];
}
[_store[key] addObject:hashData];
[FBSDKUserDataStore setHashData:[_store[key] componentsJoinedByString:@","]
forType:key];
});
}
+ (BOOL)checkMetadataLabels:(NSArray<NSString *> *)labels
matchRuleK:(NSString *)ruleK
{
for (NSString *label in labels) {
if ([self checkMetadataHint:label matchRuleK:ruleK]) {
return YES;
}
}
return NO;
}
+ (BOOL)checkMetadataHint:(NSString *)hint
matchRuleK:(NSString *)ruleK
{
if (hint.length > 0 && ruleK) {
NSArray<NSString *> *items = [ruleK componentsSeparatedByString:@","];
for (NSString *item in items) {
if ([hint containsString:item]) {
return YES;
}
}
}
return NO;
}
+ (BOOL)checkMetadataText:(NSString *)text
matchRuleV:(NSString *)ruleV
{
if (text.length > 0 && ruleV) {
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:ruleV
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger matches = [regex numberOfMatchesInString:text options:0 range:NSMakeRange(0, text.length)];
NSString *prunedText = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"+- ()."]] componentsJoinedByString:@""];
NSUInteger prunedMatches = [regex numberOfMatchesInString:prunedText options:0 range:NSMakeRange(0, prunedText.length)];
return matches > 0 || prunedMatches > 0;
}
return NO;
}
+ (NSString *)normalizeField:(NSString *)field
{
if (!field) {
return nil;
}
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[_-]|\\s"
options:NSRegularExpressionCaseInsensitive
error:nil];
return [regex stringByReplacingMatchesInString:field
options:0
range:NSMakeRange(0, field.length)
withTemplate:@""].lowercaseString;
}
+ (NSString *)normalizedValue:(NSString *)value
{
if (!value) {
return nil;
}
return [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].lowercaseString;
}
@end
#endif

View file

@ -1,40 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void(^FBSDKCodelessSettingLoadBlock)(BOOL isCodelessSetupEnabled, NSError *_Nullable error);
NS_SWIFT_NAME(CodelessIndexer)
@interface FBSDKCodelessIndexer : NSObject
@property (class, nonatomic, copy, readonly) NSString *extInfo;
+ (void)enable;
@end
NS_ASSUME_NONNULL_END
#endif

View file

@ -1,414 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKCodelessIndexer.h"
#import <objc/runtime.h>
#import <sys/sysctl.h>
#import <sys/utsname.h>
#import <UIKit/UIKit.h>
#import "FBSDKCoreKit+Internal.h"
#import "FBSDKGraphRequest.h"
#import "FBSDKSettings.h"
@implementation FBSDKCodelessIndexer
static BOOL _isCodelessIndexing;
static BOOL _isCheckingSession;
static BOOL _isCodelessIndexingEnabled;
static BOOL _isGestureSet;
static NSMutableDictionary<NSString *, id> *_codelessSetting;
static const NSTimeInterval kTimeout = 4.0;
static NSString *_deviceSessionID;
static NSTimer *_appIndexingTimer;
static NSString *_lastTreeHash;
+ (void)enable
{
if (_isGestureSet) {
return;
}
#if TARGET_OS_SIMULATOR
[self setupGesture];
#else
[self loadCodelessSettingWithCompletionBlock:^(BOOL isCodelessSetupEnabled, NSError *error) {
if (isCodelessSetupEnabled) {
[self setupGesture];
}
}];
#endif
}
// DO NOT call this function, it is only called once in the load function
+ (void)loadCodelessSettingWithCompletionBlock:(FBSDKCodelessSettingLoadBlock)completionBlock
{
NSString *appID = [FBSDKSettings appID];
if (appID == nil) {
return;
}
[FBSDKServerConfigurationManager loadServerConfigurationWithCompletionBlock:^(FBSDKServerConfiguration *serverConfiguration, NSError *serverConfigurationLoadingError) {
if (!serverConfiguration.codelessEventsEnabled) {
return;
}
// load the defaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *defaultKey = [NSString stringWithFormat:CODELESS_SETTING_KEY, appID];
NSData *data = [defaults objectForKey:defaultKey];
if ([data isKindOfClass:[NSData class]]) {
NSMutableDictionary<NSString *, id> *codelessSetting = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if (codelessSetting) {
_codelessSetting = codelessSetting;
}
}
if (!_codelessSetting) {
_codelessSetting = [[NSMutableDictionary alloc] init];
}
if (![self _codelessSetupTimestampIsValid:[_codelessSetting objectForKey:CODELESS_SETTING_TIMESTAMP_KEY]]) {
FBSDKGraphRequest *request = [self requestToLoadCodelessSetup:appID];
if (request == nil) {
return;
}
FBSDKGraphRequestConnection *requestConnection = [[FBSDKGraphRequestConnection alloc] init];
requestConnection.timeout = kTimeout;
[requestConnection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *codelessLoadingError) {
if (codelessLoadingError) {
return;
}
NSDictionary<NSString *, id> *resultDictionary = [FBSDKTypeUtility dictionaryValue:result];
if (resultDictionary) {
BOOL isCodelessSetupEnabled = [FBSDKTypeUtility boolValue:resultDictionary[CODELESS_SETUP_ENABLED_FIELD]];
[_codelessSetting setObject:@(isCodelessSetupEnabled) forKey:CODELESS_SETUP_ENABLED_KEY];
[_codelessSetting setObject:[NSDate date] forKey:CODELESS_SETTING_TIMESTAMP_KEY];
// update the cached copy in user defaults
[defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:_codelessSetting] forKey:defaultKey];
completionBlock(isCodelessSetupEnabled, codelessLoadingError);
}
}];
[requestConnection start];
} else {
completionBlock([FBSDKTypeUtility boolValue:[_codelessSetting objectForKey:CODELESS_SETUP_ENABLED_KEY]], nil);
}
}];
}
+ (FBSDKGraphRequest *)requestToLoadCodelessSetup:(NSString *)appID
{
NSString *advertiserID = [FBSDKAppEventsUtility advertiserID];
if (!advertiserID) {
return nil;
}
NSDictionary<NSString *, NSString *> *parameters = @{
@"fields": CODELESS_SETUP_ENABLED_FIELD,
@"advertiser_id": advertiserID
};
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:appID
parameters:parameters
tokenString:nil
HTTPMethod:nil
flags:FBSDKGraphRequestFlagSkipClientToken | FBSDKGraphRequestFlagDisableErrorRecovery];
return request;
}
+ (BOOL)_codelessSetupTimestampIsValid:(NSDate *)timestamp
{
return (timestamp != nil && [[NSDate date] timeIntervalSinceDate:timestamp] < CODELESS_SETTING_CACHE_TIMEOUT);
}
+ (void)setupGesture
{
_isGestureSet = YES;
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
Class class = [UIApplication class];
[FBSDKSwizzler swizzleSelector:@selector(motionBegan:withEvent:) onClass:class withBlock:^{
if ([FBSDKServerConfigurationManager cachedServerConfiguration].isCodelessEventsEnabled) {
[self checkCodelessIndexingSession];
}
} named:@"motionBegan"];
}
+ (void)checkCodelessIndexingSession
{
if (_isCheckingSession) return;
_isCheckingSession = YES;
NSDictionary *parameters = @{
CODELESS_INDEXING_SESSION_ID_KEY: [self currentSessionDeviceID],
CODELESS_INDEXING_EXT_INFO_KEY: [self extInfo]
};
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:@"%@/%@",
[FBSDKSettings appID], CODELESS_INDEXING_SESSION_ENDPOINT]
parameters:parameters
HTTPMethod:FBSDKHTTPMethodPOST];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
_isCheckingSession = NO;
if ([result isKindOfClass:[NSDictionary class]]) {
_isCodelessIndexingEnabled = [((NSDictionary *)result)[CODELESS_INDEXING_STATUS_KEY] boolValue];
if (_isCodelessIndexingEnabled) {
_lastTreeHash = nil;
if (!_appIndexingTimer) {
_appIndexingTimer = [NSTimer timerWithTimeInterval:CODELESS_INDEXING_UPLOAD_INTERVAL_IN_SECONDS
target:self
selector:@selector(startIndexing)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:_appIndexingTimer forMode:NSDefaultRunLoopMode];
}
} else {
_deviceSessionID = nil;
}
}
}];
}
+ (NSString *)currentSessionDeviceID
{
if (!_deviceSessionID) {
_deviceSessionID = [NSUUID UUID].UUIDString;
}
return _deviceSessionID;
}
+ (NSString *)extInfo
{
struct utsname systemInfo;
uname(&systemInfo);
NSString *machine = @(systemInfo.machine);
NSString *advertiserID = [FBSDKAppEventsUtility advertiserID] ?: @"";
machine = machine ?: @"";
NSString *debugStatus = [FBSDKAppEventsUtility isDebugBuild] ? @"1" : @"0";
#if TARGET_IPHONE_SIMULATOR
NSString *isSimulator = @"1";
#else
NSString *isSimulator = @"0";
#endif
NSLocale *locale = [NSLocale currentLocale];
NSString *languageCode = [locale objectForKey:NSLocaleLanguageCode];
NSString *countryCode = [locale objectForKey:NSLocaleCountryCode];
NSString *localeString = locale.localeIdentifier;
if (languageCode && countryCode) {
localeString = [NSString stringWithFormat:@"%@_%@", languageCode, countryCode];
}
NSString *extinfo = [FBSDKBasicUtility JSONStringForObject:@[machine,
advertiserID,
debugStatus,
isSimulator,
localeString]
error:NULL
invalidObjectHandler:NULL];
return extinfo ?: @"";
}
+ (void)startIndexing {
if (!_isCodelessIndexingEnabled) {
return;
}
if (UIApplicationStateActive != [UIApplication sharedApplication].applicationState) {
return;
}
// If userAgentSuffix begins with Unity, trigger unity code to upload view hierarchy
NSString *userAgentSuffix = [FBSDKSettings userAgentSuffix];
if (userAgentSuffix != nil && [userAgentSuffix hasPrefix:@"Unity"]) {
Class FBUnityUtility = objc_lookUpClass("FBUnityUtility");
SEL selector = NSSelectorFromString(@"triggerUploadViewHierarchy");
if (FBUnityUtility && selector && [FBUnityUtility respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[FBUnityUtility performSelector:selector];
#pragma clang diagnostic pop
}
} else {
[self uploadIndexing];
}
}
+ (void)uploadIndexing
{
if (_isCodelessIndexing) {
return;
}
NSString *tree = [FBSDKCodelessIndexer currentViewTree];
[self uploadIndexing:tree];
}
+ (void)uploadIndexing:(NSString *)tree
{
if (_isCodelessIndexing) {
return;
}
if (!tree) {
return;
}
NSString *currentTreeHash = [FBSDKUtility SHA256Hash:tree];
if (_lastTreeHash && [_lastTreeHash isEqualToString:currentTreeHash]) {
return;
}
_lastTreeHash = currentTreeHash;
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *version = [mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:@"%@/%@",
[FBSDKSettings appID], CODELESS_INDEXING_ENDPOINT]
parameters:@{
CODELESS_INDEXING_TREE_KEY: tree,
CODELESS_INDEXING_APP_VERSION_KEY: version ?: @"",
CODELESS_INDEXING_PLATFORM_KEY: @"iOS",
CODELESS_INDEXING_SESSION_ID_KEY: [self currentSessionDeviceID]
}
HTTPMethod:FBSDKHTTPMethodPOST];
_isCodelessIndexing = YES;
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
_isCodelessIndexing = NO;
if ([result isKindOfClass:[NSDictionary class]]) {
_isCodelessIndexingEnabled = [result[CODELESS_INDEXING_STATUS_KEY] boolValue];
if (!_isCodelessIndexingEnabled) {
_deviceSessionID = nil;
}
}
}];
}
+ (NSString *)currentViewTree
{
NSMutableArray *trees = [NSMutableArray array];
NSArray *windows = [UIApplication sharedApplication].windows;
for (UIWindow *window in windows) {
NSDictionary *tree = [FBSDKCodelessIndexer recursiveCaptureTree:window];
if (tree) {
if (window.isKeyWindow) {
[trees insertObject:tree atIndex:0];
} else {
[trees addObject:tree];
}
}
}
if (0 == trees.count) {
return nil;
}
NSArray *viewTrees = [trees reverseObjectEnumerator].allObjects;
NSData *data = UIImageJPEGRepresentation([FBSDKCodelessIndexer screenshot], 0.5);
NSString *screenshot = [data base64EncodedStringWithOptions:0];
NSMutableDictionary *treeInfo = [NSMutableDictionary dictionary];
treeInfo[@"view"] = viewTrees;
treeInfo[@"screenshot"] = screenshot ?: @"";
NSString *tree = nil;
data = [NSJSONSerialization dataWithJSONObject:treeInfo options:0 error:nil];
if (data) {
tree = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
return tree;
}
+ (NSDictionary<NSString *, id> *)recursiveCaptureTree:(NSObject *)obj
{
if (!obj) {
return nil;
}
NSMutableDictionary *result = [FBSDKViewHierarchy getDetailAttributesOf:obj];
NSArray *children = [FBSDKViewHierarchy getChildren:obj];
NSMutableArray *childrenTrees = [NSMutableArray array];
for (NSObject *child in children) {
NSDictionary *objTree = [self recursiveCaptureTree:child];
[childrenTrees addObject:objTree];
}
if (childrenTrees.count > 0) {
[result setValue:[childrenTrees copy] forKey:VIEW_HIERARCHY_CHILD_VIEWS_KEY];
}
return [result copy];
}
+ (UIImage *)screenshot {
UIWindow *window = [UIApplication sharedApplication].delegate.window;
UIGraphicsBeginImageContext(window.bounds.size);
[window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
+ (NSDictionary<NSString *, NSNumber *> *)dimensionOf:(NSObject *)obj
{
UIView *view = nil;
if ([obj isKindOfClass:[UIView class]]) {
view = (UIView *)obj;
} else if ([obj isKindOfClass:[UIViewController class]]) {
view = ((UIViewController *)obj).view;
}
CGRect frame = view.frame;
CGPoint offset = CGPointZero;
if ([view isKindOfClass:[UIScrollView class]])
offset = ((UIScrollView *)view).contentOffset;
return @{
CODELESS_VIEW_TREE_TOP_KEY: @((int)frame.origin.y),
CODELESS_VIEW_TREE_LEFT_KEY: @((int)frame.origin.x),
CODELESS_VIEW_TREE_WIDTH_KEY: @((int)frame.size.width),
CODELESS_VIEW_TREE_HEIGHT_KEY: @((int)frame.size.height),
CODELESS_VIEW_TREE_OFFSET_X_KEY: @((int)offset.x),
CODELESS_VIEW_TREE_OFFSET_Y_KEY: @((int)offset.y),
CODELESS_VIEW_TREE_VISIBILITY_KEY: view.isHidden ? @4 : @0
};
}
@end
#endif

View file

@ -1,37 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
NS_SWIFT_NAME(CodelessParameterComponent)
@interface FBSDKCodelessParameterComponent : NSObject
@property (nonatomic, copy, readonly) NSString *name;
@property (nonatomic, copy, readonly) NSString *value;
@property (nonatomic, readonly) NSArray *path;
@property (nonatomic, copy, readonly) NSString *pathType;
- (instancetype)initWithJSON:(NSDictionary *)dict;
@end
#endif

View file

@ -1,50 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKCodelessParameterComponent.h"
#import "FBSDKCodelessPathComponent.h"
#import "FBSDKViewHierarchyMacros.h"
@implementation FBSDKCodelessParameterComponent
- (instancetype)initWithJSON:(NSDictionary *)dict {
if (self = [super init]) {
_name = [dict[CODELESS_MAPPING_PARAMETER_NAME_KEY] copy];
_value = [dict[CODELESS_MAPPING_PARAMETER_VALUE_KEY] copy];
_pathType = [dict[CODELESS_MAPPING_PATH_TYPE_KEY] copy];
NSArray *ary = dict[CODELESS_MAPPING_PATH_KEY];
NSMutableArray *mut = [NSMutableArray array];
for (NSDictionary *info in ary) {
FBSDKCodelessPathComponent *component = [[FBSDKCodelessPathComponent alloc] initWithJSON:info];
[mut addObject:component];
}
_path = [mut copy];
}
return self;
}
@end
#endif

View file

@ -1,51 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
typedef NS_OPTIONS(int, FBSDKCodelessMatchBitmaskField)
{
FBSDKCodelessMatchBitmaskFieldID = 1,
FBSDKCodelessMatchBitmaskFieldText = 1 << 1,
FBSDKCodelessMatchBitmaskFieldTag = 1 << 2,
FBSDKCodelessMatchBitmaskFieldDescription = 1 << 3,
FBSDKCodelessMatchBitmaskFieldHint = 1 << 4
};
NS_SWIFT_NAME(CodelessPathComponent)
@interface FBSDKCodelessPathComponent : NSObject
@property (nonatomic, copy, readonly) NSString *className;
@property (nonatomic, copy, readonly) NSString *text;
@property (nonatomic, copy, readonly) NSString *hint;
@property (nonatomic, copy, readonly) NSString *desc; // description
@property (nonatomic, readonly) int index;
@property (nonatomic, readonly) int tag;
@property (nonatomic, readonly) int section;
@property (nonatomic, readonly) int row;
@property (nonatomic, readonly) int matchBitmask;
- (instancetype)initWithJSON:(NSDictionary*)dict;
@end
#endif

View file

@ -1,64 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKCodelessPathComponent.h"
#import "FBSDKViewHierarchyMacros.h"
@implementation FBSDKCodelessPathComponent
- (instancetype)initWithJSON:(NSDictionary *)dict {
if (self = [super init]) {
_className = [dict[CODELESS_MAPPING_CLASS_NAME_KEY] copy];
_text = [dict[CODELESS_MAPPING_TEXT_KEY] copy];
_hint = [dict[CODELESS_MAPPING_HINT_KEY] copy];
_desc = [dict[CODELESS_MAPPING_DESC_KEY] copy];
if (dict[CODELESS_MAPPING_INDEX_KEY]) {
_index = [dict[CODELESS_MAPPING_INDEX_KEY] intValue];
} else {
_index = -1;
}
if (dict[CODELESS_MAPPING_SECTION_KEY]) {
_section = [dict[CODELESS_MAPPING_SECTION_KEY] intValue];
} else {
_section = -1;
}
if (dict[CODELESS_MAPPING_ROW_KEY]) {
_row = [dict[CODELESS_MAPPING_ROW_KEY] intValue];
} else {
_row = -1;
}
_tag = [dict[CODELESS_MAPPING_TAG_KEY] intValue];
_matchBitmask = [dict[CODELESS_MAPPING_MATCH_BITMASK_KEY] intValue];
}
return self;
}
@end
#endif

View file

@ -1,42 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <UIKit/UIKit.h>
NS_SWIFT_NAME(EventBinding)
@interface FBSDKEventBinding : NSObject
@property (nonatomic, copy, readonly) NSString *eventName;
@property (nonatomic, copy, readonly) NSString *eventType;
@property (nonatomic, copy, readonly) NSString *appVersion;
@property (nonatomic, readonly) NSArray *path;
@property (nonatomic, copy, readonly) NSString *pathType;
@property (nonatomic, readonly) NSArray *parameters;
+ (BOOL)isViewMatchPath:(UIView *)view path:(NSArray *)path;
+ (BOOL)isPath:(NSArray *)path matchViewPath:(NSArray *)viewPath;
- (FBSDKEventBinding *)initWithJSON:(NSDictionary *)dict;
- (void)trackEvent:(id)sender;
@end
#endif

View file

@ -1,282 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKEventBinding.h"
#import "FBSDKAppEvents.h"
#import "FBSDKAppEventsUtility.h"
#import "FBSDKCodelessParameterComponent.h"
#import "FBSDKCodelessPathComponent.h"
#import "FBSDKSwizzler.h"
#import "FBSDKUtility.h"
#import "FBSDKViewHierarchy.h"
#import "FBSDKViewHierarchyMacros.h"
#define CODELESS_PATH_TYPE_ABSOLUTE @"absolute"
#define CODELESS_PATH_TYPE_RELATIVE @"relative"
#define CODELESS_CODELESS_EVENT_KEY @"_is_fb_codeless"
#define PARAMETER_NAME_PRICE @"_valueToSum"
@implementation FBSDKEventBinding
- (FBSDKEventBinding *)initWithJSON:(NSDictionary *)dict
{
if ((self = [super init])) {
_eventName = [dict[CODELESS_MAPPING_EVENT_NAME_KEY] copy];
_eventType = [dict[CODELESS_MAPPING_EVENT_TYPE_KEY] copy];
_appVersion = [dict[CODELESS_MAPPING_APP_VERSION_KEY] copy];
_pathType = [dict[CODELESS_MAPPING_PATH_TYPE_KEY] copy];
NSArray *pathComponents = dict[CODELESS_MAPPING_PATH_KEY];
NSMutableArray *mut = [NSMutableArray array];
for (NSDictionary *info in pathComponents) {
FBSDKCodelessPathComponent *component = [[FBSDKCodelessPathComponent alloc] initWithJSON:info];
[mut addObject:component];
}
_path = [mut copy];
NSArray *parameters = dict[CODELESS_MAPPING_PARAMETERS_KEY];
mut = [NSMutableArray array];
for (NSDictionary *info in parameters) {
FBSDKCodelessParameterComponent *component = [[FBSDKCodelessParameterComponent alloc] initWithJSON:info];
[mut addObject:component];
}
_parameters = [mut copy];
}
return self;
}
- (void)trackEvent:(id)sender
{
UIView *sourceView = [sender isKindOfClass:[UIView class]] ? (UIView *)sender : nil;
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[CODELESS_CODELESS_EVENT_KEY] = @"1";
for (FBSDKCodelessParameterComponent *component in self.parameters) {
NSString *text = component.value;
if (!text || text.length == 0) {
text = [FBSDKEventBinding findParameterOfPath:component.path
pathType:component.pathType
sourceView:sourceView];
}
if (text) {
if ([component.name isEqualToString:PARAMETER_NAME_PRICE]) {
NSNumber *value = [FBSDKAppEventsUtility getNumberValue:text];
params[component.name] = value;
} else {
params[component.name] = text;
}
}
}
[FBSDKAppEvents logEvent:_eventName parameters:[params copy]];
}
+ (BOOL)matchAnyView:(NSArray *)views
pathComponent:(FBSDKCodelessPathComponent *)component
{
for (NSObject *view in views) {
if ([self match:view pathComponent:component]) {
return YES;
}
}
return NO;
}
+ (BOOL)match:(NSObject *)view
pathComponent:(FBSDKCodelessPathComponent *)component
{
NSString *className = NSStringFromClass([view class]);
if (![className isEqualToString:component.className]) {
return NO;
}
if (component.index >= 0) {
NSObject *parent = [FBSDKViewHierarchy getParent:view];
if (parent) {
NSArray *children = [FBSDKViewHierarchy getChildren:[FBSDKViewHierarchy getParent:view]];
NSUInteger index = [children indexOfObject:view];
if (index == NSNotFound || index != component.index) {
return NO;
}
} else {
if (0 != component.index) {
return NO;
}
}
}
if ((component.matchBitmask & FBSDKCodelessMatchBitmaskFieldText) > 0) {
NSString *text = [FBSDKViewHierarchy getText:view];
BOOL match = ((text.length == 0 && component.text.length == 0)
|| [text isEqualToString:component.text]);
if (!match) {
return NO;
}
}
if ((component.matchBitmask & FBSDKCodelessMatchBitmaskFieldTag) > 0
&& [view isKindOfClass:[UIView class]]
&& component.tag != ((UIView *)view).tag) {
return NO;
}
if ((component.matchBitmask & FBSDKCodelessMatchBitmaskFieldHint) > 0) {
NSString *hint = [FBSDKViewHierarchy getHint:view];
BOOL match = ((hint.length == 0 && component.hint.length == 0)
|| [hint isEqualToString:component.hint]);
if (!match) {
return NO;
}
}
return YES;
}
+ (BOOL)isViewMatchPath:(UIView *)view path:(NSArray *)path
{
NSArray *viewPath = [FBSDKViewHierarchy getPath:view];
BOOL isMatch = [self isPath:path matchViewPath:viewPath];
return isMatch;
}
+ (BOOL)isPath:(NSArray *)path matchViewPath:(NSArray *)viewPath {
for (NSInteger i = 0; i < MIN(path.count, viewPath.count); i++) {
NSInteger idxPath = path.count - i - 1;
NSInteger idxViewPath = viewPath.count - i - 1;
FBSDKCodelessPathComponent *pathComponent = path[idxPath];
FBSDKCodelessPathComponent *viewPathComponent = viewPath[idxViewPath];
if (![pathComponent.className isEqualToString:viewPathComponent.className]) {
return NO;
}
if (pathComponent.index >= 0
&& pathComponent.index != viewPathComponent.index) {
return NO;
}
if ((pathComponent.matchBitmask & FBSDKCodelessMatchBitmaskFieldText) > 0) {
NSString *text = viewPathComponent.text;
BOOL match = ((text.length == 0 && pathComponent.text.length == 0)
|| [text isEqualToString:pathComponent.text]
|| [[FBSDKUtility SHA256Hash:text] isEqualToString:pathComponent.text]);
if (!match) {
return NO;
}
}
if ((pathComponent.matchBitmask & FBSDKCodelessMatchBitmaskFieldTag) > 0
&& pathComponent.tag != viewPathComponent.tag) {
return NO;
}
if ((pathComponent.matchBitmask & FBSDKCodelessMatchBitmaskFieldHint) > 0) {
NSString *hint = viewPathComponent.hint;
BOOL match = ((hint.length == 0 && pathComponent.hint.length == 0)
|| [hint isEqualToString:pathComponent.hint]
|| [[FBSDKUtility SHA256Hash:hint] isEqualToString:pathComponent.hint]);
if (!match) {
return NO;
}
}
}
return YES;
}
+ (NSObject *)findViewByPath:(NSArray *)path parent:(NSObject *)parent level:(int)level {
if (level >= path.count) {
return nil;
}
FBSDKCodelessPathComponent *pathComponent = path[level];
// If found parent, skip to next level
if ([pathComponent.className isEqualToString:CODELESS_MAPPING_PARENT_CLASS_NAME]) {
NSObject *nextParent = [FBSDKViewHierarchy getParent:parent];
return [FBSDKEventBinding findViewByPath:path parent:nextParent level:level + 1];
} else if ([pathComponent.className isEqualToString:CODELESS_MAPPING_CURRENT_CLASS_NAME]) {
return parent;
}
NSArray *children;
if (parent) {
children = [FBSDKViewHierarchy getChildren:parent];
} else {
UIWindow *window = [UIApplication sharedApplication].delegate.window;
if (window) {
children = @[window];
} else {
return nil;
}
}
if (path.count - 1 == level) {
int index = pathComponent.index;
if (index >= 0) {
NSObject *child = index < children.count ? children[index] : nil;
if ([self match:child pathComponent:pathComponent]) {
return child;
}
} else {
for (NSObject *child in children) {
if ([self match:child pathComponent:pathComponent]) {
return child;
}
}
}
} else {
for (NSObject *child in children) {
NSObject *result = [self findViewByPath:path parent:child level:level + 1];
if (result) {
return result;
}
}
}
return nil;
}
// MARK: - find event parameters via relative path
+ (NSString *)findParameterOfPath:(NSArray *)path
pathType:(NSString *)pathType
sourceView:(UIView *)sourceView {
if (0 == path.count) {
return nil;
}
UIView *rootView = sourceView;
if (![pathType isEqualToString:CODELESS_PATH_TYPE_RELATIVE]) {
rootView = nil;
}
NSObject *foundObj = [self findViewByPath:path parent:rootView level:0];
return [FBSDKViewHierarchy getText:foundObj];
}
@end
#endif

View file

@ -1,34 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
NS_SWIFT_NAME(EventBindingManager)
@interface FBSDKEventBindingManager : NSObject
- (FBSDKEventBindingManager*)initWithJSON:(NSDictionary*)dict;
- (void)updateBindings:(NSArray *)bindings;
+ (NSArray *)parseArray:(NSArray *)array;
@end
#endif

View file

@ -1,397 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKEventBindingManager.h"
#import <objc/runtime.h>
#import <UIKit/UIKit.h>
#import "FBSDKCodelessPathComponent.h"
#import "FBSDKEventBinding.h"
#import "FBSDKSwizzler.h"
#import "FBSDKTypeUtility.h"
#import "FBSDKViewHierarchy.h"
#import "FBSDKViewHierarchyMacros.h"
#define ReactNativeTargetKey @"target"
#define ReactNativeTouchEndEventName @"touchEnd"
#define ReactNativeClassRCTTextView "RCTTextView"
#define ReactNativeClassRCTImageView "RCTImageVIew"
#define ReactNativeClassRCTTouchEvent "RCTTouchEvent"
#define ReactNativeClassRCTTouchHandler "RCTTouchHandler"
@interface FBSDKEventBindingManager ()
{
BOOL isStarted;
NSMutableDictionary *reactBindings;
NSSet *validClasses;
BOOL hasReactNative;
NSArray *eventBindings;
}
@end
@implementation FBSDKEventBindingManager
- (id)init {
self = [super init];
if (self) {
isStarted = NO;
hasReactNative = NO;
reactBindings = [NSMutableDictionary dictionary];
NSMutableSet *classes = [NSMutableSet set];
[classes addObject:[UIControl class]];
[classes addObject:[UITableView class]];
[classes addObject:[UICollectionView class]];
// ReactNative
Class classRCTRootView = objc_lookUpClass(ReactNativeClassRCTRootView);
if (classRCTRootView != nil) {
hasReactNative = YES;
Class classRCTView = objc_lookUpClass(ReactNativeClassRCTView);
Class classRCTTextView = objc_lookUpClass(ReactNativeClassRCTTextView);
Class classRCTImageView = objc_lookUpClass(ReactNativeClassRCTImageView);
if (classRCTView) {
[classes addObject:classRCTView];
}
if (classRCTTextView) {
[classes addObject:classRCTTextView];
}
if (classRCTImageView) {
[classes addObject:classRCTImageView];
}
}
validClasses = [NSSet setWithSet:classes];
}
return self;
}
+ (NSArray *)parseArray:(NSArray *)array {
NSMutableArray *result = [NSMutableArray array];
for (NSDictionary *json in array) {
FBSDKEventBinding *binding = [[FBSDKEventBinding alloc] initWithJSON:json];
[result addObject:binding];
}
return [result copy];
}
- (FBSDKEventBindingManager*)initWithJSON:(NSDictionary*)dict
{
if ((self = [super init])) {
NSArray *eventBindingsDict = [FBSDKTypeUtility arrayValue:dict[@"event_bindings"]];
NSMutableArray *bindings = [NSMutableArray array];
for (NSDictionary *d in eventBindingsDict) {
FBSDKEventBinding *e = [[FBSDKEventBinding alloc] initWithJSON:d];
[bindings addObject:e];
}
eventBindings = [bindings copy];
}
return self;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
- (void)start
{
if (isStarted) {
return;
}
if (0 == eventBindings.count) {
return;
}
isStarted = YES;
void (^blockToWindow)(id view) = ^(id view) {
[self matchView:view delegate:nil];
};
[FBSDKSwizzler swizzleSelector:@selector(didMoveToWindow)
onClass:[UIControl class]
withBlock:blockToWindow named:@"map_control"];
// ReactNative
if (hasReactNative) { // If app is built via ReactNative
Class classRCTView = objc_lookUpClass(ReactNativeClassRCTView);
Class classRCTTextView = objc_lookUpClass(ReactNativeClassRCTTextView);
Class classRCTImageView = objc_lookUpClass(ReactNativeClassRCTImageView);
Class classRCTTouchHandler = objc_lookUpClass(ReactNativeClassRCTTouchHandler);
// All react-native views would be added tp RCTRootView, so no need to check didMoveToWindow
[FBSDKSwizzler swizzleSelector:@selector(didMoveToWindow)
onClass:classRCTView
withBlock:blockToWindow
named:@"match_react_native"];
[FBSDKSwizzler swizzleSelector:@selector(didMoveToWindow)
onClass:classRCTTextView
withBlock:blockToWindow
named:@"match_react_native"];
[FBSDKSwizzler swizzleSelector:@selector(didMoveToWindow)
onClass:classRCTImageView
withBlock:blockToWindow
named:@"match_react_native"];
// RCTTouchHandler handles with touch events, like touchEnd and uses RCTEventDispather to dispatch events, so we can check _updateAndDispatchTouches to fire events
[FBSDKSwizzler swizzleSelector:@selector(_updateAndDispatchTouches:eventName:) onClass:classRCTTouchHandler withBlock:^(id touchHandler, SEL command, id touches, id eventName){
if ([touches isKindOfClass:[NSSet class]] && [eventName isKindOfClass:[NSString class]]) {
@try {
NSString *reactEventName = (NSString *)eventName;
NSSet<UITouch *> *reactTouches = (NSSet<UITouch *> *)touches;
if ([reactEventName isEqualToString:ReactNativeTouchEndEventName]) {
for (UITouch *touch in reactTouches) {
UIView *targetView = ((UITouch *)touch).view.superview;
NSNumber *reactTag = nil;
// Find the closest React-managed touchable view like RCTTouchHandler
while(targetView) {
reactTag = [FBSDKViewHierarchy getViewReactTag:targetView];
if (reactTag != nil && targetView.userInteractionEnabled) {
break;
}
targetView = targetView.superview;
}
FBSDKEventBinding *eventBinding = self->reactBindings[reactTag];
if (reactTag != nil && eventBinding != nil) {
[eventBinding trackEvent:nil];
}
}
}
}
@catch(NSException *exception) {
// Catch exception here to prevent LytroKit from crashing app
}
}
} named:@"dispatch_rn_event"];
}
// UITableView
void (^tableViewBlock)(UITableView *tableView,
SEL cmd,
id<UITableViewDelegate> delegate) =
^(UITableView *tableView, SEL cmd, id<UITableViewDelegate> delegate) {
if (!delegate) {
return;
}
[self matchView:tableView delegate:delegate];
};
[FBSDKSwizzler swizzleSelector:@selector(setDelegate:)
onClass:[UITableView class]
withBlock:tableViewBlock
named:@"match_table_view"];
// UICollectionView
void (^collectionViewBlock)(UICollectionView *collectionView,
SEL cmd,
id<UICollectionViewDelegate> delegate) =
^(UICollectionView *collectionView, SEL cmd, id<UICollectionViewDelegate> delegate) {
if (nil == delegate) {
return;
}
[self matchView:collectionView delegate:delegate];
};
[FBSDKSwizzler swizzleSelector:@selector(setDelegate:)
onClass:[UICollectionView class]
withBlock:collectionViewBlock
named:@"handle_collection_view"];
}
- (void)rematchBindings {
if (0 == eventBindings.count) {
return;
}
NSArray *windows = [UIApplication sharedApplication].windows;
for (UIWindow *window in windows) {
[self matchSubviewsIn:window];
}
}
- (void)matchSubviewsIn:(UIView *)view {
if (!view) {
return;
}
for (UIView *subview in view.subviews) {
BOOL isValidClass = NO;
for (Class cls in validClasses) {
if ([subview isKindOfClass:cls]) {
isValidClass = YES;
break;
}
}
if (isValidClass) {
if ([subview isKindOfClass:[UITableView class]]) {
UITableView *tableView = (UITableView *)subview;
if (tableView.delegate) {
[self matchView:subview delegate:tableView.delegate];
}
} else if ([subview isKindOfClass:[UICollectionView class]]) {
UICollectionView *collectionView = (UICollectionView *)subview;
if (collectionView.delegate) {
[self matchView:subview delegate:collectionView.delegate];
}
} else {
[self matchView:subview delegate:nil];
}
}
if (![subview isKindOfClass:[UIControl class]]) {
[self matchSubviewsIn:subview];
}
}
}
// check if the view is matched to any event
- (void)matchView:(UIView *)view delegate:(id)delegate {
if (0 == eventBindings.count) {
return;
}
fb_dispatch_on_main_thread(^{
if (![view window]) {
return;
}
NSArray *path = [FBSDKViewHierarchy getPath:view];
fb_dispatch_on_default_thread(^{
if ([view isKindOfClass:[UIControl class]]) {
UIControl *control = (UIControl *)view;
for (FBSDKEventBinding *binding in self->eventBindings) {
if ([FBSDKEventBinding isPath:binding.path matchViewPath:path]) {
fb_dispatch_on_main_thread(^{
[control addTarget:binding
action:@selector(trackEvent:)
forControlEvents:UIControlEventTouchUpInside];
});
break;
}
}
} else if (self->hasReactNative
&& [view respondsToSelector:@selector(reactTag)]) {
for (FBSDKEventBinding *binding in self->eventBindings) {
if ([FBSDKEventBinding isPath:binding.path matchViewPath:path]) {
fb_dispatch_on_main_thread(^{
if (view) {
NSNumber *reactTag = [FBSDKViewHierarchy getViewReactTag:view];
if (reactTag != nil) {
self->reactBindings[reactTag] = binding;
}
}
});
break;
}
}
} else if ([view isKindOfClass:[UITableView class]]
&& [delegate conformsToProtocol:@protocol(UITableViewDelegate)]) {
fb_dispatch_on_default_thread(^{
NSMutableSet *matchedBindings = [NSMutableSet set];
for (FBSDKEventBinding *binding in self->eventBindings) {
if (binding.path.count > 1) {
NSArray *shortPath = [binding.path
subarrayWithRange:NSMakeRange(0, binding.path.count - 1)];
if ([FBSDKEventBinding isPath:shortPath matchViewPath:path]) {
[matchedBindings addObject:binding];
}
}
}
if (matchedBindings.count > 0) {
NSArray *bindings = matchedBindings.allObjects;
void (^block)(id, SEL, id, id) = ^(id target, SEL command, UITableView *tableView, NSIndexPath *indexPath) {
fb_dispatch_on_main_thread(^{
for (FBSDKEventBinding *binding in bindings) {
FBSDKCodelessPathComponent *component = binding.path.lastObject;
if ((component.section == -1 || component.section == indexPath.section)
&& (component.row == -1 || component.row == indexPath.row)) {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[binding trackEvent:cell];
}
}
});
};
[FBSDKSwizzler swizzleSelector:@selector(tableView:didSelectRowAtIndexPath:)
onClass:[delegate class]
withBlock:block
named:@"handle_table_view"];
}
});
} else if ([view isKindOfClass:[UICollectionView class]]
&& [delegate conformsToProtocol:@protocol(UICollectionViewDelegate)]) {
fb_dispatch_on_default_thread(^{
NSMutableSet *matchedBindings = [NSMutableSet set];
for (FBSDKEventBinding *binding in self->eventBindings) {
if (binding.path.count > 1) {
NSArray *shortPath = [binding.path
subarrayWithRange:NSMakeRange(0, binding.path.count - 1)];
if ([FBSDKEventBinding isPath:shortPath matchViewPath:path]) {
[matchedBindings addObject:binding];
}
}
}
if (matchedBindings.count > 0) {
NSArray *bindings = matchedBindings.allObjects;
void (^block)(id, SEL, id, id) = ^(id target, SEL command, UICollectionView *collectionView, NSIndexPath *indexPath) {
fb_dispatch_on_main_thread(^{
for (FBSDKEventBinding *binding in bindings) {
FBSDKCodelessPathComponent *component = binding.path.lastObject;
if ((component.section == -1 || component.section == indexPath.section)
&& (component.row == -1 || component.row == indexPath.row)) {
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
[binding trackEvent:cell];
}
}
});
};
[FBSDKSwizzler swizzleSelector:@selector(collectionView:didSelectItemAtIndexPath:)
onClass:[delegate class]
withBlock:block
named:@"handle_collection_view"];
}
});
}
});
});
}
#pragma clang diagnostic pop
- (void)updateBindings:(NSArray *)bindings {
eventBindings = bindings;
[reactBindings removeAllObjects];
if (!isStarted) {
[self start];
}
fb_dispatch_on_main_thread(^{
[self rematchBindings];
});
}
@end
#endif

View file

@ -1,34 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface FBSDKEventDeactivationManager : NSObject
+ (void)enable;
+ (void)updateDeactivatedEvents:(nullable NSDictionary<NSString *, id> *)events;
+ (void)processEvents:(NSMutableArray<NSDictionary<NSString *, id> *> *)events;
+ (nullable NSDictionary<NSString *, id> *)processParameters:(nullable NSDictionary<NSString *, id> *)parameters
eventName:(NSString *)eventName;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,119 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "FBSDKEventDeactivationManager.h"
static NSString *const DEPRECATED_PARAM_KEY = @"deprecated_param";
static NSString *const DEPRECATED_EVENT_KEY = @"is_deprecated_event";
@interface FBSDKDeactivatedEvent : NSObject
@property (nonatomic, readonly, copy) NSString *eventName;
@property (nonatomic, readonly, copy, nullable) NSSet<NSString *> *deactivatedParams;
-(instancetype)initWithEventName:(NSString *)eventName
deactivatedParams:(NSSet<NSString *> *)deactivatedParams;
@end
@implementation FBSDKDeactivatedEvent
-(instancetype)initWithEventName:(NSString *)eventName
deactivatedParams:(NSSet<NSString *> *)deactivatedParams
{
self = [super init];
if (self) {
_eventName = eventName;
_deactivatedParams = deactivatedParams;
}
return self;
}
@end
@implementation FBSDKEventDeactivationManager
static BOOL isEventDeactivationEnabled = NO;
static NSMutableSet<NSString *> *_deactivatedEvents;
static NSMutableArray<FBSDKDeactivatedEvent *> *_eventsWithDeactivatedParams;
+ (void)enable
{
isEventDeactivationEnabled = YES;
}
+ (void)updateDeactivatedEvents:(nullable NSDictionary<NSString *, id> *)events
{
if (!isEventDeactivationEnabled || events.count == 0) {
return;
}
[_deactivatedEvents removeAllObjects];
[_eventsWithDeactivatedParams removeAllObjects];
NSMutableArray<FBSDKDeactivatedEvent *> *deactivatedParamsArray = [NSMutableArray array];
NSMutableSet<NSString *> *deactivatedEventSet = [NSMutableSet set];
for (NSString *eventName in events.allKeys) {
NSDictionary<NSString *, id> *eventInfo = events[eventName];
if (!eventInfo) {
return;
}
if (eventInfo[DEPRECATED_EVENT_KEY]) {
[deactivatedEventSet addObject:eventName];
}
if (eventInfo[DEPRECATED_PARAM_KEY]) {
FBSDKDeactivatedEvent *eventWithDeactivatedParams = [[FBSDKDeactivatedEvent alloc] initWithEventName:eventName
deactivatedParams:[NSSet setWithArray:eventInfo[DEPRECATED_PARAM_KEY]]];
[deactivatedParamsArray addObject:eventWithDeactivatedParams];
}
}
_deactivatedEvents = deactivatedEventSet;
_eventsWithDeactivatedParams = deactivatedParamsArray;
}
+ (void)processEvents:(NSMutableArray<NSDictionary<NSString *, id> *> *)events
{
if (!isEventDeactivationEnabled) {
return;
}
NSArray<NSDictionary<NSString *, id> *> *eventArray = [events copy];
for (NSDictionary<NSString *, NSDictionary<NSString *, id> *> *event in eventArray) {
if ([_deactivatedEvents containsObject:event[@"event"][@"_eventName"]]) {
[events removeObject:event];
}
}
}
+ (nullable NSDictionary<NSString *, id> *)processParameters:(nullable NSDictionary<NSString *, id> *)parameters
eventName:(NSString *)eventName
{
if (!isEventDeactivationEnabled || parameters.count == 0 || _eventsWithDeactivatedParams.count == 0) {
return parameters;
}
NSMutableDictionary<NSString *, id> *params = [NSMutableDictionary dictionaryWithDictionary:parameters];
for (NSString *key in [parameters keyEnumerator]) {
for (FBSDKDeactivatedEvent *event in _eventsWithDeactivatedParams) {
if ([event.eventName isEqualToString:eventName] && [event.deactivatedParams containsObject:key]) {
[params removeObjectForKey:key];
}
}
}
return [params copy];
}
@end

View file

@ -1,245 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#if SWIFT_PACKAGE
#import "FBSDKAppEvents.h"
#else
#import <FBSDKCoreKit/FBSDKAppEvents.h>
#endif
#import "FBSDKAppEventsUtility.h"
@class FBSDKGraphRequest;
// Internally known event names
/** Use to log that the share dialog was launched */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameShareSheetLaunch;
/** Use to log that the share dialog was dismissed */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameShareSheetDismiss;
/** Use to log that the permissions UI was launched */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNamePermissionsUILaunch;
/** Use to log that the permissions UI was dismissed */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNamePermissionsUIDismiss;
/** Use to log that the login view was used */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameLoginViewUsage;
/** Use to log that the share tray launched. */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameShareTrayDidLaunch;
/** Use to log that the person selected a sharing target. */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameShareTrayDidSelectActivity;
// Internally known event parameters
/** String parameter specifying the outcome of a dialog invocation */
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterDialogOutcome;
/** Parameter key used to specify which application launches this application. */
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterLaunchSource;
/** Use to log the result of a call to FBDialogs presentShareDialogWithParams: */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsPresentShareDialog;
/** Use to log the result of a call to FBDialogs presentShareDialogWithOpenGraphActionParams: */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsPresentShareDialogOG;
/** Use to log the result of a call to FBDialogs presentLikeDialogWithLikeParams: */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsPresentLikeDialogOG;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsPresentShareDialogPhoto;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsPresentMessageDialog;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsPresentMessageDialogPhoto;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsPresentMessageDialogOG;
/** Use to log the start of an auth request that cannot be fulfilled by the token cache */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSessionAuthStart;
/** Use to log the end of an auth request that was not fulfilled by the token cache */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSessionAuthEnd;
/** Use to log the start of a specific auth method as part of an auth request */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSessionAuthMethodStart;
/** Use to log the end of the last tried auth method as part of an auth request */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSessionAuthMethodEnd;
/** Use to log the timestamp for the transition to the Facebook native login dialog */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsNativeLoginDialogStart;
/** Use to log the timestamp for the transition back to the app after the Facebook native login dialog */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsNativeLoginDialogEnd;
/** Use to log the e2e timestamp metrics for web login */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBDialogsWebLoginCompleted;
/** Use to log the result of the App Switch OS AlertView. Only available on OS >= iOS10 */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSessionFASLoginDialogResult;
/** Use to log the live streaming events from sdk */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingStart;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingStop;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingPause;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingResume;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingError;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingUpdateStatus;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingVideoID;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingMic;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingCamera;
/** Use to log the results of a share dialog */
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKEventShareDialogResult;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKEventMessengerShareDialogResult;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKEventAppInviteShareDialogResult;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKEventShareDialogShow;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKEventMessengerShareDialogShow;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKEventAppInviteShareDialogShow;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterDialogMode;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterDialogShareContentType;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterDialogShareContentUUID;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterDialogShareContentPageID;
/** Use to log parameters for share tray use */
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterShareTrayActivityName;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterShareTrayResult;
/** Use to log parameters for live streaming*/
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterLiveStreamingPrevStatus;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterLiveStreamingStatus;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterLiveStreamingError;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterLiveStreamingVideoID;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterLiveStreamingMicEnabled;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterLiveStreamingCameraEnabled;
// Internally known event parameter values
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogOutcomeValue_Completed;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogOutcomeValue_Cancelled;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogOutcomeValue_Failed;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareContentTypeOpenGraph;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareContentTypeStatus;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareContentTypePhoto;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareContentTypeVideo;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareContentTypeCamera;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareContentTypeMessengerGenericTemplate;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareContentTypeMessengerMediaTemplate;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareContentTypeMessengerOpenGraphMusicTemplate;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareContentTypeUnknown;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareModeAutomatic;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareModeBrowser;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareModeNative;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareModeShareSheet;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareModeWeb;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareModeFeedBrowser;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareModeFeedWeb;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsDialogShareModeUnknown;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsNativeLoginDialogStartTime;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsNativeLoginDialogEndTime;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWebLoginE2E;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeButtonImpression;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLoginButtonImpression;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKSendButtonImpression;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKShareButtonImpression;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingButtonImpression;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKSmartLoginService;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeButtonDidTap;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLoginButtonDidTap;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKSendButtonDidTap;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKShareButtonDidTap;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLiveStreamingButtonDidTap;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeControlDidDisable;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeControlDidLike;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeControlDidPresentDialog;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeControlDidTap;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeControlDidUnlike;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeControlError;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeControlImpression;
FOUNDATION_EXPORT NSString *const FBSDKAppEventNameFBSDKLikeControlNetworkUnavailable;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterDialogErrorMessage;
FOUNDATION_EXPORT NSString *const FBSDKAppEventParameterLogTime;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWKWebViewMessagesHandlerKey;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWKWebViewMessagesActionKey;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWKWebViewMessagesEventKey;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWKWebViewMessagesParamsKey;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWKWebViewMessagesPixelTrackKey;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWKWebViewMessagesPixelTrackCustomKey;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWKWebViewMessagesPixelTrackSingleKey;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWKWebViewMessagesPixelTrackSingleCustomKey;
FOUNDATION_EXPORT NSString *const FBSDKAppEventsWKWebViewMessagesPixelIDKey;
@interface FBSDKAppEvents (Internal)
@property (class, nonatomic, strong, readonly) FBSDKAppEvents *singleton;
#ifdef DEBUG
+ (void)resetSingleton;
#endif
+ (void)logInternalEvent:(FBSDKAppEventName)eventName
isImplicitlyLogged:(BOOL)isImplicitlyLogged;
+ (void)logInternalEvent:(FBSDKAppEventName)eventName
valueToSum:(double)valueToSum
isImplicitlyLogged:(BOOL)isImplicitlyLogged;
+ (void)logInternalEvent:(FBSDKAppEventName)eventName
parameters:(NSDictionary *)parameters
isImplicitlyLogged:(BOOL)isImplicitlyLogged;
+ (void)logInternalEvent:(FBSDKAppEventName)eventName
parameters:(NSDictionary *)parameters
isImplicitlyLogged:(BOOL)isImplicitlyLogged
accessToken:(FBSDKAccessToken *)accessToken;
+ (void)logInternalEvent:(FBSDKAppEventName)eventName
valueToSum:(double)valueToSum
parameters:(NSDictionary *)parameters
isImplicitlyLogged:(BOOL)isImplicitlyLogged;
+ (void)logInternalEvent:(NSString *)eventName
valueToSum:(NSNumber *)valueToSum
parameters:(NSDictionary *)parameters
isImplicitlyLogged:(BOOL)isImplicitlyLogged
accessToken:(FBSDKAccessToken *)accessToken;
+ (void)logImplicitEvent:(NSString *)eventName
valueToSum:(NSNumber *)valueToSum
parameters:(NSDictionary *)parameters
accessToken:(FBSDKAccessToken *)accessToken;
- (void)flushForReason:(FBSDKAppEventsFlushReason)flushReason;
- (void)registerNotifications;
@end

View file

@ -1,26 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
NS_SWIFT_NAME(AppEventsDeviceInfo)
@interface FBSDKAppEventsDeviceInfo : NSObject
+ (void)extendDictionaryWithDeviceInfo:(NSMutableDictionary *)dictionary;
@end

View file

@ -1,279 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "FBSDKAppEventsDeviceInfo.h"
#import <sys/sysctl.h>
#import <sys/utsname.h>
#if !TARGET_OS_TV
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#endif
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "FBSDKAppEvents+Internal.h"
#import "FBSDKDynamicFrameworkLoader.h"
#import "FBSDKInternalUtility.h"
#import "FBSDKUtility.h"
#define FB_ARRAY_COUNT(x) sizeof(x) / sizeof(x[0])
static const u_int FB_GROUP1_RECHECK_DURATION = 30 * 60; // seconds
// Apple reports storage in binary gigabytes (1024^3) in their About menus, etc.
static const u_int FB_GIGABYTE = 1024 * 1024 * 1024; // bytes
@implementation FBSDKAppEventsDeviceInfo
{
// Ephemeral data, may change during the lifetime of an app. We collect them in different
// 'group' frequencies - group1 may gets collected once every 30 minutes.
// group1
NSString *_carrierName;
NSString *_timeZoneAbbrev;
unsigned long long _remainingDiskSpaceGB;
NSString *_timeZoneName;
// Persistent data, but we maintain it to make rebuilding the device info as fast as possible.
NSString *_bundleIdentifier;
NSString *_longVersion;
NSString *_shortVersion;
NSString *_sysVersion;
NSString *_machine;
NSString *_language;
unsigned long long _totalDiskSpaceGB;
unsigned long long _coreCount;
CGFloat _width;
CGFloat _height;
CGFloat _density;
// Other state
long _lastGroup1CheckTime;
BOOL _isEncodingDirty;
NSString *_encodedDeviceInfo;
}
#pragma mark - Public Methods
+ (void)extendDictionaryWithDeviceInfo:(NSMutableDictionary *)dictionary
{
dictionary[@"extinfo"] = [[self sharedDeviceInfo] encodedDeviceInfo];
}
#pragma mark - Internal Methods
+ (void)initialize
{
if (self == [FBSDKAppEventsDeviceInfo class]) {
[[self sharedDeviceInfo] _collectPersistentData];
}
}
+ (instancetype)sharedDeviceInfo
{
static FBSDKAppEventsDeviceInfo *_sharedDeviceInfo = nil;
if (_sharedDeviceInfo == nil) {
_sharedDeviceInfo = [[FBSDKAppEventsDeviceInfo alloc] init];
}
return _sharedDeviceInfo;
}
- (instancetype)init
{
if ((self = [super init])) {
_isEncodingDirty = YES;
}
return self;
}
- (NSString *)encodedDeviceInfo
{
@synchronized (self) {
BOOL isGroup1Expired = [self _isGroup1Expired];
BOOL isEncodingExpired = isGroup1Expired; // Can || other groups in if we add them
// As long as group1 hasn't expired, we can just return the last generated value
if (_encodedDeviceInfo && !isEncodingExpired) {
return _encodedDeviceInfo;
}
if (isGroup1Expired) {
[self _collectGroup1Data];
}
if (_isEncodingDirty) {
self.encodedDeviceInfo = [self _generateEncoding];
_isEncodingDirty = NO;
}
return _encodedDeviceInfo;
}
}
- (void)setEncodedDeviceInfo:(NSString *)encodedDeviceInfo
{
@synchronized (self) {
if (![_encodedDeviceInfo isEqualToString:encodedDeviceInfo]) {
_encodedDeviceInfo = [encodedDeviceInfo copy];
}
}
}
// This data need only be collected once.
- (void)_collectPersistentData
{
// Bundle stuff
NSBundle *mainBundle = [NSBundle mainBundle];
_bundleIdentifier = mainBundle.bundleIdentifier;
_longVersion = [mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"];
_shortVersion = [mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
// Locale stuff
_language = [NSLocale currentLocale].localeIdentifier;
// Device stuff
UIDevice *device = [UIDevice currentDevice];
_sysVersion = device.systemVersion;
_coreCount = [FBSDKAppEventsDeviceInfo _coreCount];
UIScreen *sc = [UIScreen mainScreen];
CGRect sr = sc.bounds;
_width = sr.size.width;
_height = sr.size.height;
_density = sc.scale;
struct utsname systemInfo;
uname(&systemInfo);
_machine = @(systemInfo.machine);
// Disk space stuff
float totalDiskSpace = [FBSDKAppEventsDeviceInfo _getTotalDiskSpace].floatValue;
_totalDiskSpaceGB = (unsigned long long)round(totalDiskSpace / FB_GIGABYTE);
}
- (BOOL)_isGroup1Expired
{
return ([FBSDKAppEventsUtility unixTimeNow] - _lastGroup1CheckTime) > FB_GROUP1_RECHECK_DURATION;
}
// This data is collected only once every GROUP1_RECHECK_DURATION.
- (void)_collectGroup1Data
{
// Carrier
NSString *newCarrierName = [FBSDKAppEventsDeviceInfo _getCarrier];
if (![newCarrierName isEqualToString:_carrierName]) {
_carrierName = newCarrierName;
_isEncodingDirty = YES;
}
// Time zone
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
NSString *timeZoneName = timeZone.name;
if (![timeZoneName isEqualToString:_timeZoneName]) {
_timeZoneName = timeZoneName;
_timeZoneAbbrev = timeZone.abbreviation;
_isEncodingDirty = YES;
}
// Remaining disk space
float remainingDiskSpace = [FBSDKAppEventsDeviceInfo _getRemainingDiskSpace].floatValue;
unsigned long long newRemainingDiskSpaceGB = (unsigned long long)round(remainingDiskSpace / FB_GIGABYTE);
if (_remainingDiskSpaceGB != newRemainingDiskSpaceGB) {
_remainingDiskSpaceGB = newRemainingDiskSpaceGB;
_isEncodingDirty = YES;
}
_lastGroup1CheckTime = [FBSDKAppEventsUtility unixTimeNow];
}
- (NSString *)_generateEncoding
{
// Keep a bit of precision on density as it's the most likely to become non-integer.
NSString *densityString = _density ? [NSString stringWithFormat:@"%.02f", _density] : @"";
NSArray *arr = @[
@"i2", // version - starts with 'i' for iOS, we'll use 'a' for Android
_bundleIdentifier ?: @"",
_longVersion ?: @"",
_shortVersion ?: @"",
_sysVersion ?: @"",
_machine ?: @"",
_language ?: @"",
_timeZoneAbbrev ?: @"",
_carrierName ?: @"",
_width ? @((unsigned long)_width) : @"",
_height ? @((unsigned long)_height) : @"",
densityString,
@(_coreCount) ?: @"",
@(_totalDiskSpaceGB) ?: @"",
@(_remainingDiskSpaceGB) ?: @"",
_timeZoneName ?: @""
];
return [FBSDKBasicUtility JSONStringForObject:arr error:NULL invalidObjectHandler:NULL];
}
#pragma mark - Helper Methods
+ (NSNumber *)_getTotalDiskSpace
{
NSDictionary *attrs = [[[NSFileManager alloc] init] attributesOfFileSystemForPath:NSHomeDirectory()
error:nil];
return attrs[NSFileSystemSize];
}
+ (NSNumber *)_getRemainingDiskSpace
{
NSDictionary *attrs = [[[NSFileManager alloc] init] attributesOfFileSystemForPath:NSHomeDirectory()
error:nil];
return attrs[NSFileSystemFreeSize];
}
+ (uint)_coreCount
{
return [FBSDKAppEventsDeviceInfo _readSysCtlUInt:CTL_HW type:HW_AVAILCPU];
}
+ (uint)_readSysCtlUInt:(int)ctl type:(int)type
{
int mib[2] = {ctl, type};
uint value;
size_t size = sizeof value;
if (0 != sysctl(mib, FB_ARRAY_COUNT(mib), &value, &size, NULL, 0)) {
return 0;
}
return value;
}
+ (NSString *)_getCarrier
{
#if TARGET_OS_TV || TARGET_IPHONE_SIMULATOR
return @"NoCarrier";
#else
// Dynamically load class for this so calling app doesn't need to link framework in.
CTTelephonyNetworkInfo *networkInfo = [[fbsdkdfl_CTTelephonyNetworkInfoClass() alloc] init];
CTCarrier *carrier = networkInfo.subscriberCellularProvider;
return carrier.carrierName ?: @"NoCarrier";
#endif
}
@end

View file

@ -1,42 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
// this type is not thread safe.
NS_SWIFT_NAME(AppEventsState)
@interface FBSDKAppEventsState : NSObject<NSCopying, NSSecureCoding>
@property (nonatomic, readonly, copy) NSArray *events;
@property (nonatomic, readonly, assign) NSUInteger numSkipped;
@property (nonatomic, readonly, copy) NSString *tokenString;
@property (nonatomic, readonly, copy) NSString *appID;
@property (nonatomic, readonly, getter=areAllEventsImplicit) BOOL allEventsImplicit;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithToken:(NSString *)tokenString appID:(NSString *)appID NS_DESIGNATED_INITIALIZER;
- (void)addEvent:(NSDictionary *)eventDictionary isImplicit:(BOOL)isImplicit;
- (void)addEventsFromAppEventState:(FBSDKAppEventsState *)appEventsState;
- (BOOL)isCompatibleWithAppEventsState:(FBSDKAppEventsState *)appEventsState;
- (BOOL)isCompatibleWithTokenString:(NSString *)tokenString appID:(NSString *)appID;
- (NSString *)JSONStringForEvents:(BOOL)includeImplicitEvents;
- (NSString *)extractReceiptData;
@end

View file

@ -1,185 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "FBSDKAppEventsState.h"
#import "FBSDKBasicUtility.h"
#import "FBSDKEventDeactivationManager.h"
#import "FBSDKRestrictiveDataFilterManager.h"
#define FBSDK_APPEVENTSTATE_ISIMPLICIT_KEY @"isImplicit"
#define FBSDK_APPEVENTSSTATE_MAX_EVENTS 1000
#define FBSDK_APPEVENTSSTATE_APPID_KEY @"appID"
#define FBSDK_APPEVENTSSTATE_EVENTS_KEY @"events"
#define FBSDK_APPEVENTSSTATE_NUMSKIPPED_KEY @"numSkipped"
#define FBSDK_APPEVENTSSTATE_TOKENSTRING_KEY @"tokenString"
#define FBSDK_APPEVENTSTATE_RECEIPTDATA_KEY @"receipt_data"
#define FBSDK_APPEVENTSTATE_RECEIPTID_KEY @"receipt_id"
@implementation FBSDKAppEventsState
{
NSMutableArray *_mutableEvents;
}
- (instancetype)initWithToken:(NSString *)tokenString appID:(NSString *)appID
{
if ((self = [super init])) {
_tokenString = [tokenString copy];
_appID = [appID copy];
_mutableEvents = [NSMutableArray array];
}
return self;
}
- (instancetype)copyWithZone:(NSZone *)zone
{
FBSDKAppEventsState *copy = [[FBSDKAppEventsState allocWithZone:zone] initWithToken:_tokenString appID:_appID];
if (copy) {
[copy->_mutableEvents addObjectsFromArray:_mutableEvents];
copy->_numSkipped = _numSkipped;
}
return copy;
}
#pragma mark - NSCoding
+ (BOOL)supportsSecureCoding
{
return YES;
}
- (id)initWithCoder:(NSCoder *)decoder
{
NSString *appID = [decoder decodeObjectOfClass:[NSString class] forKey:FBSDK_APPEVENTSSTATE_APPID_KEY];
NSString *tokenString = [decoder decodeObjectOfClass:[NSString class] forKey:FBSDK_APPEVENTSSTATE_TOKENSTRING_KEY];
NSArray *events = [decoder decodeObjectOfClass:[NSArray class] forKey:FBSDK_APPEVENTSSTATE_EVENTS_KEY];
NSUInteger numSkipped = [[decoder decodeObjectOfClass:[NSNumber class] forKey:FBSDK_APPEVENTSSTATE_NUMSKIPPED_KEY] unsignedIntegerValue];
if ((self = [self initWithToken:tokenString appID:appID])) {
_mutableEvents = [NSMutableArray arrayWithArray:events];
_numSkipped = numSkipped;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:_appID forKey:FBSDK_APPEVENTSSTATE_APPID_KEY];
[encoder encodeObject:_tokenString forKey:FBSDK_APPEVENTSSTATE_TOKENSTRING_KEY];
[encoder encodeObject:@(_numSkipped) forKey:FBSDK_APPEVENTSSTATE_NUMSKIPPED_KEY];
[encoder encodeObject:_mutableEvents forKey:FBSDK_APPEVENTSSTATE_EVENTS_KEY];
}
#pragma mark - Implementation
- (NSArray *)events
{
return [_mutableEvents copy];
}
- (void)addEventsFromAppEventState:(FBSDKAppEventsState *)appEventsState
{
NSArray *toAdd = appEventsState->_mutableEvents;
NSInteger excess = _mutableEvents.count + toAdd.count - FBSDK_APPEVENTSSTATE_MAX_EVENTS;
if (excess > 0) {
NSInteger range = FBSDK_APPEVENTSSTATE_MAX_EVENTS - _mutableEvents.count;
toAdd = [toAdd subarrayWithRange:NSMakeRange(0, range)];
_numSkipped += excess;
}
[_mutableEvents addObjectsFromArray:toAdd];
}
- (void)addEvent:(NSDictionary *)eventDictionary
isImplicit:(BOOL)isImplicit {
if (_mutableEvents.count >= FBSDK_APPEVENTSSTATE_MAX_EVENTS) {
_numSkipped++;
} else {
[_mutableEvents addObject:@{
@"event" : [eventDictionary mutableCopy],
FBSDK_APPEVENTSTATE_ISIMPLICIT_KEY : @(isImplicit)
}];
}
}
- (NSString *)extractReceiptData {
NSMutableString *receipts_string = [NSMutableString string];
NSInteger transactionId = 1;
for (NSMutableDictionary* events in _mutableEvents) {
NSMutableDictionary *event = events[@"event"];
NSString* receipt = event[@"receipt_data"];
// Add receipt id as the identifier for receipt data in event parameter.
// Receipt data will be sent as post parameter rather than the event parameter
if (receipt) {
NSString* idKey = [NSString stringWithFormat:@"receipt_%ld", (long)transactionId];
event[FBSDK_APPEVENTSTATE_RECEIPTID_KEY] = idKey;
NSString* receiptWithId = [NSString stringWithFormat:@"%@::%@;;;", idKey, receipt];
[receipts_string appendString:receiptWithId];
transactionId++;
}
}
return receipts_string;
}
- (BOOL)areAllEventsImplicit
{
for (NSDictionary *event in _mutableEvents) {
if (![[event valueForKey:FBSDK_APPEVENTSTATE_ISIMPLICIT_KEY] boolValue]) {
return NO;
}
}
return YES;
}
- (BOOL)isCompatibleWithAppEventsState:(FBSDKAppEventsState *)appEventsState
{
return ([self isCompatibleWithTokenString:appEventsState.tokenString appID:appEventsState.appID]);
}
- (BOOL)isCompatibleWithTokenString:(NSString *)tokenString appID:(NSString *)appID
{
// token strings can be nil (e.g., no user token) but appIDs should not.
BOOL tokenCompatible = ([self.tokenString isEqualToString:tokenString] ||
(self.tokenString == nil && tokenString == nil));
return (tokenCompatible &&
[self.appID isEqualToString:appID]);
}
- (NSString *)JSONStringForEvents:(BOOL)includeImplicitEvents
{
[FBSDKEventDeactivationManager processEvents:_mutableEvents];
NSMutableArray *events = [[NSMutableArray alloc] initWithCapacity:_mutableEvents.count];
for (NSDictionary *eventAndImplicitFlag in _mutableEvents) {
if (!includeImplicitEvents && [eventAndImplicitFlag[FBSDK_APPEVENTSTATE_ISIMPLICIT_KEY] boolValue]) {
continue;
}
NSMutableDictionary *event = eventAndImplicitFlag[@"event"];
NSAssert(event != nil, @"event cannot be nil");
[event removeObjectForKey:FBSDK_APPEVENTSTATE_RECEIPTDATA_KEY];
[events addObject:event];
}
return [FBSDKBasicUtility JSONStringForObject:events error:NULL invalidObjectHandler:NULL];
}
@end

View file

@ -1,35 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
@class FBSDKAppEventsState;
NS_SWIFT_NAME(AppEventsStateManager)
@interface FBSDKAppEventsStateManager : NSObject
+ (void)clearPersistedAppEventsStates;
// reads all saved event states, appends the param, and writes them all.
+ (void)persistAppEventsData:(FBSDKAppEventsState *)appEventsState;
// returns the array of saved app event states and deletes them.
+ (NSArray *)retrievePersistedAppEventsStates;
@end

View file

@ -1,79 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "FBSDKAppEventsStateManager.h"
#import <Foundation/Foundation.h>
#import "FBSDKAppEventsState.h"
#import "FBSDKAppEventsUtility.h"
#import "FBSDKInternalUtility.h"
#import "FBSDKLogger.h"
#import "FBSDKSettings.h"
// A quick optimization to allow returning empty array if we know there are no persisted events.
static BOOL g_canSkipDiskCheck = NO;
@implementation FBSDKAppEventsStateManager
+ (void)clearPersistedAppEventsStates
{
[FBSDKLogger singleShotLogEntry:FBSDKLoggingBehaviorAppEvents
logEntry:@"FBSDKAppEvents Persist: Clearing"];
[[NSFileManager defaultManager] removeItemAtPath:[[self class] filePath]
error:NULL];
g_canSkipDiskCheck = YES;
}
+ (void)persistAppEventsData:(FBSDKAppEventsState *)appEventsState
{
[FBSDKLogger singleShotLogEntry:FBSDKLoggingBehaviorAppEvents
formatString:@"FBSDKAppEvents Persist: Writing %lu events", (unsigned long)appEventsState.events.count];
if (!appEventsState.events.count) {
return;
}
NSMutableArray *existingEvents = [NSMutableArray arrayWithArray:[[self class] retrievePersistedAppEventsStates]];
[existingEvents addObject:appEventsState];
[NSKeyedArchiver archiveRootObject:existingEvents toFile:[[self class] filePath]];
g_canSkipDiskCheck = NO;
}
+ (NSArray *)retrievePersistedAppEventsStates
{
NSMutableArray *eventsStates = [NSMutableArray array];
if (!g_canSkipDiskCheck) {
[eventsStates addObjectsFromArray:[NSKeyedUnarchiver unarchiveObjectWithFile:[[self class] filePath]]];
[FBSDKLogger singleShotLogEntry:FBSDKLoggingBehaviorAppEvents
formatString:@"FBSDKAppEvents Persist: Read %lu event states. First state has %lu events",
(unsigned long)eventsStates.count,
(unsigned long)(eventsStates.count > 0 ? ((FBSDKAppEventsState *)eventsStates[0]).events.count : 0)];
[[self class] clearPersistedAppEventsStates];
}
return eventsStates;
}
#pragma mark - Private Helpers
+ (NSString *)filePath
{
return [FBSDKBasicUtility persistenceFilePath:@"com-facebook-sdk-AppEventsPersistedEvents.json"];
}
@end

View file

@ -1,66 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
@class FBSDKAccessToken;
typedef NS_ENUM(NSUInteger, FBSDKAdvertisingTrackingStatus)
{
FBSDKAdvertisingTrackingAllowed,
FBSDKAdvertisingTrackingDisallowed,
FBSDKAdvertisingTrackingUnspecified
} NS_SWIFT_NAME(AppEventsUtility.AdvertisingTrackingStatus);
typedef NS_ENUM(NSUInteger, FBSDKAppEventsFlushReason)
{
FBSDKAppEventsFlushReasonExplicit,
FBSDKAppEventsFlushReasonTimer,
FBSDKAppEventsFlushReasonSessionChange,
FBSDKAppEventsFlushReasonPersistedEvents,
FBSDKAppEventsFlushReasonEventThreshold,
FBSDKAppEventsFlushReasonEagerlyFlushingEvent
} NS_SWIFT_NAME(AppEventsUtility.FlushReason);
NS_SWIFT_NAME(AppEventsUtility)
@interface FBSDKAppEventsUtility : NSObject
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
@property (class, nonatomic, copy, readonly) NSString *advertiserID;
@property (class, nonatomic, assign, readonly) FBSDKAdvertisingTrackingStatus advertisingTrackingStatus;
@property (class, nonatomic, strong, readonly) NSString *attributionID;
@property (class, nonatomic, assign, readonly) long unixTimeNow;
@property (class, nonatomic, assign, readonly) BOOL isDebugBuild;
+ (NSMutableDictionary *)activityParametersDictionaryForEvent:(NSString *)eventCategory
implicitEventsOnly:(BOOL)implicitEventsOnly
shouldAccessAdvertisingID:(BOOL)shouldAccessAdvertisingID;
+ (void)ensureOnMainThread:(NSString *)methodName className:(NSString *)className;
+ (NSString *)flushReasonToString:(FBSDKAppEventsFlushReason)flushReason;
+ (void)logAndNotify:(NSString *)msg allowLogAsDeveloperError:(BOOL)allowLogAsDeveloperError;
+ (void)logAndNotify:(NSString *)msg;
+ (NSString *)tokenStringToUseFor:(FBSDKAccessToken *)token;
+ (BOOL)validateIdentifier:(NSString *)identifier;
+ (id)getVariable:(NSString *)variableName fromInstance:(NSObject *)instance;
+ (NSNumber *)getNumberValue:(NSString *)text;
+ (BOOL)isSensitiveUserData:(NSString *)text;
@end

View file

@ -1,430 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "FBSDKAppEventsUtility.h"
#import <objc/runtime.h>
#import <AdSupport/AdSupport.h>
#import "FBSDKAccessToken.h"
#import "FBSDKAppEvents.h"
#import "FBSDKAppEventsDeviceInfo.h"
#import "FBSDKConstants.h"
#import "FBSDKDynamicFrameworkLoader.h"
#import "FBSDKError.h"
#import "FBSDKInternalUtility.h"
#import "FBSDKLogger.h"
#import "FBSDKSettings.h"
#import "FBSDKTimeSpentData.h"
#define FBSDK_APPEVENTSUTILITY_ANONYMOUSIDFILENAME @"com-facebook-sdk-PersistedAnonymousID.json"
#define FBSDK_APPEVENTSUTILITY_ANONYMOUSID_KEY @"anon_id"
#define FBSDK_APPEVENTSUTILITY_MAX_IDENTIFIER_LENGTH 40
@implementation FBSDKAppEventsUtility
+ (NSMutableDictionary *)activityParametersDictionaryForEvent:(NSString *)eventCategory
implicitEventsOnly:(BOOL)implicitEventsOnly
shouldAccessAdvertisingID:(BOOL)shouldAccessAdvertisingID {
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
parameters[@"event"] = eventCategory;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
NSString *attributionID = [[self class] attributionID]; // Only present on iOS 6 and below.
[FBSDKBasicUtility dictionary:parameters setObject:attributionID forKey:@"attribution"];
#endif
if (!implicitEventsOnly && shouldAccessAdvertisingID) {
NSString *advertiserID = [[self class] advertiserID];
[FBSDKBasicUtility dictionary:parameters setObject:advertiserID forKey:@"advertiser_id"];
}
parameters[FBSDK_APPEVENTSUTILITY_ANONYMOUSID_KEY] = [FBSDKBasicUtility anonymousID];
FBSDKAdvertisingTrackingStatus advertisingTrackingStatus = [[self class] advertisingTrackingStatus];
if (advertisingTrackingStatus != FBSDKAdvertisingTrackingUnspecified) {
BOOL allowed = (advertisingTrackingStatus == FBSDKAdvertisingTrackingAllowed);
parameters[@"advertiser_tracking_enabled"] = @(allowed).stringValue;
}
if (advertisingTrackingStatus == FBSDKAdvertisingTrackingAllowed) {
NSString *userData = [FBSDKAppEvents getUserData];
if (userData){
parameters[@"ud"] = userData;
}
}
parameters[@"application_tracking_enabled"] = @(!FBSDKSettings.limitEventAndDataUsage).stringValue;
NSString *userID = [FBSDKAppEvents userID];
if (userID) {
parameters[@"app_user_id"] = userID;
}
[FBSDKAppEventsDeviceInfo extendDictionaryWithDeviceInfo:parameters];
static dispatch_once_t fetchBundleOnce;
static NSMutableArray *urlSchemes;
dispatch_once(&fetchBundleOnce, ^{
NSBundle *mainBundle = [NSBundle mainBundle];
urlSchemes = [[NSMutableArray alloc] init];
for (NSDictionary<NSString *, id> *fields in [mainBundle objectForInfoDictionaryKey:@"CFBundleURLTypes"]) {
NSArray<NSString *> *schemesForType = fields[@"CFBundleURLSchemes"];
if (schemesForType) {
[urlSchemes addObjectsFromArray:schemesForType];
}
}
});
if (urlSchemes.count > 0) {
parameters[@"url_schemes"] = [FBSDKBasicUtility JSONStringForObject:urlSchemes error:NULL invalidObjectHandler:NULL];
}
return parameters;
}
+ (NSString *)advertiserID
{
if (!FBSDKSettings.isAdvertiserIDCollectionEnabled) {
return nil;
}
NSString *result = nil;
Class ASIdentifierManagerClass = fbsdkdfl_ASIdentifierManagerClass();
if ([ASIdentifierManagerClass class]) {
ASIdentifierManager *manager = [ASIdentifierManagerClass sharedManager];
result = manager.advertisingIdentifier.UUIDString;
}
return result;
}
+ (FBSDKAdvertisingTrackingStatus)advertisingTrackingStatus
{
static dispatch_once_t fetchAdvertisingTrackingStatusOnce;
static FBSDKAdvertisingTrackingStatus status;
dispatch_once(&fetchAdvertisingTrackingStatusOnce, ^{
status = FBSDKAdvertisingTrackingUnspecified;
Class ASIdentifierManagerClass = fbsdkdfl_ASIdentifierManagerClass();
if ([ASIdentifierManagerClass class]) {
ASIdentifierManager *manager = [ASIdentifierManagerClass sharedManager];
if (manager) {
status = manager.advertisingTrackingEnabled ? FBSDKAdvertisingTrackingAllowed : FBSDKAdvertisingTrackingDisallowed;
}
}
});
return status;
}
+ (NSString *)attributionID
{
#if TARGET_OS_TV
return nil;
#else
return [UIPasteboard pasteboardWithName:@"fb_app_attribution" create:NO].string;
#endif
}
#pragma mark - Internal, for testing
+ (void)clearLibraryFiles
{
[[NSFileManager defaultManager] removeItemAtPath:[[self class] persistenceFilePath:FBSDK_APPEVENTSUTILITY_ANONYMOUSIDFILENAME]
error:NULL];
[[NSFileManager defaultManager] removeItemAtPath:[[self class] persistenceFilePath:FBSDKTimeSpentFilename]
error:NULL];
}
+ (void)ensureOnMainThread:(NSString *)methodName className:(NSString *)className
{
FBSDKConditionalLog([NSThread isMainThread],
FBSDKLoggingBehaviorDeveloperErrors,
@"*** <%@, %@> is not called on the main thread. This can lead to errors.",
methodName,
className);
}
+ (NSString *)flushReasonToString:(FBSDKAppEventsFlushReason)flushReason
{
NSString *result = @"Unknown";
switch (flushReason) {
case FBSDKAppEventsFlushReasonExplicit:
result = @"Explicit";
break;
case FBSDKAppEventsFlushReasonTimer:
result = @"Timer";
break;
case FBSDKAppEventsFlushReasonSessionChange:
result = @"SessionChange";
break;
case FBSDKAppEventsFlushReasonPersistedEvents:
result = @"PersistedEvents";
break;
case FBSDKAppEventsFlushReasonEventThreshold:
result = @"EventCountThreshold";
break;
case FBSDKAppEventsFlushReasonEagerlyFlushingEvent:
result = @"EagerlyFlushingEvent";
break;
}
return result;
}
+ (void)logAndNotify:(NSString *)msg
{
[[self class] logAndNotify:msg allowLogAsDeveloperError:YES];
}
+ (void)logAndNotify:(NSString *)msg allowLogAsDeveloperError:(BOOL)allowLogAsDeveloperError
{
NSString *behaviorToLog = FBSDKLoggingBehaviorAppEvents;
if (allowLogAsDeveloperError) {
if ([FBSDKSettings.loggingBehaviors containsObject:FBSDKLoggingBehaviorDeveloperErrors]) {
// Rather than log twice, prefer 'DeveloperErrors' if it's set over AppEvents.
behaviorToLog = FBSDKLoggingBehaviorDeveloperErrors;
}
}
[FBSDKLogger singleShotLogEntry:behaviorToLog logEntry:msg];
NSError *error = [FBSDKError errorWithCode:FBSDKErrorAppEventsFlush message:msg];
[[NSNotificationCenter defaultCenter] postNotificationName:FBSDKAppEventsLoggingResultNotification object:error];
}
+ (BOOL)matchString:(NSString *)string
firstCharacterSet:(NSCharacterSet *)firstCharacterSet
restOfStringCharacterSet:(NSCharacterSet *)restOfStringCharacterSet
{
if (string.length == 0) {
return NO;
}
for (NSUInteger i = 0; i < string.length; i++) {
const unichar c = [string characterAtIndex:i];
if (i == 0) {
if (![firstCharacterSet characterIsMember:c]) {
return NO;
}
} else {
if (![restOfStringCharacterSet characterIsMember:c]) {
return NO;
}
}
}
return YES;
}
+ (BOOL)regexValidateIdentifier:(NSString *)identifier
{
static NSCharacterSet *firstCharacterSet;
static NSCharacterSet *restOfStringCharacterSet;
static dispatch_once_t onceToken;
static NSMutableSet *cachedIdentifiers;
dispatch_once(&onceToken, ^{
NSMutableCharacterSet *mutableSet = [NSMutableCharacterSet alphanumericCharacterSet];
[mutableSet addCharactersInString:@"_"];
firstCharacterSet = [mutableSet copy];
[mutableSet addCharactersInString:@"- "];
restOfStringCharacterSet = [mutableSet copy];
cachedIdentifiers = [[NSMutableSet alloc] init];
});
@synchronized(self) {
if (![cachedIdentifiers containsObject:identifier]) {
if ([self matchString:identifier
firstCharacterSet:firstCharacterSet
restOfStringCharacterSet:restOfStringCharacterSet]) {
[cachedIdentifiers addObject:identifier];
} else {
return NO;
}
}
}
return YES;
}
+ (BOOL)validateIdentifier:(NSString *)identifier
{
if (identifier == nil || identifier.length == 0 || identifier.length > FBSDK_APPEVENTSUTILITY_MAX_IDENTIFIER_LENGTH || ![[self class] regexValidateIdentifier:identifier]) {
[[self class] logAndNotify:[NSString stringWithFormat:@"Invalid identifier: '%@'. Must be between 1 and %d characters, and must be contain only alphanumerics, _, - or spaces, starting with alphanumeric or _.",
identifier, FBSDK_APPEVENTSUTILITY_MAX_IDENTIFIER_LENGTH]];
return NO;
}
return YES;
}
// Given a candidate token (which may be nil), find the real token to string to use.
// Precedence: 1) provided token, 2) current token, 3) app | client token, 4) fully anonymous session.
+ (NSString *)tokenStringToUseFor:(FBSDKAccessToken *)token
{
if (!token) {
token = [FBSDKAccessToken currentAccessToken];
}
NSString *appID = [FBSDKAppEvents loggingOverrideAppID] ?: token.appID ?: [FBSDKSettings appID];
NSString *tokenString = token.tokenString;
if (!tokenString || ![appID isEqualToString:token.appID]) {
// If there's an logging override app id present, then we don't want to use the client token since the client token
// is intended to match up with the primary app id (and AppEvents doesn't require a client token).
NSString *clientTokenString = [FBSDKSettings clientToken];
if (clientTokenString && appID && [appID isEqualToString:token.appID]){
tokenString = [NSString stringWithFormat:@"%@|%@", appID, clientTokenString];
} else if (appID) {
tokenString = nil;
}
}
return tokenString;
}
+ (long)unixTimeNow
{
return (long)round([NSDate date].timeIntervalSince1970);
}
+ (id)getVariable:(NSString *)variableName fromInstance:(NSObject *)instance {
Ivar ivar = class_getInstanceVariable([instance class], variableName.UTF8String);
if (ivar != NULL) {
const char *encoding = ivar_getTypeEncoding(ivar);
if (encoding != NULL && encoding[0] == '@') {
return object_getIvar(instance, ivar);
}
}
return nil;
}
+ (NSNumber *)getNumberValue:(NSString *)text {
NSNumber *value = @0;
NSLocale *locale = [NSLocale currentLocale];
NSString *ds = [locale objectForKey:NSLocaleDecimalSeparator] ?: @".";
NSString *gs = [locale objectForKey:NSLocaleGroupingSeparator] ?: @",";
NSString *separators = [ds stringByAppendingString:gs];
NSString *regex = [NSString stringWithFormat:@"[+-]?([0-9]+[%1$@]?)?[%1$@]?([0-9]+[%1$@]?)+", separators];
NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:regex
options:0
error:nil];
NSTextCheckingResult *match = [re firstMatchInString:text
options:0
range:NSMakeRange(0, text.length)];
if (match) {
NSString *validText = [text substringWithRange:match.range];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.locale = locale;
formatter.numberStyle = NSNumberFormatterDecimalStyle;
value = [formatter numberFromString:validText];
if (nil == value) {
value = @(validText.floatValue);
}
}
return value;
}
+ (BOOL)isDebugBuild {
#if TARGET_IPHONE_SIMULATOR
return YES;
#else
BOOL isDevelopment = NO;
// There is no provisioning profile in AppStore Apps.
@try
{
NSData *data = [NSData dataWithContentsOfFile:[NSBundle.mainBundle pathForResource:@"embedded" ofType:@"mobileprovision"]];
if (data) {
const char *bytes = [data bytes];
NSMutableString *profile = [[NSMutableString alloc] initWithCapacity:data.length];
for (NSUInteger i = 0; i < data.length; i++) {
[profile appendFormat:@"%c", bytes[i]];
}
// Look for debug value, if detected we're in a development build.
NSString *cleared = [[profile componentsSeparatedByCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet] componentsJoinedByString:@""];
isDevelopment = ([cleared rangeOfString:@"<key>get-task-allow</key><true/>"].length > 0);
}
return isDevelopment;
}
@catch(NSException *exception)
{
}
return NO;
#endif
}
+ (BOOL)isSensitiveUserData:(NSString *)text
{
if (0 == text.length) {
return NO;
}
return [self isEmailAddress:text] || [self isCreditCardNumber:text];
}
+ (BOOL)isCreditCardNumber:(NSString *)text
{
text = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet.decimalDigitCharacterSet invertedSet]] componentsJoinedByString:@""];
if (text.doubleValue == 0) {
return NO;
}
if (text.length < 9 || text.length > 21) {
return NO;
}
const char *chars = [text cStringUsingEncoding:NSUTF8StringEncoding];
if (NULL == chars) {
return NO;
}
BOOL isOdd = YES;
int oddSum = 0;
int evenSum = 0;
for (int i = (int)text.length - 1; i >= 0; i--) {
int digit = chars[i] - '0';
if (isOdd)
oddSum += digit;
else
evenSum += digit / 5 + (2 * digit) % 10;
isOdd = !isOdd;
}
return ((oddSum + evenSum) % 10 == 0);
}
+ (BOOL)isEmailAddress:(NSString *)text
{
NSString *pattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger matches = [regex numberOfMatchesInString:text options:0 range:NSMakeRange(0, [text length])];
return matches > 0;
}
@end

View file

@ -1,31 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
NS_SWIFT_NAME(HybridAppEventsScriptMessageHandler)
@interface FBSDKHybridAppEventsScriptMessageHandler : NSObject <WKScriptMessageHandler>
@end
#endif

View file

@ -1,74 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKHybridAppEventsScriptMessageHandler.h"
#if SWIFT_PACKAGE
#import "FBSDKAppEvents.h"
#else
#import <FBSDKCoreKit/FBSDKAppEvents.h>
#endif
#import "FBSDKAppEvents+Internal.h"
NSString *const FBSDKAppEventsWKWebViewMessagesPixelReferralParamKey = @"_fb_pixel_referral_id";
@class WKUserContentController;
@implementation FBSDKHybridAppEventsScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:FBSDKAppEventsWKWebViewMessagesHandlerKey]) {
NSString *event = message.body[FBSDKAppEventsWKWebViewMessagesEventKey];
if (event.length > 0) {
NSString *stringedParams = message.body[FBSDKAppEventsWKWebViewMessagesParamsKey];
NSMutableDictionary <NSString *, id> *params = nil;
NSError *jsonParseError = nil;
if ([stringedParams isKindOfClass:[NSString class]]) {
params = [NSJSONSerialization JSONObjectWithData:[stringedParams dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&jsonParseError
];
}
NSString *pixelID = message.body[FBSDKAppEventsWKWebViewMessagesPixelIDKey];
if (pixelID == nil) {
[FBSDKAppEventsUtility logAndNotify:@"Can't bridge an event without a referral Pixel ID. Check your webview Pixel configuration."];
return;
}
if (jsonParseError != nil || ![params isKindOfClass:[NSDictionary class]] || params == nil) {
[FBSDKAppEventsUtility logAndNotify:@"Could not find parameters for your Pixel request. Check your webview Pixel configuration."];
params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:pixelID, FBSDKAppEventsWKWebViewMessagesPixelReferralParamKey, nil];
}
else {
params[FBSDKAppEventsWKWebViewMessagesPixelReferralParamKey] = pixelID;
}
[FBSDKAppEvents logInternalEvent:event
parameters:params
isImplicitlyLogged:NO];
}
}
}
@end
#endif

View file

@ -1,26 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
// Class to encapsulate implicit logging of purchase events
NS_SWIFT_NAME(PaymentObserver)
@interface FBSDKPaymentObserver : NSObject
+ (void)startObservingTransactions;
+ (void)stopObservingTransactions;
@end

View file

@ -1,547 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "FBSDKPaymentObserver.h"
#import <StoreKit/StoreKit.h>
#import "FBSDKCoreKit+Internal.h"
#import "FBSDKAppEvents+Internal.h"
#import "FBSDKDynamicFrameworkLoader.h"
#import "FBSDKLogger.h"
#import "FBSDKSettings.h"
static NSString *const FBSDKPaymentObserverOriginalTransactionKey = @"com.facebook.appevents.PaymentObserver.originalTransaction";
static NSString *const FBSDKPaymentObserverDelimiter = @",";
static NSString *const FBSDKAppEventParameterImplicitlyLoggedPurchase = @"_implicitlyLogged";
static NSString *const FBSDKAppEventNamePurchaseFailed = @"fb_mobile_purchase_failed";
static NSString *const FBSDKAppEventNamePurchaseRestored = @"fb_mobile_purchase_restored";
static NSString *const FBSDKAppEventParameterNameInAppPurchaseType = @"fb_iap_product_type";
static NSString *const FBSDKAppEventParameterNameProductTitle = @"fb_content_title";
static NSString *const FBSDKAppEventParameterNameOriginalTransactionID = @"fb_original_transaction_id";
static NSString *const FBSDKAppEventParameterNameTransactionID = @"fb_transaction_id";
static NSString *const FBSDKAppEventParameterNameTransactionDate = @"fb_transaction_date";
static NSString *const FBSDKAppEventParameterNameSubscriptionPeriod = @"fb_iap_subs_period";
static NSString *const FBSDKAppEventParameterNameIsStartTrial = @"fb_iap_is_start_trial";
static NSString *const FBSDKAppEventParameterNameHasFreeTrial = @"fb_iap_has_free_trial";
static NSString *const FBSDKAppEventParameterNameTrialPeriod = @"fb_iap_trial_period";
static NSString *const FBSDKAppEventParameterNameTrialPrice = @"fb_iap_trial_price";
static int const FBSDKMaxParameterValueLength = 100;
static NSMutableArray *g_pendingRequestors;
static NSString *const FBSDKGateKeeperAppEventsIfAutoLogSubs = @"app_events_if_auto_log_subs";
@interface FBSDKPaymentProductRequestor : NSObject<SKProductsRequestDelegate>
@property (nonatomic, retain) SKPaymentTransaction *transaction;
- (instancetype)initWithTransaction:(SKPaymentTransaction*)transaction;
- (void)resolveProducts;
@end
@interface FBSDKPaymentObserver() <SKPaymentTransactionObserver>
@end
@implementation FBSDKPaymentObserver
{
BOOL _observingTransactions;
}
+ (void)startObservingTransactions
{
[[self singleton] startObservingTransactions];
}
+ (void)stopObservingTransactions
{
[[self singleton] stopObservingTransactions];
}
#pragma mark - Internal Methods
+ (FBSDKPaymentObserver *)singleton
{
static dispatch_once_t pred;
static FBSDKPaymentObserver *shared = nil;
dispatch_once(&pred, ^{
shared = [[FBSDKPaymentObserver alloc] init];
});
return shared;
}
- (instancetype) init
{
self = [super init];
if (self) {
_observingTransactions = NO;
}
return self;
}
- (void)startObservingTransactions
{
@synchronized (self) {
if (!_observingTransactions) {
[(SKPaymentQueue *)[fbsdkdfl_SKPaymentQueueClass() defaultQueue] addTransactionObserver:self];
_observingTransactions = YES;
}
}
}
- (void)stopObservingTransactions
{
@synchronized (self) {
if (_observingTransactions) {
[(SKPaymentQueue *)[fbsdkdfl_SKPaymentQueueClass() defaultQueue] removeTransactionObserver:self];
_observingTransactions = NO;
}
}
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing:
case SKPaymentTransactionStatePurchased:
case SKPaymentTransactionStateFailed:
case SKPaymentTransactionStateRestored:
[self handleTransaction:transaction];
break;
case SKPaymentTransactionStateDeferred:
break;
}
}
}
- (void)handleTransaction:(SKPaymentTransaction *)transaction
{
FBSDKPaymentProductRequestor *productRequest = [[FBSDKPaymentProductRequestor alloc] initWithTransaction:transaction];
[productRequest resolveProducts];
}
@end
@interface FBSDKPaymentProductRequestor()
@property (nonatomic, retain) SKProductsRequest *productRequest;
@end
@implementation FBSDKPaymentProductRequestor
{
NSMutableSet<NSString *> *_originalTransactionSet;
NSSet<NSString *> *_eventsWithReceipt;
NSDateFormatter *_formatter;
}
+ (void)initialize
{
if ([self class] == [FBSDKPaymentProductRequestor class]) {
g_pendingRequestors = [[NSMutableArray alloc] init];
}
}
- (instancetype)initWithTransaction:(SKPaymentTransaction*)transaction
{
self = [super init];
if (self) {
_transaction = transaction;
_formatter = [[NSDateFormatter alloc] init];
_formatter.dateFormat = @"yyyy-MM-dd HH:mm:ssZ";
NSString *data = [[NSUserDefaults standardUserDefaults] stringForKey:FBSDKPaymentObserverOriginalTransactionKey];
_eventsWithReceipt = [NSSet setWithArray:@[FBSDKAppEventNamePurchased, FBSDKAppEventNameSubscribe,
FBSDKAppEventNameStartTrial]];
if (data) {
_originalTransactionSet = [NSMutableSet setWithArray:[data componentsSeparatedByString:FBSDKPaymentObserverDelimiter]];
} else {
_originalTransactionSet = [[NSMutableSet alloc] init];
}
}
return self;
}
- (void)setProductRequest:(SKProductsRequest *)productRequest
{
if (productRequest != _productRequest) {
if (_productRequest) {
_productRequest.delegate = nil;
}
_productRequest = productRequest;
}
}
- (void)resolveProducts
{
NSString *productId = self.transaction.payment.productIdentifier;
NSSet *productIdentifiers = [NSSet setWithObjects:productId, nil];
self.productRequest = [[fbsdkdfl_SKProductsRequestClass() alloc] initWithProductIdentifiers:productIdentifiers];
self.productRequest.delegate = self;
@synchronized(g_pendingRequestors) {
[g_pendingRequestors addObject:self];
}
[self.productRequest start];
}
- (NSString *)getTruncatedString:(NSString *)inputString
{
if (!inputString) {
return @"";
}
return inputString.length <= FBSDKMaxParameterValueLength ? inputString : [inputString substringToIndex:FBSDKMaxParameterValueLength];
}
- (void)logTransactionEvent:(SKProduct *)product
{
if ([self isSubscription:product] &&
[FBSDKGateKeeperManager boolForKey:FBSDKGateKeeperAppEventsIfAutoLogSubs
defaultValue:NO]) {
[self logImplicitSubscribeTransaction:self.transaction ofProduct:product];
} else {
[self logImplicitPurchaseTransaction:self.transaction ofProduct:product];
}
}
- (BOOL)isSubscription:(SKProduct *)product
{
#if !TARGET_OS_TV
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_11_1
if (@available(iOS 11.2, *)) {
return (product.subscriptionPeriod != nil) && ((unsigned long)product.subscriptionPeriod.numberOfUnits > 0);
}
#endif
#endif
return NO;
}
- (NSMutableDictionary<NSString *, id> *)getEventParametersOfProduct:(SKProduct *)product
withTransaction:(SKPaymentTransaction *)transaction
{
NSString *transactionID = nil;
NSString *transactionDate = nil;
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing:
break;
case SKPaymentTransactionStatePurchased:
transactionID = self.transaction.transactionIdentifier;
transactionDate = [_formatter stringFromDate:self.transaction.transactionDate];
break;
case SKPaymentTransactionStateFailed:
break;
case SKPaymentTransactionStateRestored:
transactionDate = [_formatter stringFromDate:self.transaction.transactionDate];
break;
default: break;
}
SKPayment *payment = transaction.payment;
NSMutableDictionary *eventParameters = [NSMutableDictionary dictionaryWithDictionary: @{
FBSDKAppEventParameterNameContentID: payment.productIdentifier ?: @"",
FBSDKAppEventParameterNameNumItems: @(payment.quantity),
FBSDKAppEventParameterNameTransactionDate: transactionDate ?: @"",
}];
if (product) {
[eventParameters addEntriesFromDictionary: @{
FBSDKAppEventParameterNameCurrency: [product.priceLocale objectForKey:NSLocaleCurrencyCode],
FBSDKAppEventParameterNameNumItems: @(payment.quantity),
FBSDKAppEventParameterNameProductTitle: [self getTruncatedString:product.localizedTitle],
FBSDKAppEventParameterNameDescription: [self getTruncatedString:product.localizedDescription],
}];
if (transactionID) {
eventParameters[FBSDKAppEventParameterNameTransactionID] = transactionID;
}
}
#if !TARGET_OS_TV
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_11_1
if (@available(iOS 11.2, *)) {
if ([self isSubscription:product]) {
// subs inapp
eventParameters[FBSDKAppEventParameterNameSubscriptionPeriod] = [self durationOfSubscriptionPeriod:product.subscriptionPeriod];
eventParameters[FBSDKAppEventParameterNameInAppPurchaseType] = @"subs";
eventParameters[FBSDKAppEventParameterNameIsStartTrial] = [self isStartTrial:transaction ofProduct:product] ? @"1" : @"0";
// trial information for subs
SKProductDiscount *discount = product.introductoryPrice;
if (discount) {
if (discount.paymentMode == SKProductDiscountPaymentModeFreeTrial) {
eventParameters[FBSDKAppEventParameterNameHasFreeTrial] = @"1";
} else {
eventParameters[FBSDKAppEventParameterNameHasFreeTrial] = @"0";
}
eventParameters[FBSDKAppEventParameterNameTrialPeriod] = [self durationOfSubscriptionPeriod:discount.subscriptionPeriod];
eventParameters[FBSDKAppEventParameterNameTrialPrice] = discount.price;
}
} else {
eventParameters[FBSDKAppEventParameterNameInAppPurchaseType] = @"inapp";
}
}
#endif
#endif
return eventParameters;
}
- (void)appendOriginalTransactionID:(NSString *)transactionID
{
if (!transactionID) {
return;
}
[_originalTransactionSet addObject:transactionID];
[[NSUserDefaults standardUserDefaults] setObject:[[_originalTransactionSet allObjects] componentsJoinedByString:FBSDKPaymentObserverDelimiter]
forKey:FBSDKPaymentObserverOriginalTransactionKey];
}
- (void)clearOriginalTransactionID:(NSString *)transactionID
{
if (!transactionID) {
return;
}
[_originalTransactionSet removeObject:transactionID];
[[NSUserDefaults standardUserDefaults] setObject:[[_originalTransactionSet allObjects] componentsJoinedByString:FBSDKPaymentObserverDelimiter]
forKey:FBSDKPaymentObserverOriginalTransactionKey];
}
- (BOOL)isStartTrial:(SKPaymentTransaction *)transaction
ofProduct:(SKProduct *)product
{
#if !TARGET_OS_TV
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_11_1
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_11_4
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_12_1
// promotional offer starting from iOS 12.2
if (@available(iOS 12.2, *)) {
SKPaymentDiscount *paymentDiscount = transaction.payment.paymentDiscount;
if (paymentDiscount) {
NSArray<SKProductDiscount *> *discounts = product.discounts;
for (SKProductDiscount *discount in discounts) {
if (discount.paymentMode == SKProductDiscountPaymentModeFreeTrial &&
[paymentDiscount.identifier isEqualToString:discount.identifier]) {
return YES;
}
}
}
}
#endif
#endif
// introductory offer starting from iOS 11.2
if (@available(iOS 11.2, *)) {
if (product.introductoryPrice &&
product.introductoryPrice.paymentMode == SKProductDiscountPaymentModeFreeTrial) {
NSString *originalTransactionID = transaction.originalTransaction.transactionIdentifier;
// only consider the very first trial transaction as start trial
if (!originalTransactionID) {
return YES;
}
}
}
#endif
#endif
return NO;
}
- (BOOL)hasStartTrial:(SKProduct *)product
{
#if !TARGET_OS_TV
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_11_1
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_11_4
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_12_1
// promotional offer starting from iOS 12.2
if (@available(iOS 12.2, *)) {
NSArray<SKProductDiscount *> *discounts = product.discounts;
for (SKProductDiscount *discount in discounts) {
if (discount.paymentMode == SKProductDiscountPaymentModeFreeTrial) {
return YES;
}
}
}
#endif
#endif
// introductory offer starting from iOS 11.2
if (@available(iOS 11.2, *)) {
if (product.introductoryPrice && (product.introductoryPrice.paymentMode == SKProductDiscountPaymentModeFreeTrial)) {
return YES;
}
}
#endif
#endif
return NO;
}
- (NSString *)durationOfSubscriptionPeriod:(id)subcriptionPeriod
{
#if !TARGET_OS_TV
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_11_1
if (@available(iOS 11.2, *)) {
if (subcriptionPeriod && [subcriptionPeriod isKindOfClass:[SKProductSubscriptionPeriod class]]) {
SKProductSubscriptionPeriod *period = (SKProductSubscriptionPeriod *)subcriptionPeriod;
NSString *unit = nil;
switch (period.unit) {
case SKProductPeriodUnitDay: unit = @"D"; break;
case SKProductPeriodUnitWeek: unit = @"W"; break;
case SKProductPeriodUnitMonth: unit = @"M"; break;
case SKProductPeriodUnitYear: unit = @"Y"; break;
}
return [NSString stringWithFormat:@"P%lu%@", (unsigned long)period.numberOfUnits, unit];
}
}
#endif
#endif
return nil;
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
NSArray* products = response.products;
NSArray* invalidProductIdentifiers = response.invalidProductIdentifiers;
if (products.count + invalidProductIdentifiers.count != 1) {
[FBSDKLogger singleShotLogEntry:FBSDKLoggingBehaviorAppEvents
formatString:@"FBSDKPaymentObserver: Expect to resolve one product per request"];
}
SKProduct *product = nil;
if (products.count) {
product = products[0];
}
[self logTransactionEvent:product];
}
- (void)requestDidFinish:(SKRequest *)request
{
[self cleanUp];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
[self logTransactionEvent:nil];
[self cleanUp];
}
- (void)cleanUp
{
@synchronized(g_pendingRequestors) {
[g_pendingRequestors removeObject:self];
}
}
- (void)logImplicitSubscribeTransaction:(SKPaymentTransaction *)transaction
ofProduct:(SKProduct *)product
{
NSString *eventName = nil;
NSString *originalTransactionID = transaction.originalTransaction.transactionIdentifier;
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing:
eventName = @"SubscriptionInitiatedCheckout";
break;
case SKPaymentTransactionStatePurchased:
if ([self isStartTrial:transaction ofProduct:product]) {
eventName = FBSDKAppEventNameStartTrial;
[self clearOriginalTransactionID:originalTransactionID];
} else {
if (originalTransactionID && [_originalTransactionSet containsObject:originalTransactionID]) {
return;
}
eventName = FBSDKAppEventNameSubscribe;
[self appendOriginalTransactionID:(originalTransactionID ?: transaction.transactionIdentifier)];
}
break;
case SKPaymentTransactionStateFailed:
eventName = @"SubscriptionFailed";
break;
case SKPaymentTransactionStateRestored:
eventName = @"SubscriptionRestore";
break;
case SKPaymentTransactionStateDeferred:
return;
}
double totalAmount = 0;
if (product) {
totalAmount = transaction.payment.quantity * product.price.doubleValue;
}
[self logImplicitTransactionEvent:eventName
valueToSum:totalAmount
parameters:[self getEventParametersOfProduct:product withTransaction:transaction]];
}
- (void)logImplicitPurchaseTransaction:(SKPaymentTransaction *)transaction
ofProduct:(SKProduct *)product
{
NSString *eventName = nil;
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing:
eventName = FBSDKAppEventNameInitiatedCheckout;
break;
case SKPaymentTransactionStatePurchased:
eventName = FBSDKAppEventNamePurchased;
break;
case SKPaymentTransactionStateFailed:
eventName = FBSDKAppEventNamePurchaseFailed;
break;
case SKPaymentTransactionStateRestored:
eventName = FBSDKAppEventNamePurchaseRestored;
break;
case SKPaymentTransactionStateDeferred:
return;
}
double totalAmount = 0;
if (product) {
totalAmount = transaction.payment.quantity * product.price.doubleValue;
}
[self logImplicitTransactionEvent:eventName
valueToSum:totalAmount
parameters:[self getEventParametersOfProduct:product withTransaction:transaction]];
}
- (void)logImplicitTransactionEvent:(NSString *)eventName
valueToSum:(double)valueToSum
parameters:(NSDictionary<NSString *, id> *)parameters
{
NSMutableDictionary *eventParameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
if ([_eventsWithReceipt containsObject:eventName]) {
NSData* receipt = [self fetchDeviceReceipt];
if (receipt) {
NSString *base64encodedReceipt = [receipt base64EncodedStringWithOptions:0];
eventParameters[@"receipt_data"] = base64encodedReceipt;
}
}
eventParameters[FBSDKAppEventParameterImplicitlyLoggedPurchase] = @"1";
[FBSDKAppEvents logEvent:eventName
valueToSum:valueToSum
parameters:eventParameters];
// Unless the behavior is set to only allow explicit flushing, we go ahead and flush, since purchase events
// are relatively rare and relatively high value and worth getting across on wire right away.
if ([FBSDKAppEvents flushBehavior] != FBSDKAppEventsFlushBehaviorExplicitOnly) {
[[FBSDKAppEvents singleton] flushForReason:FBSDKAppEventsFlushReasonEagerlyFlushingEvent];
}
}
// Fetch the current receipt for this application.
- (NSData*)fetchDeviceReceipt
{
NSURL *receiptURL = [NSBundle bundleForClass:[self class]].appStoreReceiptURL;
NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];
return receipt;
}
@end

View file

@ -1,35 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
FOUNDATION_EXPORT NSString *const FBSDKTimeSpentFilename;
// Class to encapsulate persisting of time spent data collected by [FBSDKAppEvents activateApp]. The activate app App Event is
// logged when restore: is called with sufficient time since the last deactivation.
NS_SWIFT_NAME(TimeSpentData)
@interface FBSDKTimeSpentData : NSObject
+ (void)suspend;
+ (void)restore:(BOOL)calledFromActivateApp;
+ (void)setSourceApplication:(NSString *)sourceApplication openURL:(NSURL *)url;
+ (void)setSourceApplication:(NSString *)sourceApplication isFromAppLink:(BOOL)isFromAppLink;
+ (void)registerAutoResetSourceApplication;
@end

View file

@ -1,319 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "FBSDKTimeSpentData.h"
#import "FBSDKAppEvents+Internal.h"
#import "FBSDKAppEventsUtility.h"
#import "FBSDKInternalUtility.h"
#import "FBSDKLogger.h"
#import "FBSDKServerConfiguration.h"
#import "FBSDKServerConfigurationManager.h"
#import "FBSDKSettings.h"
// Filename and keys for session length
NSString *const FBSDKTimeSpentFilename = @"com-facebook-sdk-AppEventsTimeSpent.json";
static NSString *const FBSDKTimeSpentPersistKeySessionSecondsSpent = @"secondsSpentInCurrentSession";
static NSString *const FBSDKTimeSpentPersistKeySessionNumInterruptions = @"numInterruptions";
static NSString *const FBSDKTimeSpentPersistKeyLastSuspendTime = @"lastSuspendTime";
static NSString *const FBSDKTimeSpentPersistKeySessionID = @"sessionID";
static NSString *const FBSDKAppEventNameActivatedApp = @"fb_mobile_activate_app";
static NSString *const FBSDKAppEventNameDeactivatedApp = @"fb_mobile_deactivate_app";
static NSString *const FBSDKAppEventParameterNameSessionInterruptions = @"fb_mobile_app_interruptions";
static NSString *const FBSDKAppEventParameterNameTimeBetweenSessions = @"fb_mobile_time_between_sessions";
static NSString *const FBSDKAppEventParameterNameSessionID = @"_session_id";
static const int SECS_PER_MIN = 60;
static const int SECS_PER_HOUR = 60 * SECS_PER_MIN;
static const int SECS_PER_DAY = 24 * SECS_PER_HOUR;
static NSString *g_sourceApplication;
static BOOL g_isOpenedFromAppLink;
// Will be translated and displayed in App Insights. Need to maintain same number and value of quanta on the server.
static const long INACTIVE_SECONDS_QUANTA[] =
{
5 * SECS_PER_MIN,
15 * SECS_PER_MIN,
30 * SECS_PER_MIN,
1 * SECS_PER_HOUR,
6 * SECS_PER_HOUR,
12 * SECS_PER_HOUR,
1 * SECS_PER_DAY,
2 * SECS_PER_DAY,
3 * SECS_PER_DAY,
7 * SECS_PER_DAY,
14 * SECS_PER_DAY,
21 * SECS_PER_DAY,
28 * SECS_PER_DAY,
60 * SECS_PER_DAY,
90 * SECS_PER_DAY,
120 * SECS_PER_DAY,
150 * SECS_PER_DAY,
180 * SECS_PER_DAY,
365 * SECS_PER_DAY,
LONG_MAX, // keep as LONG_MAX to guarantee loop will terminate
};
/**
* This class encapsulates the notion of an app 'session' - the length of time that the user has
* spent in the app that can be considered a single usage of the app. Apps may be frequently interrupted
* do to other device activity, like a text message, so this class allows those interruptions to be smoothed
* out and the time actually spent in the app excluding this interruption time to be accumulated. Also,
* once a certain amount of time has gone by where the app is not in the foreground, we consider the
* session to be complete, and a new session beginning. When this occurs, we log a 'deactivate app' event
* with the duration of the previous session as the 'value' of this event, along with the number of
* interruptions from that previous session as an event parameter.
*/
@implementation FBSDKTimeSpentData
{
BOOL _isCurrentlyLoaded;
BOOL _shouldLogActivateEvent;
BOOL _shouldLogDeactivateEvent;
long _secondsSpentInCurrentSession;
long _timeSinceLastSuspend;
int _numInterruptionsInCurrentSession;
long _lastRestoreTime;
long _lastSuspendTime;
NSString *_sessionID;
}
//
// Public methods
//
+ (void)suspend
{
[self.singleton instanceSuspend];
}
+ (void)restore:(BOOL)calledFromActivateApp
{
[self.singleton instanceRestore:calledFromActivateApp];
}
//
// Internal methods
//
+ (FBSDKTimeSpentData *)singleton
{
static dispatch_once_t pred;
static FBSDKTimeSpentData *shared = nil;
dispatch_once(&pred, ^{
shared = [[FBSDKTimeSpentData alloc] init];
});
return shared;
}
// Calculate and persist time spent data for this instance of the app activation.
- (void)instanceSuspend
{
[FBSDKAppEventsUtility ensureOnMainThread:NSStringFromSelector(_cmd) className:NSStringFromClass([self class])];
if (!_isCurrentlyLoaded) {
FBSDKConditionalLog(YES, FBSDKLoggingBehaviorInformational, @"[FBSDKTimeSpentData suspend] invoked without corresponding restore");
return;
}
long now = [FBSDKAppEventsUtility unixTimeNow];
long timeSinceRestore = now - _lastRestoreTime;
// Can happen if the clock on the device is changed
if (timeSinceRestore < 0) {
[FBSDKLogger singleShotLogEntry:FBSDKLoggingBehaviorAppEvents
formatString:@"Clock skew detected"];
timeSinceRestore = 0;
}
_secondsSpentInCurrentSession += timeSinceRestore;
NSDictionary *timeSpentData =
@{
FBSDKTimeSpentPersistKeySessionSecondsSpent : @(_secondsSpentInCurrentSession),
FBSDKTimeSpentPersistKeySessionNumInterruptions : @(_numInterruptionsInCurrentSession),
FBSDKTimeSpentPersistKeyLastSuspendTime : @(now),
FBSDKTimeSpentPersistKeySessionID : _sessionID,
};
NSString *content = [FBSDKBasicUtility JSONStringForObject:timeSpentData error:NULL invalidObjectHandler:NULL];
[content writeToFile:[FBSDKBasicUtility persistenceFilePath:FBSDKTimeSpentFilename]
atomically:YES
encoding:NSASCIIStringEncoding
error:nil];
[FBSDKLogger singleShotLogEntry:FBSDKLoggingBehaviorAppEvents
formatString:@"FBSDKTimeSpentData Persist: %@", content];
_isCurrentlyLoaded = NO;
}
// Called during activation - either through an explicit 'activateApp' call or implicitly when the app is foregrounded.
// In both cases, we restore the persisted event data. In the case of the activateApp, we log an 'app activated'
// event if there's been enough time between the last deactivation and now.
- (void)instanceRestore:(BOOL)calledFromActivateApp
{
[FBSDKAppEventsUtility ensureOnMainThread:NSStringFromSelector(_cmd) className:NSStringFromClass([self class])];
// It's possible to call this multiple times during the time the app is in the foreground. If this is the case,
// just restore persisted data the first time.
if (!_isCurrentlyLoaded) {
NSString *content =
[[NSString alloc] initWithContentsOfFile:[FBSDKBasicUtility persistenceFilePath:FBSDKTimeSpentFilename]
usedEncoding:nil
error:nil];
[FBSDKLogger singleShotLogEntry:FBSDKLoggingBehaviorAppEvents
formatString:@"FBSDKTimeSpentData Restore: %@", content];
long now = [FBSDKAppEventsUtility unixTimeNow];
if (!content) {
// Nothing persisted, so this is the first launch.
_sessionID = [NSUUID UUID].UUIDString;
_secondsSpentInCurrentSession = 0;
_numInterruptionsInCurrentSession = 0;
_lastSuspendTime = 0;
// We want to log the app activation event on the first launch, but not the deactivate event
_shouldLogActivateEvent = YES;
_shouldLogDeactivateEvent = NO;
} else {
NSDictionary<id, id> *results = [FBSDKBasicUtility objectForJSONString:content error:NULL];
_lastSuspendTime = [results[FBSDKTimeSpentPersistKeyLastSuspendTime] longValue];
_timeSinceLastSuspend = now - _lastSuspendTime;
_secondsSpentInCurrentSession = [results[FBSDKTimeSpentPersistKeySessionSecondsSpent] intValue];
_sessionID = results[FBSDKTimeSpentPersistKeySessionID] ? : [NSUUID UUID].UUIDString;
_numInterruptionsInCurrentSession = [results[FBSDKTimeSpentPersistKeySessionNumInterruptions] intValue];
_shouldLogActivateEvent = (_timeSinceLastSuspend > [FBSDKServerConfigurationManager cachedServerConfiguration].sessionTimoutInterval);
// Other than the first launch, we always log the last session's deactivate with this session's activate.
_shouldLogDeactivateEvent = _shouldLogActivateEvent;
if (!_shouldLogDeactivateEvent) {
// If we're not logging, then the time we spent deactivated is considered another interruption. But cap it
// so errant or test uses doesn't blow out the cardinality on the backend processing
_numInterruptionsInCurrentSession = MIN(_numInterruptionsInCurrentSession + 1, 200);
}
}
_lastRestoreTime = now;
_isCurrentlyLoaded = YES;
if (calledFromActivateApp) {
// It's important to log deactivate first to reset sessionID
if (_shouldLogDeactivateEvent) {
[FBSDKAppEvents logEvent:FBSDKAppEventNameDeactivatedApp
valueToSum:_secondsSpentInCurrentSession
parameters:[self appEventsParametersForDeactivate]];
// We've logged the session stats, now reset.
_secondsSpentInCurrentSession = 0;
_numInterruptionsInCurrentSession = 0;
_sessionID = [NSUUID UUID].UUIDString;
}
if (_shouldLogActivateEvent) {
[FBSDKAppEvents logEvent:FBSDKAppEventNameActivatedApp
parameters:[self appEventsParametersForActivate]];
// Unless the behavior is set to only allow explicit flushing, we go ahead and flush. App launch
// events are critical to Analytics so we don't want to lose them.
if ([FBSDKAppEvents flushBehavior] != FBSDKAppEventsFlushBehaviorExplicitOnly) {
[[FBSDKAppEvents singleton] flushForReason:FBSDKAppEventsFlushReasonEagerlyFlushingEvent];
}
}
}
}
}
- (NSDictionary *)appEventsParametersForActivate
{
return @{
FBSDKAppEventParameterLaunchSource: [[self class] getSourceApplication],
FBSDKAppEventParameterNameSessionID: _sessionID,
};
}
- (NSDictionary *)appEventsParametersForDeactivate
{
int quantaIndex = 0;
while (_timeSinceLastSuspend > INACTIVE_SECONDS_QUANTA[quantaIndex]) {
quantaIndex++;
}
NSMutableDictionary *params = [@{ FBSDKAppEventParameterNameSessionInterruptions : @(_numInterruptionsInCurrentSession),
FBSDKAppEventParameterNameTimeBetweenSessions : [NSString stringWithFormat:@"session_quanta_%d", quantaIndex],
FBSDKAppEventParameterLaunchSource: [[self class] getSourceApplication],
FBSDKAppEventParameterNameSessionID : _sessionID ?: @"",
} mutableCopy];
if (_lastSuspendTime) {
params[FBSDKAppEventParameterLogTime] = @(_lastSuspendTime);
}
return [params copy];
}
+ (void)setSourceApplication:(NSString *)sourceApplication openURL:(NSURL *)url
{
[self setSourceApplication:sourceApplication
isFromAppLink:[FBSDKInternalUtility dictionaryFromFBURL:url][@"al_applink_data"] != nil];
}
+ (void)setSourceApplication:(NSString *)sourceApplication isFromAppLink:(BOOL)isFromAppLink
{
g_isOpenedFromAppLink = isFromAppLink;
g_sourceApplication = sourceApplication;
}
+ (NSString *)getSourceApplication
{
NSString *openType = @"Unclassified";
if (g_isOpenedFromAppLink) {
openType = @"AppLink";
}
return (g_sourceApplication ?
[NSString stringWithFormat:@"%@(%@)", openType, g_sourceApplication]
: openType);
}
+ (void)resetSourceApplication
{
g_sourceApplication = nil;
g_isOpenedFromAppLink = NO;
}
+ (void)registerAutoResetSourceApplication
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(resetSourceApplication)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
}
@end

View file

@ -1,48 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "FBSDKAppEvents+Internal.h"
NS_ASSUME_NONNULL_BEGIN
NS_SWIFT_NAME(UserDataStore)
@interface FBSDKUserDataStore : NSObject
+ (void)setAndHashUserEmail:(nullable NSString *)email
firstName:(nullable NSString *)firstName
lastName:(nullable NSString *)lastName
phone:(nullable NSString *)phone
dateOfBirth:(nullable NSString *)dateOfBirth
gender:(nullable NSString *)gender
city:(nullable NSString *)city
state:(nullable NSString *)state
zip:(nullable NSString *)zip
country:(nullable NSString *)country;
+ (void)setAndHashData:(nullable NSString *)data
forType:(FBSDKAppEventUserDataType)type;
+ (void)setHashData:(nullable NSString *)hashData
forType:(FBSDKAppEventUserDataType)type;
+ (nullable NSString *)getHashedData;
+ (nullable NSString *)getHashedDataForType:(FBSDKAppEventUserDataType)type;
+ (void)clearDataForType:(FBSDKAppEventUserDataType)type;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,199 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "FBSDKUserDataStore.h"
#import "FBSDKAppEventsUtility.h"
#import "FBSDKLogger.h"
#import "FBSDKSettings.h"
#import "FBSDKUtility.h"
static NSString *const FBSDKUserDataKey = @"com.facebook.appevents.UserDataStore.userData";
static NSMutableDictionary<NSString *, NSString *> *hashedUserData;
static dispatch_queue_t serialQueue;
@implementation FBSDKUserDataStore
+ (void)initialize
{
serialQueue = dispatch_queue_create("com.facebook.appevents.UserDataStore", DISPATCH_QUEUE_SERIAL);
NSString *userData = [[NSUserDefaults standardUserDefaults] stringForKey:FBSDKUserDataKey];
if (userData) {
hashedUserData = (NSMutableDictionary<NSString *, NSString *> *)[NSJSONSerialization JSONObjectWithData:[userData dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:nil];
}
if (!hashedUserData) {
hashedUserData = [[NSMutableDictionary alloc] init];
}
}
+ (void)setAndHashUserEmail:(nullable NSString *)email
firstName:(nullable NSString *)firstName
lastName:(nullable NSString *)lastName
phone:(nullable NSString *)phone
dateOfBirth:(nullable NSString *)dateOfBirth
gender:(nullable NSString *)gender
city:(nullable NSString *)city
state:(nullable NSString *)state
zip:(nullable NSString *)zip
country:(nullable NSString *)country
{
NSMutableDictionary *ud = [[NSMutableDictionary alloc] init];
if (email) {
ud[FBSDKAppEventEmail] = [FBSDKUserDataStore encryptData:email type:FBSDKAppEventEmail];
}
if (firstName) {
ud[FBSDKAppEventFirstName] = [FBSDKUserDataStore encryptData:firstName type:FBSDKAppEventFirstName];
}
if (lastName) {
ud[FBSDKAppEventLastName] = [FBSDKUserDataStore encryptData:lastName type:FBSDKAppEventLastName];
}
if (phone) {
ud[FBSDKAppEventPhone] = [FBSDKUserDataStore encryptData:phone type:FBSDKAppEventPhone];
}
if (dateOfBirth) {
ud[FBSDKAppEventDateOfBirth] = [FBSDKUserDataStore encryptData:dateOfBirth type:FBSDKAppEventDateOfBirth];
}
if (gender) {
ud[FBSDKAppEventGender] = [FBSDKUserDataStore encryptData:gender type:FBSDKAppEventGender];
}
if (city) {
ud[FBSDKAppEventCity] = [FBSDKUserDataStore encryptData:city type:FBSDKAppEventCity];
}
if (state) {
ud[FBSDKAppEventState] = [FBSDKUserDataStore encryptData:state type:FBSDKAppEventState];
}
if (zip) {
ud[FBSDKAppEventZip] = [FBSDKUserDataStore encryptData:zip type:FBSDKAppEventZip];
}
if (country) {
ud[FBSDKAppEventCountry] = [FBSDKUserDataStore encryptData:country type:FBSDKAppEventCountry];
}
dispatch_async(serialQueue, ^{
hashedUserData = [ud mutableCopy];
[[NSUserDefaults standardUserDefaults] setObject:[FBSDKUserDataStore stringByHashedData:hashedUserData]
forKey:FBSDKUserDataKey];
});
}
+ (void)setAndHashData:(nullable NSString *)data
forType:(FBSDKAppEventUserDataType)type
{
[FBSDKUserDataStore setHashData:[FBSDKUserDataStore encryptData:data type:type]
forType:type];
}
+ (void)setHashData:(nullable NSString *)hashData
forType:(FBSDKAppEventUserDataType)type
{
dispatch_async(serialQueue, ^{
if (!hashData) {
[hashedUserData removeObjectForKey:type];
} else {
hashedUserData[type] = hashData;
}
[[NSUserDefaults standardUserDefaults] setObject:[FBSDKUserDataStore stringByHashedData:hashedUserData]
forKey:FBSDKUserDataKey];
});
}
+ (void)clearDataForType:(FBSDKAppEventUserDataType)type
{
[FBSDKUserDataStore setAndHashData:nil forType:type];
}
+ (NSString *)getHashedData
{
__block NSString *hashedUserDataString;
dispatch_sync(serialQueue, ^{
hashedUserDataString = [FBSDKUserDataStore stringByHashedData:hashedUserData];
});
return hashedUserDataString;
}
+ (NSString *)getHashedDataForType:(FBSDKAppEventUserDataType)type
{
__block NSString *hashedData;
dispatch_sync(serialQueue, ^{
hashedData = [hashedUserData objectForKey:type];
});
return hashedData;
}
+ (NSString *)stringByHashedData:(id)hashedData
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:hashedData
options:0
error:&error];
if (jsonData) {
return [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
} else {
[FBSDKAppEventsUtility logAndNotify:[NSString stringWithFormat:@"Invalid json object: %@", error]];
return @"";
}
}
+ (NSString *)encryptData:(NSString *)data
type:(FBSDKAppEventUserDataType)type
{
if (data.length == 0 || [FBSDKUserDataStore maybeSHA256Hashed:data]) {
return data;
}
return [FBSDKUtility SHA256Hash:[FBSDKUserDataStore normalizeData:data type:type]];
}
+ (NSString *)normalizeData:(NSString *)data
type:(FBSDKAppEventUserDataType)type
{
NSString *normalizedData = @"";
NSSet<FBSDKAppEventUserDataType> *set = [NSSet setWithArray:
@[FBSDKAppEventEmail, FBSDKAppEventFirstName, FBSDKAppEventLastName, FBSDKAppEventCity, FBSDKAppEventState, FBSDKAppEventCountry]];
if ([set containsObject:type]) {
normalizedData = [data stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
normalizedData = normalizedData.lowercaseString;
} else if ([type isEqualToString:FBSDKAppEventPhone]) {
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^0-9]"
options:NSRegularExpressionCaseInsensitive
error:&error
];
normalizedData = [regex stringByReplacingMatchesInString:data
options:0
range:NSMakeRange(0, data.length)
withTemplate:@""
];
} else if ([type isEqualToString:FBSDKAppEventGender]) {
NSString *temp = [data stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
temp = temp.lowercaseString;
normalizedData = temp.length > 0 ? [temp substringToIndex:1]: @"";
}
return normalizedData;
}
+ (BOOL)maybeSHA256Hashed:(NSString *)data
{
NSRange range = [data rangeOfString:@"[A-Fa-f0-9]{64}" options:NSRegularExpressionSearch];
return (data.length == 64) && (range.location != NSNotFound);
}
@end

View file

@ -1,35 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
typedef void (^FBSDKDownloadCompletionBlock)(BOOL success);
@interface FBSDKModelManager : NSObject
+ (void)enable;
+ (nullable NSDictionary *)getRules;
+ (nullable NSString *)getWeightsPath:(NSString *_Nonnull)useCaseKey;
@end
#endif

View file

@ -1,233 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKModelManager.h"
#import "FBSDKAddressFilterManager.h"
#import "FBSDKAddressInferencer.h"
#import "FBSDKEventInferencer.h"
#import "FBSDKFeatureExtractor.h"
#import "FBSDKFeatureManager.h"
#import "FBSDKGraphRequest.h"
#import "FBSDKGraphRequestConnection.h"
#import "FBSDKSettings.h"
#import "FBSDKSuggestedEventsIndexer.h"
#import "FBSDKTypeUtility.h"
#import "FBSDKViewHierarchyMacros.h"
#define FBSDK_ML_MODEL_PATH @"models"
static NSString *const MODEL_INFO_KEY= @"com.facebook.sdk:FBSDKModelInfo";
static NSString *const ASSET_URI_KEY = @"asset_uri";
static NSString *const RULES_URI_KEY = @"rules_uri";
static NSString *const THRESHOLDS_KEY = @"thresholds";
static NSString *const USE_CASE_KEY = @"use_case";
static NSString *const VERSION_ID_KEY = @"version_id";
static NSString *const MODEL_DATA_KEY = @"data";
static NSString *const ADDRESS_FILTERING_KEY = @"DATA_DETECTION_ADDRESS";
static NSString *_directoryPath;
static NSMutableDictionary<NSString *, id> *_modelInfo;
@implementation FBSDKModelManager
+ (void)enable
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *languageCode = [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode];
// If the languageCode could not be fetched successfully, it's regarded as "en" by default.
if (languageCode && ![languageCode isEqualToString:@"en"]) {
return;
}
NSString *dirPath = [NSTemporaryDirectory() stringByAppendingPathComponent:FBSDK_ML_MODEL_PATH];
if (![[NSFileManager defaultManager] fileExistsAtPath:dirPath]) {
[[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:NO attributes:NULL error:NULL];
}
_directoryPath = dirPath;
// fetch api
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:@"%@/model_asset", [FBSDKSettings appID]]];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error) {
return;
}
NSDictionary<NSString *, id> *resultDictionary = [FBSDKTypeUtility dictionaryValue:result];
NSDictionary<NSString *, id> *modelInfo = [self convertToDictionary:resultDictionary[MODEL_DATA_KEY]];
if (!modelInfo) {
return;
}
// update cache
[[NSUserDefaults standardUserDefaults] setObject:modelInfo forKey:MODEL_INFO_KEY];
[FBSDKFeatureManager checkFeature:FBSDKFeatureSuggestedEvents completionBlock:^(BOOL enabled) {
if (enabled) {
[self getModelAndRules:SUGGEST_EVENT_KEY handler:^(BOOL success){
if (success) {
[FBSDKEventInferencer loadWeights];
[FBSDKFeatureExtractor loadRules];
[FBSDKSuggestedEventsIndexer enable];
}
}];
}
}];
[FBSDKFeatureManager checkFeature:FBSDKFeaturePIIFiltering completionBlock:^(BOOL enabled) {
if (enabled) {
[self getModelAndRules:ADDRESS_FILTERING_KEY handler:^(BOOL success){
if (success) {
[FBSDKAddressInferencer loadWeights];
[FBSDKAddressInferencer initializeDenseFeature];
[FBSDKAddressFilterManager enable];
}
}];
}
}];
}];
});
}
+ (void)getModelAndRules:(NSString *)useCaseKey
handler:(FBSDKDownloadCompletionBlock)handler
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
_modelInfo = [[NSUserDefaults standardUserDefaults] objectForKey:MODEL_INFO_KEY];
if (!_modelInfo || !_directoryPath) {
if (handler) {
handler(NO);
return;
}
}
NSDictionary<NSString *, id> *model = [_modelInfo objectForKey:useCaseKey];
if (!model) {
if (handler) {
handler(NO);
return;
}
}
// clear old model files
NSArray<NSString *> *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:_directoryPath error:nil];
NSString *prefixWithVersion = [NSString stringWithFormat:@"%@_%@", useCaseKey, model[VERSION_ID_KEY]];
for (NSString *file in files) {
if ([file hasPrefix:useCaseKey] && ![file hasPrefix:prefixWithVersion]) {
[[NSFileManager defaultManager] removeItemAtPath:[_directoryPath stringByAppendingPathComponent:file] error:nil];
}
}
// download model asset
NSString *assetUrlString = [model objectForKey:ASSET_URI_KEY];
NSString *assetFilePath;
if (assetUrlString.length > 0) {
assetFilePath = [_directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@.weights", useCaseKey, model[VERSION_ID_KEY]]];
[self download:assetUrlString filePath:assetFilePath queue:queue group:group];
}
// download rules
NSString *rulesUrlString = [model objectForKey:RULES_URI_KEY];
NSString *rulesFilePath;
// rules are optional and rulesUrlString may be empty
if (rulesUrlString.length > 0) {
rulesFilePath = [_directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@.rules", useCaseKey, model[VERSION_ID_KEY]]];
[self download:rulesUrlString filePath:rulesFilePath queue:queue group:group];
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
if (handler) {
if ([[NSFileManager defaultManager] fileExistsAtPath:assetFilePath] && (!rulesUrlString || (rulesUrlString && [[NSFileManager defaultManager] fileExistsAtPath:rulesFilePath]))) {
handler(YES);
return;
}
handler(NO);
}
});
}
+ (void)download:(NSString *)urlString
filePath:(NSString *)filePath
queue:(dispatch_queue_t)queue
group:(dispatch_group_t)group
{
if (!filePath || [[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
return;
}
dispatch_group_async(group, queue, ^{
NSURL *url = [NSURL URLWithString:urlString];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if (urlData) {
[urlData writeToFile:filePath atomically:YES];
}
});
}
+ (nullable NSMutableDictionary<NSString *, id> *)convertToDictionary:(NSArray<NSDictionary<NSString *, id> *> *)models
{
if ([models count] == 0) {
return nil;
}
NSMutableDictionary<NSString *, id> *modelInfo = [NSMutableDictionary dictionary];
for (NSDictionary<NSString *, id> *model in models) {
if (model[USE_CASE_KEY]) {
[modelInfo addEntriesFromDictionary:@{model[USE_CASE_KEY]:model}];
}
}
return modelInfo;
}
+ (nullable NSDictionary *)getRules
{
NSDictionary<NSString *, id> *cachedModelInfo = [[NSUserDefaults standardUserDefaults] objectForKey:MODEL_INFO_KEY];
if (!cachedModelInfo) {
return nil;
}
NSDictionary<NSString *, id> *model = [cachedModelInfo objectForKey:SUGGEST_EVENT_KEY];
if (model && model[VERSION_ID_KEY]) {
NSString *filePath = [_directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@.rules", SUGGEST_EVENT_KEY, model[VERSION_ID_KEY]]];
if (filePath) {
NSData *ruelsData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *rules = [NSJSONSerialization JSONObjectWithData:ruelsData options:0 error:nil];
return rules;
}
}
return nil;
}
+ (nullable NSString *)getWeightsPath:(NSString *_Nonnull)useCaseKey
{
NSDictionary<NSString *, id> *cachedModelInfo = [[NSUserDefaults standardUserDefaults] objectForKey:MODEL_INFO_KEY];
if (!cachedModelInfo || !_directoryPath) {
return nil;
}
NSDictionary<NSString *, id> *model = [cachedModelInfo objectForKey:useCaseKey];
if (model && model[VERSION_ID_KEY]) {
return [_directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@.weights", useCaseKey, model[VERSION_ID_KEY]]];
}
return nil;
}
@end
#endif

View file

@ -1,310 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#include <float.h>
#include <math.h>
#include <stdint.h>
#include <unordered_map>
#include <unordered_set>
#import <Accelerate/Accelerate.h>
#include "FBSDKStandaloneModel.hpp"
#define SEQ_LEN 128
#define ALPHABET_SIZE 256
#define EMBEDDING_SIZE 64
#define DENSE_FEATURE_LEN 30
const int CONV_BLOCKS[3][3] = {{32, 2, SEQ_LEN - 1}, {32, 3, SEQ_LEN - 2}, {32, 5, SEQ_LEN - 4}};
namespace mat1 {
static void relu(float *data, int len) {
float min = 0;
float max = FLT_MAX;
vDSP_vclip(data, 1, &min, &max, data, 1, len);
}
static void concatenate(float *dst, float *a, float *b, int a_len, int b_len) {
memcpy(dst, a, a_len * sizeof(float));
memcpy(dst + a_len, b, b_len * sizeof(float));
}
static void softmax(float *data, int n) {
int i = 0;
float max = FLT_MIN;
float sum = 0;
for (i = 0; i < n; i++) {
if (data[i] > max) {
max = data[i];
}
}
for (i = 0; i < n; i++){
data[i] = expf(data[i] - max);
}
for (i = 0; i < n; i++){
sum += data[i];
}
for (i = 0; i < n; i++){
data[i] = data[i] / sum;
}
}
static float* embedding(int *a, float *b, int n_examples, int seq_length, int embedding_size) {
int i,j,k,val;
float* res = (float *)malloc(sizeof(float) * (n_examples * seq_length * embedding_size));
for (i = 0; i < n_examples; i++) {
for (j = 0; j < seq_length; j++) {
val = a[i * seq_length + j];
for (k = 0; k < embedding_size; k++) {
res[(embedding_size * seq_length) * i + embedding_size * j + k] = b[val * embedding_size + k];
}
}
}
return res;
}
/*
a shape: n_examples, in_vector_size
b shape: n_examples, out_vector_size
c shape: out_vector_size
return shape: n_examples, out_vector_size
*/
static float* dense(float *a, float *b, float *c, int n_examples, int in_vector_size, int out_vector_size) {
int i,j;
float *m_res = (float *)malloc(sizeof(float) * (n_examples * out_vector_size));
vDSP_mmul(a, 1, b, 1, m_res, 1, n_examples, out_vector_size, in_vector_size);
for (i = 0; i < n_examples; i++) {
for (j = 0; j < out_vector_size; j++) {
m_res[i * out_vector_size + j] += c[j];
}
}
return m_res;
}
/*
x shape: n_examples, seq_len, input_size
w shape: kernel_size, input_size, output_size
return shape: n_examples, seq_len - kernel_size + 1, output_size
*/
static float* conv1D(float *x, float *w, int n_examples, int seq_len, int input_size, int kernel_size, int output_size) {
int n, o, i, k, m;
float sum;
float *res = (float *)malloc(sizeof(float) * (n_examples * (seq_len - kernel_size + 1) * output_size));
float *temp_x = (float *)malloc(sizeof(float) * (kernel_size * input_size));
float *temp_w = (float *)malloc(sizeof(float) * (kernel_size * input_size));
for (n = 0; n < n_examples; n++){
for (o = 0; o < output_size; o++){
for (i = 0; i < seq_len - kernel_size + 1; i++) {
sum = 0;
for (m = 0; m < kernel_size; m++) {
for (k = 0; k < input_size; k++) {
temp_x[m * input_size + k] = x[n * (seq_len * input_size) + (m + i) * input_size + k];
temp_w[m * input_size + k] = w[(m * input_size + k) * output_size + o];
}
}
vDSP_dotpr(temp_x, 1, temp_w, 1, &sum, kernel_size * input_size);
res[(n * (output_size * (seq_len - kernel_size + 1)) + i * output_size + o)] = sum;
}
}
}
free(temp_x);
free(temp_w);
return res;
}
/*
input shape: n_examples, len, n_channel
return shape: n_examples, len - pool_size + 1, n_channel
*/
static float* maxPool1D(float *input, int n_examples, int input_len, int n_channel, int pool_size) {
int res_len = input_len - pool_size + 1;
float* res = (float *)calloc(n_examples * res_len * n_channel, sizeof(float));
for (int n = 0; n < n_examples; n++) {
for (int c = 0; c < n_channel; c++) {
for (int i = 0; i < res_len; i++) {
for (int r = i; r < i + pool_size; r++) {
int res_pos = n * (n_channel * res_len) + i * n_channel + c;
int input_pos = n * (n_channel * input_len) + r * n_channel + c;
if (r == i) {
res[res_pos] = input[input_pos];
} else {
res[res_pos] = fmax(res[res_pos], input[input_pos]);
}
}
}
}
}
return res;
}
static int* vectorize(const char *texts, int str_len, int max_len) {
int *res = (int *)malloc(sizeof(int) * max_len);
for (int i = 0; i < max_len; i++) {
if (i < str_len){
res[i] = static_cast<unsigned char>(texts[i]);
} else {
res[i] = 0;
}
}
return res;
}
/*
input shape: m, n
return shape: n, m
*/
static float* transpose2D(float *input, int m, int n) {
float *transposed = (float *)malloc(sizeof(float) * m * n);
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++) {
transposed[j * m + i] = input[i * n + j];
}
}
return transposed;
}
/*
input shape: m, n, p
return shape: p, n, m
*/
static float* transpose3D(float *input, int64_t m, int n, int p) {
float *transposed = (float *)malloc((size_t)(sizeof(float) * m * n * p));
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++) {
for (int k = 0; k < p; k++) {
transposed[k * m * n + j * m + i] = input[i * n * p + j * p + k];
}
}
}
return transposed;
}
static float* add(float *a, float *b, int m, int n, int p) {
for(int i = 0; i < m * n; i++){
for(int j = 0; j < p; j++){
a[i * p + j] += b[j];
}
}
return a;
}
static float* predictOnText(const char *texts, std::unordered_map<std::string, mat::MTensor>& weights, float *df) {
int *x;
float *embed_x;
float *dense1_x;
float *dense2_x;
float *dense3_x;
float *c1;
float *c2;
float *c3;
float *ca;
float *cb;
float *cc;
mat::MTensor& embed_t = weights.at("embed.weight");
mat::MTensor& conv1w_t = weights.at("convs.0.weight"); // (32, 64, 2)
mat::MTensor& conv2w_t = weights.at("convs.1.weight");
mat::MTensor& conv3w_t = weights.at("convs.2.weight");
mat::MTensor& conv1b_t = weights.at("convs.0.bias");
mat::MTensor& conv2b_t = weights.at("convs.1.bias");
mat::MTensor& conv3b_t = weights.at("convs.2.bias");
mat::MTensor& fc1w_t = weights.at("fc1.weight"); // (128, 126)
mat::MTensor& fc1b_t = weights.at("fc1.bias"); // 128
mat::MTensor& fc2w_t = weights.at("fc2.weight"); // (64, 128)
mat::MTensor& fc2b_t = weights.at("fc2.bias"); // 64
mat::MTensor& fc3w_t = weights.at("fc3.weight"); // (2, 64) or (4, 64)
mat::MTensor& fc3b_t = weights.at("fc3.bias"); // 2 or 4
float *embed_weight = embed_t.data<float>();
float *convs_0_weight = transpose3D(conv1w_t.data<float>(), (int)conv1w_t.size(0), (int)conv1w_t.size(1), (int)conv1w_t.size(2)); // (2, 64, 32)
float *convs_1_weight = transpose3D(conv2w_t.data<float>(), (int)conv2w_t.size(0), (int)conv2w_t.size(1), (int)conv2w_t.size(2));
float *convs_2_weight = transpose3D(conv3w_t.data<float>(), (int)conv3w_t.size(0), (int)conv3w_t.size(1), (int)conv3w_t.size(2));
float *convs_0_bias = conv1b_t.data<float>();
float *convs_1_bias = conv2b_t.data<float>();
float *convs_2_bias = conv3b_t.data<float>();
float *fc1_weight = transpose2D(fc1w_t.data<float>(), (int)fc1w_t.size(0), (int)fc1w_t.size(1));
float *fc2_weight = transpose2D(fc2w_t.data<float>(), (int)fc2w_t.size(0), (int)fc2w_t.size(1));
float *fc3_weight = transpose2D(fc3w_t.data<float>(), (int)fc3w_t.size(0), (int)fc3w_t.size(1));
float *fc1_bias = fc1b_t.data<float>();
float *fc2_bias = fc2b_t.data<float>();
float *fc3_bias = fc3b_t.data<float>();
// vectorize text
x = vectorize(texts, (int)strlen(texts), SEQ_LEN);
// embedding
embed_x = embedding(x, embed_weight, 1, SEQ_LEN, EMBEDDING_SIZE); // (1, 128, 64)
free(x);
// conv1D
c1 = conv1D(embed_x, convs_0_weight, 1, SEQ_LEN, EMBEDDING_SIZE, (int)conv1w_t.size(2), (int)conv1w_t.size(0)); // (1, 127, 32) CONV_BLOCKS[0][1], CONV_BLOCKS[0][0]
c2 = conv1D(embed_x, convs_1_weight, 1, SEQ_LEN, EMBEDDING_SIZE, (int)conv2w_t.size(2), (int)conv2w_t.size(0)); // (1, 126, 32)
c3 = conv1D(embed_x, convs_2_weight, 1, SEQ_LEN, EMBEDDING_SIZE, (int)conv3w_t.size(2), (int)conv3w_t.size(0)); // (1, 124, 32)
free(embed_x);
// add bias
add(c1, convs_0_bias, 1, (int)(SEQ_LEN - conv1w_t.size(2) + 1), (int)conv1w_t.size(0));
add(c2, convs_1_bias, 1, (int)(SEQ_LEN - conv2w_t.size(2) + 1), (int)conv2w_t.size(0));
add(c3, convs_2_bias, 1, (int)(SEQ_LEN - conv3w_t.size(2) + 1), (int)conv3w_t.size(0));
// relu
relu(c1, (int)(SEQ_LEN - conv1w_t.size(2) + 1) * (int)conv1w_t.size(0));
relu(c2, (int)(SEQ_LEN - conv2w_t.size(2) + 1) * (int)conv2w_t.size(0));
relu(c3, (int)(SEQ_LEN - conv3w_t.size(2) + 1) * (int)conv3w_t.size(0));
// max pooling
ca = maxPool1D(c1, 1, (int)(SEQ_LEN - conv1w_t.size(2) + 1), (int)conv1w_t.size(0), (int)(SEQ_LEN - conv1w_t.size(2) + 1)); // (1, 1, 32)
cb = maxPool1D(c2, 1, (int)(SEQ_LEN - conv2w_t.size(2) + 1), (int)conv2w_t.size(0), (int)(SEQ_LEN - conv2w_t.size(2) + 1)); // (1, 1, 32)
cc = maxPool1D(c3, 1, (int)(SEQ_LEN - conv3w_t.size(2) + 1), (int)conv3w_t.size(0), (int)(SEQ_LEN - conv3w_t.size(2) + 1)); // (1, 1, 32)
free(c1);
free(c2);
free(c3);
// concatenate
float *concat = (float *)malloc((size_t)(sizeof(float) * (conv1w_t.size(0) + conv2w_t.size(0) + conv3w_t.size(0) + 30)));
concatenate(concat, ca, cb, (int)conv1w_t.size(0), (int)conv2w_t.size(0));
concatenate(concat + conv1w_t.size(0) + conv2w_t.size(0), cc, df, (int)conv3w_t.size(0), 30);
free(ca);
free(cb);
free(cc);
// dense + relu
dense1_x = dense(concat, fc1_weight, fc1_bias, 1, (int)fc1w_t.size(1), (int)fc1w_t.size(0));
free(concat);
relu(dense1_x, (int)fc1b_t.size(0));
dense2_x = dense(dense1_x, fc2_weight, fc2_bias, 1, (int)fc2w_t.size(1), (int)fc2w_t.size(0));
relu(dense2_x, (int)fc2b_t.size(0));
free(dense1_x);
dense3_x = dense(dense2_x, fc3_weight, fc3_bias, 1, (int)fc3w_t.size(1), (int)fc3w_t.size(0));
free(dense2_x);
softmax(dense3_x, (int)fc3b_t.size(0));
return dense3_x;
}
}
#endif

View file

@ -1,31 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
@interface FBSDKModelUtility : NSObject
+ (NSString *)normalizeText:(NSString *)text;
@end
#endif

View file

@ -1,38 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
#import "FBSDKModelUtility.h"
@implementation FBSDKModelUtility : NSObject
+ (NSString *)normalizeText:(NSString *)text
{
NSMutableArray *tokens = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
[tokens removeObject:@""];
return [tokens componentsJoinedByString: @" "];
}
@end
#endif

View file

@ -1,152 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#include <cassert>
#include <cmath>
#include <cstring>
#include <iostream>
#include <memory>
#include <stddef.h>
#include <stdint.h>
#include <unordered_map>
#include <vector>
#import <Accelerate/Accelerate.h>
// minimal aten implementation
#define MAT_ALWAYS_INLINE inline __attribute__((always_inline))
namespace mat {
template <typename T, size_t N>
class MTensorAccessor {
public:
MAT_ALWAYS_INLINE
MTensorAccessor(T* data, const int64_t* sizes, const int64_t* strides)
: data_(data), sizes_(sizes), strides_(strides) {}
MAT_ALWAYS_INLINE MTensorAccessor<T, N - 1> operator[](int64_t i) {
return MTensorAccessor<T, N - 1>(
this->data_ + this->strides_[0] * i,
this->sizes_ + 1,
this->strides_ + 1);
}
T* data_;
private:
const int64_t* sizes_;
const int64_t* strides_;
};
template <typename T>
class MTensorAccessor<T, 1> {
public:
MAT_ALWAYS_INLINE
MTensorAccessor(T* data, const int64_t* sizes, const int64_t* strides)
: data_(data), sizes_(sizes), strides_(strides) {}
MAT_ALWAYS_INLINE T& operator[](int64_t i) {
// assume stride==1 in innermost dimension.
// DCHECK_EQ(strides_[0], 1);
return this->data_[i];
}
T* data_;
private:
const int64_t* sizes_;
const int64_t* strides_;
};
static void* MAllocateMemory(size_t nbytes) {
void* ptr = nullptr;
assert(nbytes > 0);
#ifdef __ANDROID__
ptr = memalign(64, nbytes);
#else
const int ret = posix_memalign(&ptr, 64, nbytes);
(void)ret;
assert(ret == 0);
#endif
return ptr;
}
static void MFreeMemory(void* ptr) {
free(ptr);
}
static void MCheckPtr(void* ptr) {
if (ptr) {
MFreeMemory(ptr);
}
}
class MTensor {
public:
MTensor(){};
MTensor(const std::vector<int64_t>& sizes) {
auto strides = std::vector<int64_t>(sizes.size());
strides[strides.size() - 1] = 1;
for (auto i = static_cast<int32_t>(strides.size()) - 2; i >= 0; --i) {
strides[i] = strides[i + 1] * sizes[i + 1];
}
strides_ = strides;
sizes_ = sizes;
// assume float32 storage.
size_t nbytes = sizeof(float);
for (auto size : sizes) {
nbytes *= size;
}
storage_ = std::shared_ptr<void>(MAllocateMemory(nbytes), MCheckPtr);
}
int64_t size(int dim) {
return sizes_[dim];
}
const std::vector<int64_t>& sizes() const {
return sizes_;
}
const std::vector<int64_t>& strides() const {
return strides_;
}
template <typename T>
T* data() {
return static_cast<T*>(storage_.get());
}
template <typename T, size_t N>
MTensorAccessor<T, N> accessor() {
return MTensorAccessor<T, N>(data<T>(), sizes().data(), strides().data());
}
private:
std::vector<int64_t> sizes_;
std::vector<int64_t> strides_;
std::shared_ptr<void> storage_;
};
static MTensor mempty(const std::vector<int64_t>& sizes) {
return MTensor(sizes);
}
} // namespace mat
#endif

View file

@ -1,32 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
@interface FBSDKAddressFilterManager : NSObject
+ (void)enable;
+ (nullable NSDictionary<NSString *, id> *)processParameters:(nullable NSDictionary<NSString *, id> *)parameters;
@end
#endif

View file

@ -1,69 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKAddressFilterManager.h"
#import "FBSDKAddressInferencer.h"
#import "FBSDKBasicUtility.h"
#import "FBSDKGateKeeperManager.h"
#import "FBSDKSettings.h"
#import "FBSDKTypeUtility.h"
static BOOL isAddressFilterEnabled = NO;
static BOOL isSampleEnabled = NO;
@implementation FBSDKAddressFilterManager
+ (void)enable
{
isAddressFilterEnabled = YES;
isSampleEnabled = [FBSDKGateKeeperManager boolForKey:@"FBSDKFeatureAddressDetectionSample" defaultValue:false];
}
+ (nullable NSDictionary<NSString *, id> *)processParameters:(nullable NSDictionary<NSString *, id> *)parameters
{
if (!isAddressFilterEnabled || parameters.count == 0) {
return parameters;
}
NSMutableDictionary<NSString *, id> *params = [NSMutableDictionary dictionaryWithDictionary:parameters];
NSMutableDictionary<NSString *, id> *addressParams = [NSMutableDictionary dictionary];
for (NSString *key in [parameters keyEnumerator]) {
NSString *valueString =[FBSDKTypeUtility stringValue:parameters[key]];
BOOL shouldFilter = [FBSDKAddressInferencer shouldFilterParam:valueString];
if (shouldFilter) {
[addressParams setObject:isSampleEnabled ? valueString : @"" forKey:key];
[params removeObjectForKey:key];
}
}
if ([addressParams count] > 0) {
NSString *addressParamsJSONString = [FBSDKBasicUtility JSONStringForObject:addressParams
error:NULL
invalidObjectHandler:NULL];
[FBSDKBasicUtility dictionary:params setObject:addressParamsJSONString forKey:@"_onDeviceParams"];
}
return [params copy];
}
@end
#endif

View file

@ -1,37 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface FBSDKAddressInferencer : NSObject
+ (void)initializeDenseFeature;
+ (void)loadWeights;
+ (BOOL)shouldFilterParam:(nullable NSString *)param;
@end
NS_ASSUME_NONNULL_END
#endif

View file

@ -1,213 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import "FBSDKAddressInferencer.h"
#import "FBSDKModelManager.h"
#import "FBSDKModelRuntime.hpp"
#import "FBSDKModelUtility.h"
#import "FBSDKStandaloneModel.hpp"
#include<stdexcept>
static NSString *const MODEL_INFO_KEY= @"com.facebook.sdk:FBSDKModelInfo";
static NSString *const THRESHOLDS_KEY = @"thresholds";
static NSString *const DATA_DETECTION_ADDRESS_KEY = @"DATA_DETECTION_ADDRESS";
static NSDictionary<NSString *, NSArray *> *const WEIGHTS_INFO = @{@"embed.weight" : @[@(256), @(64)],
@"convs.0.weight" : @[@(32), @(64), @(2)],
@"convs.0.bias" : @[@(32)],
@"convs.1.weight" : @[@(32), @(64), @(3)],
@"convs.1.bias" : @[@(32)],
@"convs.2.weight" : @[@(32), @(64), @(5)],
@"convs.2.bias" : @[@(32)],
@"fc1.weight": @[@(128), @(126)],
@"fc1.bias": @[@(128)],
@"fc2.weight": @[@(64), @(128)],
@"fc2.bias": @[@(64)],
@"fc3.weight": @[@(2), @(64)],
@"fc3.bias": @[@(2)]};
static NSDictionary<NSString *, NSString *> *const WEIGHTS_KEYS = @{@"embedding.weight": @"embed.weight",
@"dense1.weight": @"fc1.weight",
@"dense2.weight": @"fc2.weight",
@"dense3.weight": @"fc3.weight",
@"dense1.bias": @"fc1.bias",
@"dense2.bias": @"fc2.bias",
@"dense3.bias": @"fc3.bias"};
@implementation FBSDKAddressInferencer : NSObject
static std::unordered_map<std::string, mat::MTensor> _weights;
static std::vector<float> _denseFeature;
+ (void)initializeDenseFeature
{
std::vector<float> dense_feature(30);
std::fill(dense_feature.begin(), dense_feature.end(), 0);
_denseFeature = dense_feature;
}
+ (void)loadWeights
{
NSString *path = [FBSDKModelManager getWeightsPath:DATA_DETECTION_ADDRESS_KEY];
if (!path) {
return;
}
NSData *latestData = [NSData dataWithContentsOfFile:path
options:NSDataReadingMappedIfSafe
error:nil];
if (!latestData) {
return;
}
std::unordered_map<std::string, mat::MTensor> weights = [self loadWeights:latestData];
if ([self validateWeights:weights]) {
_weights = weights;
}
}
+ (bool)validateWeights: (std::unordered_map<std::string, mat::MTensor>) weights
{
if (WEIGHTS_INFO.count != weights.size()) {
return false;
}
try {
for (NSString *key in WEIGHTS_INFO) {
if (weights.count(std::string([key UTF8String])) == 0) {
return false;
}
mat::MTensor tensor = weights[std::string([key UTF8String])];
const std::vector<int64_t>& actualSize = tensor.sizes();
NSArray *expectedSize = WEIGHTS_INFO[key];
if (actualSize.size() != expectedSize.count) {
return false;
}
for (int i = 0; i < expectedSize.count; i++) {
if((int)actualSize[i] != (int)[expectedSize[i] intValue]) {
return false;
}
}
}
} catch (const std::exception &e) {
return false;
}
return true;
}
+ (std::unordered_map<std::string, mat::MTensor>)loadWeights:(NSData *)weightsData{
std::unordered_map<std::string, mat::MTensor> weights;
const void *data = weightsData.bytes;
NSUInteger totalLength = weightsData.length;
int totalFloats = 0;
if (weightsData.length < 4) {
// Make sure data length is valid
return weights;
}
try {
int length;
memcpy(&length, data, 4);
if (length + 4 > totalLength) {
// Make sure data length is valid
return weights;
}
char *json = (char *)data + 4;
NSDictionary<NSString *, id> *info = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:json length:length]
options:0
error:nil];
NSArray<NSString *> *keys = [[info allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2) {
return [key1 compare:key2];
}];
float *floats = (float *)(json + length);
for (NSString *key in keys) {
NSString *finalKey = key;
NSString *mapping = [WEIGHTS_KEYS objectForKey:key];
if (mapping) {
finalKey = mapping;
}
std::string s_name([finalKey UTF8String]);
std::vector<int64_t> v_shape;
NSArray<NSString *> *shape = [info objectForKey:key];
int count = 1;
for (NSNumber *_s in shape) {
int i = [_s intValue];
v_shape.push_back(i);
count *= i;
}
totalFloats += count;
if ((4 + length + totalFloats * 4) > totalLength) {
// Make sure data length is valid
break;
}
mat::MTensor tensor = mat::mempty(v_shape);
float *tensor_data = tensor.data<float>();
memcpy(tensor_data, floats, sizeof(float) * count);
floats += count;
weights[s_name] = tensor;
}
} catch (const std::exception &e) {}
return weights;
}
+ (BOOL)shouldFilterParam:(nullable NSString *)param
{
if (!param || _weights.size() == 0 || _denseFeature.size() == 0) {
return false;
}
NSString *text = [FBSDKModelUtility normalizeText:param];
const char *bytes = [text UTF8String];
if ((int)strlen(bytes) == 0) {
return false;
}
float *predictedRaw;
NSMutableDictionary<NSString *, id> *modelInfo = [[NSUserDefaults standardUserDefaults] objectForKey:MODEL_INFO_KEY];
if (!modelInfo) {
return false;
}
NSDictionary<NSString *, id> * addressModelInfo = [modelInfo objectForKey:DATA_DETECTION_ADDRESS_KEY];
if (!addressModelInfo) {
return false;
}
NSMutableArray *thresholds = [addressModelInfo objectForKey:THRESHOLDS_KEY];
float threshold = [thresholds[0] floatValue];
try {
predictedRaw = mat1::predictOnText(bytes, _weights, &_denseFeature[0]);
if (!predictedRaw[1]) {
return false;
}
return predictedRaw[1] >= threshold;
} catch (const std::exception &e) {
return false;
}
}
@end
#endif

View file

@ -1,35 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface FBSDKRestrictiveDataFilterManager : NSObject
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
+ (void)enable;
+ (void)updateFilters:(nullable NSDictionary<NSString *, id> *)restrictiveParams;
+ (nullable NSDictionary<NSString *, id> *)processParameters:(nullable NSDictionary<NSString *, id> *)parameters
eventName:(NSString *)eventName;
@end
NS_ASSUME_NONNULL_END

View file

@ -1,146 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "FBSDKRestrictiveDataFilterManager.h"
#import "FBSDKBasicUtility.h"
#import "FBSDKTypeUtility.h"
static NSString *const RESTRICTIVE_PARAM_KEY = @"restrictive_param";
@interface FBSDKRestrictiveEventFilter : NSObject
@property (nonatomic, readonly, copy) NSString *eventName;
@property (nonatomic, readonly, copy) NSDictionary<NSString *, id> *restrictiveParams;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
-(instancetype)initWithEventName:(NSString *)eventName
restrictiveParams:(NSDictionary<NSString *, id> *)restrictiveParams;
@end
@implementation FBSDKRestrictiveEventFilter
-(instancetype)initWithEventName:(NSString *)eventName
restrictiveParams:(NSDictionary<NSString *, id> *)restrictiveParams
{
self = [super init];
if (self) {
_eventName = eventName;
_restrictiveParams = restrictiveParams;
}
return self;
}
@end
@implementation FBSDKRestrictiveDataFilterManager
static BOOL isRestrictiveEventFilterEnabled = NO;
static NSMutableArray<FBSDKRestrictiveEventFilter *> *_params;
+ (void)updateFilters:(nullable NSDictionary<NSString *, id> *)restrictiveParams
{
if (!isRestrictiveEventFilterEnabled) {
return;
}
if (restrictiveParams.count > 0) {
[_params removeAllObjects];
NSMutableArray<FBSDKRestrictiveEventFilter *> *eventFilterArray = [NSMutableArray array];
for (NSString *eventName in restrictiveParams.allKeys) {
NSDictionary<NSString *, id> *eventInfo = restrictiveParams[eventName];
if (!eventInfo) {
return;
}
if (eventInfo[RESTRICTIVE_PARAM_KEY]) {
FBSDKRestrictiveEventFilter *restrictiveEventFilter = [[FBSDKRestrictiveEventFilter alloc] initWithEventName:eventName
restrictiveParams:eventInfo[RESTRICTIVE_PARAM_KEY]];
[eventFilterArray addObject:restrictiveEventFilter];
}
}
_params = eventFilterArray;
}
}
+ (nullable NSString *)getMatchedDataTypeWithEventName:(NSString *)eventName
paramKey:(NSString *)paramKey
{
// match by params in custom events with event name
for (FBSDKRestrictiveEventFilter *filter in _params) {
if ([filter.eventName isEqualToString:eventName]) {
NSString *type = [FBSDKTypeUtility stringValue:filter.restrictiveParams[paramKey]];
if (type) {
return type;
}
}
}
return nil;
}
+ (NSDictionary<NSString *,id> *)processParameters:(NSDictionary<NSString *,id> *)parameters
eventName:(NSString *)eventName
{
if (!isRestrictiveEventFilterEnabled) {
return parameters;
}
if (parameters) {
NSMutableDictionary<NSString *, id> *params = [NSMutableDictionary dictionaryWithDictionary:parameters];
NSMutableDictionary<NSString *, NSString *> *restrictedParams = [NSMutableDictionary dictionary];
for (NSString *key in [parameters keyEnumerator]) {
NSString *type = [FBSDKRestrictiveDataFilterManager getMatchedDataTypeWithEventName:eventName
paramKey:key];
if (type) {
[restrictedParams setObject:type forKey:key];
[params removeObjectForKey:key];
}
}
if ([[restrictedParams allKeys] count] > 0) {
NSString *restrictedParamsJSONString = [FBSDKBasicUtility JSONStringForObject:restrictedParams
error:NULL
invalidObjectHandler:NULL];
[FBSDKBasicUtility dictionary:params setObject:restrictedParamsJSONString forKey:@"_restrictedParams"];
}
return [params copy];
}
return nil;
}
+ (void)enable
{
isRestrictiveEventFilterEnabled = YES;
}
#pragma mark Helper functions
+ (BOOL)isMatchedWithPattern:(NSString *)pattern
text:(NSString *)text
{
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger matches = [regex numberOfMatchesInString:text options:0 range:NSMakeRange(0, text.length)];
return matches > 0;
}
@end

View file

@ -1,38 +0,0 @@
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import "TargetConditionals.h"
#if !TARGET_OS_TV
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface FBSDKEventInferencer : NSObject
+ (void)loadWeights;
+ (NSDictionary<NSString *, NSString *> *)predict:(NSString *)buttonText
viewTree:(NSMutableDictionary<NSString *, id> *)viewTree
withLog:(BOOL)isPrint;
@end
NS_ASSUME_NONNULL_END
#endif

Some files were not shown because too many files have changed in this diff Show more