diff --git a/Branch-TestBed/Branch-SDK-Tests/BNCAPIServerTest.m b/Branch-TestBed/Branch-SDK-Tests/BNCAPIServerTest.m index 5f70fcb68..b7df6da68 100644 --- a/Branch-TestBed/Branch-SDK-Tests/BNCAPIServerTest.m +++ b/Branch-TestBed/Branch-SDK-Tests/BNCAPIServerTest.m @@ -11,6 +11,7 @@ #import "BNCSystemObserver.h" #import "BNCConfig.h" #import "BranchConstants.h" +#import "Branch.h" @interface BNCAPIServerTest : XCTestCase @@ -370,4 +371,42 @@ - (void)testValidationServiceURL_EUTracking { XCTAssertTrue([url hasPrefix:expectedUrlPrefix]); } +- (void)testDefaultAPIURL { + BNCServerAPI *serverAPI = [BNCServerAPI new]; + XCTAssertNil(serverAPI.customAPIURL); + + NSString *storedUrl = [[BNCServerAPI sharedInstance] installServiceURL]; + NSString *expectedUrl = [BNC_API_URL stringByAppendingString: @"/v1/install"]; + XCTAssertEqualObjects(storedUrl, expectedUrl); +} + +- (void)testSetAPIURL_Example { + NSString *url = @"https://www.example.com"; + [Branch setAPIUrl:url]; + + NSString *storedUrl = [[BNCServerAPI sharedInstance] installServiceURL]; + NSString *expectedUrl = [url stringByAppendingString: @"/v1/install"]; + XCTAssertEqualObjects(storedUrl, expectedUrl); + + [Branch setAPIUrl:BNC_API_URL]; +} + +- (void)testSetAPIURL_InvalidHttp { + NSString *url = @"Invalid://www.example.com"; + [Branch setAPIUrl:url]; + + NSString *storedUrl = [[BNCServerAPI sharedInstance] installServiceURL]; + NSString *expectedUrl = [BNC_API_URL stringByAppendingString: @"/v1/install"]; + XCTAssertEqualObjects(storedUrl, expectedUrl); +} + +- (void)testSetAPIURL_InvalidEmpty { + NSString *url = @""; + [Branch setAPIUrl:url]; + + NSString *storedUrl = [[BNCServerAPI sharedInstance] installServiceURL]; + NSString *expectedUrl = [BNC_API_URL stringByAppendingString: @"/v1/install"]; + XCTAssertEqualObjects(storedUrl, expectedUrl); +} + @end diff --git a/Branch-TestBed/Branch-SDK-Tests/BNCLogTests.m b/Branch-TestBed/Branch-SDK-Tests/BNCLogTests.m deleted file mode 100644 index 32e6fcd82..000000000 --- a/Branch-TestBed/Branch-SDK-Tests/BNCLogTests.m +++ /dev/null @@ -1,43 +0,0 @@ -/** - @file BNCLogTests.m - @package BranchTests - @brief Tests for BNCLog. - - @author Edward Smith - @date October 2016 - @copyright Copyright © 2016 Branch. All rights reserved. -*/ - -#import -#import "BNCLog.h" - -@interface BNCLogTests : XCTestCase -@end - -@implementation BNCLogTests - -- (void)setUp { - // Put setup code here. This method is called before the invocation of each test method in the class. -} - -- (void)tearDown { - // Put teardown code here. This method is called after the invocation of each test method in the class. -} - -- (void)testLogLevelString { - XCTAssertEqual(BNCLogLevelAll, BNCLogLevelFromString(@"BNCLogLevelAll")); - XCTAssertEqual(BNCLogLevelDebugSDK, BNCLogLevelFromString(@"BNCLogLevelDebugSDK")); - XCTAssertEqual(BNCLogLevelWarning, BNCLogLevelFromString(@"BNCLogLevelWarning")); - XCTAssertEqual(BNCLogLevelNone, BNCLogLevelFromString(@"BNCLogLevelNone")); - XCTAssertEqual(BNCLogLevelMax, BNCLogLevelFromString(@"BNCLogLevelMax")); -} - -- (void)testLogLevelEnum { - XCTAssertEqualObjects(@"BNCLogLevelAll", BNCLogStringFromLogLevel(BNCLogLevelAll)); - XCTAssertEqualObjects(@"BNCLogLevelAll", BNCLogStringFromLogLevel(BNCLogLevelDebugSDK)); - XCTAssertEqualObjects(@"BNCLogLevelWarning", BNCLogStringFromLogLevel(BNCLogLevelWarning)); - XCTAssertEqualObjects(@"BNCLogLevelNone", BNCLogStringFromLogLevel(BNCLogLevelNone)); - XCTAssertEqualObjects(@"BNCLogLevelMax", BNCLogStringFromLogLevel(BNCLogLevelMax)); -} - -@end diff --git a/Branch-TestBed/Branch-SDK-Tests/BNCPreferenceHelperTests.m b/Branch-TestBed/Branch-SDK-Tests/BNCPreferenceHelperTests.m index 249fbe2de..5269501b3 100644 --- a/Branch-TestBed/Branch-SDK-Tests/BNCPreferenceHelperTests.m +++ b/Branch-TestBed/Branch-SDK-Tests/BNCPreferenceHelperTests.m @@ -199,34 +199,6 @@ - (void)testURLSkipList { XCTAssert([filterDesc isEqualToString:valueDesc]); } -- (void)testSetAPIURL_Example { - - NSString *url = @"https://www.example.com/"; - [self.prefHelper setBranchAPIURL:url] ; - - NSString *urlStored = self.prefHelper.branchAPIURL ; - XCTAssert([url isEqualToString:urlStored]); -} - -- (void)testSetAPIURL_InvalidHttp { - - NSString *url = @"Invalid://www.example.com/"; - [self.prefHelper setBranchAPIURL:url] ; - - NSString *urlStored = self.prefHelper.branchAPIURL ; - XCTAssert(![url isEqualToString:urlStored]); - XCTAssert([urlStored isEqualToString:BNC_API_URL]); -} - -- (void)testSetAPIURL_InvalidEmpty { - - [self.prefHelper setBranchAPIURL:@""] ; - - NSString *urlStored = self.prefHelper.branchAPIURL ; - XCTAssert(![urlStored isEqualToString:@""]); - XCTAssert([urlStored isEqualToString:BNC_API_URL]); -} - - (void)testSetCDNBaseURL_Example { NSString *url = @"https://www.example.com/"; diff --git a/Branch-TestBed/Branch-SDK-Tests/BNCTestCase.m b/Branch-TestBed/Branch-SDK-Tests/BNCTestCase.m index 76ab2e1d2..2afa92010 100644 --- a/Branch-TestBed/Branch-SDK-Tests/BNCTestCase.m +++ b/Branch-TestBed/Branch-SDK-Tests/BNCTestCase.m @@ -9,7 +9,6 @@ */ #import "BNCTestCase.h" -#import "BNCLog.h" #import "Branch.h" #import "BNCApplication+BNCTest.h" @@ -96,7 +95,6 @@ - (double) systemVersion { + (void) initialize { if (self != [BNCTestCase self]) return; - BNCLogSetDisplayLevel(BNCLogLevelAll); savedRandomizedBundleToken = [BNCPreferenceHelper sharedInstance].randomizedBundleToken; [Branch clearAll]; diff --git a/Branch-TestBed/Branch-SDK-Tests/BranchClassTests.m b/Branch-TestBed/Branch-SDK-Tests/BranchClassTests.m index e695e5afb..9d337a14e 100644 --- a/Branch-TestBed/Branch-SDK-Tests/BranchClassTests.m +++ b/Branch-TestBed/Branch-SDK-Tests/BranchClassTests.m @@ -13,6 +13,11 @@ #import "BNCAppGroupsData.h" #import "BNCPartnerParameters.h" +@interface BNCPreferenceHelper(Test) +// Expose internal private method to clear EEA data +- (void)writeObjectToDefaults:(NSString *)key value:(NSObject *)value; +@end + @interface BranchClassTests : XCTestCase @property (nonatomic, strong) Branch *branch; @end @@ -220,4 +225,20 @@ - (void)testGetLongURLWithParamsAndChannelAndTagsAndFeatureAndStageAndAlias { XCTAssertEqualObjects(generatedURL, expectedURL, @"URL should match the expected format"); } +- (void)testSetDMAParamsForEEA { + XCTAssertFalse([[BNCPreferenceHelper sharedInstance] eeaRegionInitialized]); + + [Branch setDMAParamsForEEA:FALSE AdPersonalizationConsent:TRUE AdUserDataUsageConsent:TRUE]; + XCTAssertTrue([[BNCPreferenceHelper sharedInstance] eeaRegionInitialized]); + XCTAssertFalse([BNCPreferenceHelper sharedInstance].eeaRegion); + XCTAssertTrue([BNCPreferenceHelper sharedInstance].adPersonalizationConsent); + XCTAssertTrue([BNCPreferenceHelper sharedInstance].adUserDataUsageConsent); + + // Manually clear values after testing + // By design, this API is meant to be set once and always set. However, in a test scenario it needs to be cleared. + [[BNCPreferenceHelper sharedInstance] writeObjectToDefaults:@"bnc_dma_eea" value:nil]; + [[BNCPreferenceHelper sharedInstance] writeObjectToDefaults:@"bnc_dma_ad_personalization" value:nil]; + [[BNCPreferenceHelper sharedInstance] writeObjectToDefaults:@"bnc_dma_ad_user_data" value:nil]; +} + @end diff --git a/Branch-TestBed/Branch-SDK-Tests/BranchLoggerTests.m b/Branch-TestBed/Branch-SDK-Tests/BranchLoggerTests.m new file mode 100644 index 000000000..0a9539f61 --- /dev/null +++ b/Branch-TestBed/Branch-SDK-Tests/BranchLoggerTests.m @@ -0,0 +1,109 @@ +// +// BranchLoggerTests.m +// Branch-SDK-Tests +// +// Created by Nipun Singh on 2/5/24. +// Copyright © 2024 Branch, Inc. All rights reserved. +// + +#import +#import "BranchLogger.h" +#import "Branch.h" + +@interface BranchLoggerTests : XCTestCase +@end + +@implementation BranchLoggerTests + +- (void)testEnableLoggingSetsCorrectDefaultLevel { + [[Branch getInstance] enableLogging]; + XCTAssertEqual([BranchLogger shared].logLevelThreshold, BranchLogLevelDebug, "Default log level should be Debug."); +} + +- (void)testLogLevelThresholdBlocksLowerLevels { + BranchLogger *logger = [BranchLogger new]; + logger.loggingEnabled = true; + logger.logLevelThreshold = BranchLogLevelDebug; + + XCTestExpectation *expectation = [self expectationWithDescription:@"Log callback expectation for message that should pass the threshold"]; + + logger.logCallback = ^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) { + if ([message isEqualToString:@"[BranchSDK][Debug][BranchLoggerTests testLogLevelThresholdBlocksLowerLevels] This message should trigger the log callback."] && logLevel >= BranchLogLevelDebug) { + [expectation fulfill]; + } else if (logLevel == BranchLogLevelVerbose) { + XCTFail(); + } + }; + + [logger logVerbose:@"This verbose message should not trigger the log callback."]; + [logger logDebug:@"This message should trigger the log callback."]; + + [self waitForExpectationsWithTimeout:1 handler:nil]; +} + +- (void)testLogCallbackExecutesWithCorrectParameters { + XCTestExpectation *expectation = [self expectationWithDescription:@"Log callback expectation"]; + NSString *expectedMessage = @"[BranchSDK][Info][BranchLoggerTests testLogCallbackExecutesWithCorrectParameters] Test message"; + BranchLogLevel expectedLevel = BranchLogLevelInfo; + + BranchLogger *logger = [BranchLogger new]; + + logger.logCallback = ^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) { + XCTAssertEqualObjects(message, expectedMessage, "Logged message does not match expected message."); + XCTAssertEqual(logLevel, expectedLevel, "Logged level does not match expected level."); + XCTAssertNil(error, "Error should be nil."); + [expectation fulfill]; + }; + + logger.loggingEnabled = YES; + logger.logLevelThreshold = BranchLogLevelInfo; + [logger logInfo:@"Test message"]; + + [self waitForExpectationsWithTimeout:1 handler:nil]; +} + +- (void)testLogLevelSpecificityFiltersLowerLevels { + BranchLogger *logger = [BranchLogger new]; + logger.loggingEnabled = YES; + logger.logLevelThreshold = BranchLogLevelWarning; + + XCTestExpectation *verboseExpectation = [self expectationWithDescription:@"Verbose log callback"]; + verboseExpectation.inverted = YES; + XCTestExpectation *errorExpectation = [self expectationWithDescription:@"Error log callback"]; + + __block NSUInteger callbackCount = 0; + logger.logCallback = ^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) { + if (logLevel == BranchLogLevelVerbose) { + [verboseExpectation fulfill]; + } else if (logLevel == BranchLogLevelError) { + [errorExpectation fulfill]; + } + callbackCount++; + }; + + [logger logVerbose:@"This should not be logged due to log level threshold."]; + [logger logError:@"This should be logged" error:nil]; + + [self waitForExpectations:@[verboseExpectation, errorExpectation] timeout:2]; + XCTAssertEqual(callbackCount, 1, "Only one log callback should have been invoked."); +} + +- (void)testErrorLoggingIncludesErrorDetails { + BranchLogger *logger = [BranchLogger new]; + logger.loggingEnabled = YES; + + XCTestExpectation *expectation = [self expectationWithDescription:@"Error log includes error details"]; + + NSError *testError = [NSError errorWithDomain:@"TestDomain" code:42 userInfo:@{NSLocalizedDescriptionKey: @"Test error description"}]; + logger.logCallback = ^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) { + if ([message containsString:@"Test error description"] && error == testError) { + [expectation fulfill]; + } + }; + + [logger logError:@"Testing error logging" error:testError]; + + [self waitForExpectationsWithTimeout:1 handler:nil]; +} + +@end diff --git a/Branch-TestBed/Branch-SDK-Tests/BranchOpenRequestTests.m b/Branch-TestBed/Branch-SDK-Tests/BranchOpenRequestTests.m index 772f8b624..234084b81 100644 --- a/Branch-TestBed/Branch-SDK-Tests/BranchOpenRequestTests.m +++ b/Branch-TestBed/Branch-SDK-Tests/BranchOpenRequestTests.m @@ -8,7 +8,6 @@ #import "BNCTestCase.h" #import "Branch.h" -#import "BNCLog.h" #import "BNCApplication+BNCTest.h" #import "BranchOpenRequest.h" #import "BranchConstants.h" diff --git a/Branch-TestBed/Branch-SDK-Tests/BranchShortUrlRequestTests.m b/Branch-TestBed/Branch-SDK-Tests/BranchShortUrlRequestTests.m deleted file mode 100644 index 5c3489459..000000000 --- a/Branch-TestBed/Branch-SDK-Tests/BranchShortUrlRequestTests.m +++ /dev/null @@ -1,252 +0,0 @@ -// -// BranchShortUrlRequestTests.m -// Branch-TestBed -// -// Created by Graham Mueller on 6/12/15. -// Copyright (c) 2015 Branch Metrics. All rights reserved. -// - -#import "BNCTestCase.h" -#import "BranchShortUrlRequest.h" -#import "BranchConstants.h" -#import "BNCPreferenceHelper.h" -#import -#import "BNCPreferenceHelper.h" -#import "BNCEncodingUtils.h" - -@interface BranchShortUrlRequestTests : BNCTestCase -@end - -@implementation BranchShortUrlRequestTests - -- (void)testRequestBody { - NSArray * const TAGS = @[]; - NSString * const ALIAS = @"foo-alias"; - BranchLinkType const LINK_TYPE = BranchLinkTypeOneTimeUse; - NSInteger const DURATION = 1; - NSString * const CHANNEL = @"foo-channel"; - NSString * const FEATURE = @"foo-feature"; - NSString * const STAGE = @"foo-stage"; - NSString * const CAMPAIGN = @"foo-campaign"; - NSDictionary * const PARAMS = @{}; - BNCLinkData * const LINK_DATA = [[BNCLinkData alloc] init]; - BNCLinkCache * const LINK_CACHE = [[BNCLinkCache alloc] init]; - - [LINK_DATA setupType:LINK_TYPE]; - [LINK_DATA setupTags:TAGS]; - [LINK_DATA setupChannel:CHANNEL]; - [LINK_DATA setupFeature:FEATURE]; - [LINK_DATA setupStage:STAGE]; - [LINK_DATA setupAlias:ALIAS]; - [LINK_DATA setupMatchDuration:DURATION]; - [LINK_DATA setupParams:PARAMS]; - - BNCPreferenceHelper *preferenceHelper = [BNCPreferenceHelper sharedInstance]; - NSMutableDictionary * const expectedParams = NSMutableDictionary.new; - expectedParams[BRANCH_REQUEST_KEY_SESSION_ID] = preferenceHelper.sessionID; - expectedParams[BRANCH_REQUEST_KEY_RANDOMIZED_BUNDLE_TOKEN] = preferenceHelper.randomizedBundleToken; - expectedParams[BRANCH_REQUEST_KEY_RANDOMIZED_DEVICE_TOKEN] = preferenceHelper.randomizedDeviceToken; - expectedParams[BRANCH_REQUEST_KEY_URL_ALIAS] = ALIAS; - expectedParams[BRANCH_REQUEST_KEY_URL_CHANNEL] = CHANNEL; - expectedParams[BRANCH_REQUEST_KEY_URL_DATA] = PARAMS; - expectedParams[BRANCH_REQUEST_KEY_URL_DURATION] = @(DURATION); - expectedParams[BRANCH_REQUEST_KEY_URL_FEATURE] = FEATURE; - expectedParams[BRANCH_REQUEST_KEY_URL_LINK_TYPE] = @(LINK_TYPE); - expectedParams[BRANCH_REQUEST_KEY_URL_SOURCE] = @"ios"; - expectedParams[BRANCH_REQUEST_KEY_URL_STAGE] = STAGE; - expectedParams[BRANCH_REQUEST_KEY_URL_TAGS] = TAGS; - - BranchShortUrlRequest *request = - [[BranchShortUrlRequest alloc] - initWithTags:TAGS - alias:ALIAS - type:LINK_TYPE - matchDuration:DURATION - channel:CHANNEL - feature:FEATURE - stage:STAGE - campaign:CAMPAIGN - params:PARAMS - linkData:LINK_DATA - linkCache:LINK_CACHE - callback:NULL]; - - id serverInterfaceMock = OCMClassMock([BNCServerInterface class]); - [[serverInterfaceMock expect] - postRequest:expectedParams - url:[self stringMatchingPattern:BRANCH_REQUEST_ENDPOINT_GET_SHORT_URL] - key:[OCMArg any] - callback:[OCMArg any]]; - - [request makeRequest:serverInterfaceMock key:nil callback:NULL]; - [serverInterfaceMock verify]; -} - -- (void)testRequestBodyWhenOptionalValuesArentProvided { - BranchLinkType const LINK_TYPE = BranchLinkTypeOneTimeUse; - BNCLinkData * const LINK_DATA = [[BNCLinkData alloc] init]; - BNCLinkCache * const LINK_CACHE = [[BNCLinkCache alloc] init]; - - [LINK_DATA setupType:LINK_TYPE]; - - BNCPreferenceHelper *preferenceHelper = [BNCPreferenceHelper sharedInstance]; - NSMutableDictionary * const expectedParams = NSMutableDictionary.new; - expectedParams[BRANCH_REQUEST_KEY_SESSION_ID] = preferenceHelper.sessionID; - expectedParams[BRANCH_REQUEST_KEY_RANDOMIZED_BUNDLE_TOKEN] = preferenceHelper.randomizedBundleToken; - expectedParams[BRANCH_REQUEST_KEY_RANDOMIZED_DEVICE_TOKEN] = preferenceHelper.randomizedDeviceToken; - expectedParams[BRANCH_REQUEST_KEY_URL_SOURCE] = @"ios"; - expectedParams[BRANCH_REQUEST_KEY_URL_LINK_TYPE] = @(LINK_TYPE); - - BranchShortUrlRequest *request = - [[BranchShortUrlRequest alloc] - initWithTags:nil - alias:nil - type:LINK_TYPE - matchDuration:0 - channel:nil - feature:nil - stage:nil - campaign:nil - params:nil - linkData:LINK_DATA - linkCache:LINK_CACHE - callback:NULL]; - - id serverInterfaceMock = OCMClassMock([BNCServerInterface class]); - [[serverInterfaceMock expect] - postRequest:expectedParams - url:[OCMArg any] - key:[OCMArg any] - callback:[OCMArg any]]; - - [request makeRequest:serverInterfaceMock key:nil callback:NULL]; - - [serverInterfaceMock verify]; -} - -- (void)testBasicSuccess { - NSString * URL = @"http://foo"; - NSDictionary * const REFERRAL_RESPONSE_DATA = @{ BRANCH_RESPONSE_KEY_URL: URL }; - BNCServerResponse *response = [[BNCServerResponse alloc] init]; - response.data = REFERRAL_RESPONSE_DATA; - - XCTestExpectation *requestExpecation = [self expectationWithDescription:@"Get Referral Code Request Expectation"]; - BranchShortUrlRequest *request = - [[BranchShortUrlRequest alloc] - initWithTags:nil - alias:nil - type:BranchLinkTypeOneTimeUse - matchDuration:1 - channel:nil - feature:nil - stage:nil - campaign:nil - params:nil - linkData:nil - linkCache:nil - callback:^(NSString *url, NSError *error) { - XCTAssertEqualObjects(url, URL); - XCTAssertNil(error); - [self safelyFulfillExpectation:requestExpecation]; - }]; - - [request processResponse:response error:nil]; - - [self awaitExpectations]; -} - -- (void)testFailureWithUserUrlAvailable { - NSError * RESPONSE_ERROR = [NSError errorWithDomain:@"foo" code:1 userInfo:nil]; - NSString * USER_URL = @"http://foo"; - - NSString * TAG1 = @"foo-tag"; - NSString * TAG2 = @"bar-tag"; - NSArray * const TAGS = @[ TAG1, TAG2 ]; - NSString * const ALIAS = @"foo-alias"; - BranchLinkType const LINK_TYPE = BranchLinkTypeOneTimeUse; - NSInteger const DURATION = 1; - NSString * const CHANNEL = @"foo-channel"; - NSString * const FEATURE = @"foo-feature"; - NSString * const STAGE = @"foo-stage"; - NSString * const CAMPAIGN = @"foo-campaign"; - NSDictionary * const PARAMS = @{ @"foo-param": @"bar-value" }; - NSData * const PARAMS_DATA = [BNCEncodingUtils encodeDictionaryToJsonData:PARAMS]; - NSString * const ENCODED_PARAMS = [BNCEncodingUtils base64EncodeData:PARAMS_DATA]; - - NSString * EXPECTED_URL = [NSString stringWithFormat: - @"%@?tags=%@&tags=%@&alias=%@&channel=%@&feature=%@&stage=%@&type=%ld&duration=%ld&source=ios&data=%@", - USER_URL, TAG1, TAG2, ALIAS, CHANNEL, FEATURE, STAGE, (long)LINK_TYPE, (long)DURATION, ENCODED_PARAMS]; - - BNCPreferenceHelper *preferenceHelper = [BNCPreferenceHelper sharedInstance]; - preferenceHelper.userUrl = USER_URL; - - XCTestExpectation *requestExpecation = [self expectationWithDescription:@"Get Referral Code Request Expectation"]; - BranchShortUrlRequest *request = - [[BranchShortUrlRequest alloc] - initWithTags:TAGS - alias:ALIAS - type:LINK_TYPE - matchDuration:DURATION - channel:CHANNEL - feature:FEATURE - stage:STAGE - campaign:CAMPAIGN - params:PARAMS - linkData:nil - linkCache:nil - callback:^(NSString *url, NSError *error) { - XCTAssertEqualObjects(url, EXPECTED_URL); - XCTAssertNotNil(error); - [self safelyFulfillExpectation:requestExpecation]; - }]; - - [request processResponse:nil error:RESPONSE_ERROR]; - - [self awaitExpectations]; -} - -- (void)testFailureWithoutUserUrlAvailable { - NSError * RESPONSE_ERROR = [NSError errorWithDomain:@"foo" code:1 userInfo:nil]; - - NSString * TAG1 = @"foo-tag"; - NSString * TAG2 = @"bar-tag"; - NSArray * const TAGS = @[ TAG1, TAG2 ]; - NSString * const ALIAS = @"foo-alias"; - BranchLinkType const LINK_TYPE = BranchLinkTypeOneTimeUse; - NSInteger const DURATION = 1; - NSString * const CHANNEL = @"foo-channel"; - NSString * const FEATURE = @"foo-feature"; - NSString * const CAMPAIGN = @"foo-campaign"; - NSString * const STAGE = @"foo-stage"; - NSDictionary * const PARAMS = @{ @"foo-param": @"bar-value" }; - - BNCPreferenceHelper *preferenceHelper = [BNCPreferenceHelper sharedInstance]; - preferenceHelper.userUrl = nil; - - XCTestExpectation *requestExpecation = - [self expectationWithDescription:@"testFailureWithoutUserUrlAvailable Expectation"]; - BranchShortUrlRequest *request = - [[BranchShortUrlRequest alloc] - initWithTags:TAGS - alias:ALIAS - type:LINK_TYPE - matchDuration:DURATION - channel:CHANNEL - feature:FEATURE - stage:STAGE - campaign:CAMPAIGN - params:PARAMS - linkData:nil - linkCache:nil - callback:^(NSString *url, NSError *error) { - XCTAssertTrue((Branch.branchKeyIsSet && url != nil) || (!Branch.branchKeyIsSet && url == nil)); - XCTAssertNotNil(error); - [self safelyFulfillExpectation:requestExpecation]; - }]; - - [request processResponse:nil error:RESPONSE_ERROR]; - - [self awaitExpectations]; -} - -@end diff --git a/Branch-TestBed/Branch-SDK-Tests/BranchShortUrlSyncRequestTests.m b/Branch-TestBed/Branch-SDK-Tests/BranchShortUrlSyncRequestTests.m deleted file mode 100644 index 598294277..000000000 --- a/Branch-TestBed/Branch-SDK-Tests/BranchShortUrlSyncRequestTests.m +++ /dev/null @@ -1,233 +0,0 @@ -// -// BranchShortUrlSyncRequestTests.m -// Branch-TestBed -// -// Created by Graham Mueller on 6/12/15. -// Copyright (c) 2015 Branch Metrics. All rights reserved. -// -#import "BNCTestCase.h" -#import "BranchShortUrlSyncRequest.h" -#import "BranchConstants.h" -#import "BNCPreferenceHelper.h" -#import -#import "BNCPreferenceHelper.h" -#import "BNCEncodingUtils.h" - -@interface BranchShortUrlSyncRequestTests : BNCTestCase - -@end - -@implementation BranchShortUrlSyncRequestTests - -- (void)testRequestBody { - NSArray * const TAGS = @[]; - NSString * const ALIAS = @"foo-alias"; - BranchLinkType const LINK_TYPE = BranchLinkTypeOneTimeUse; - NSInteger const DURATION = 1; - NSString * const CHANNEL = @"foo-channel"; - NSString * const FEATURE = @"foo-feature"; - NSString * const STAGE = @"foo-stage"; - NSString * const CAMPAIGN = @"foo-campaign"; - NSDictionary * const PARAMS = @{}; - BNCLinkData * const LINK_DATA = [[BNCLinkData alloc] init]; - BNCLinkCache * const LINK_CACHE = [[BNCLinkCache alloc] init]; - - [LINK_DATA setupType:LINK_TYPE]; - [LINK_DATA setupTags:TAGS]; - [LINK_DATA setupChannel:CHANNEL]; - [LINK_DATA setupFeature:FEATURE]; - [LINK_DATA setupStage:STAGE]; - [LINK_DATA setupAlias:ALIAS]; - [LINK_DATA setupMatchDuration:DURATION]; - [LINK_DATA setupParams:PARAMS]; - - BNCPreferenceHelper *preferenceHelper = [BNCPreferenceHelper sharedInstance]; - NSMutableDictionary * const expectedParams = NSMutableDictionary.new; - expectedParams[BRANCH_REQUEST_KEY_SESSION_ID] = preferenceHelper.sessionID; - expectedParams[BRANCH_REQUEST_KEY_RANDOMIZED_BUNDLE_TOKEN] = preferenceHelper.randomizedBundleToken; - expectedParams[BRANCH_REQUEST_KEY_RANDOMIZED_DEVICE_TOKEN] = preferenceHelper.randomizedDeviceToken; - expectedParams[BRANCH_REQUEST_KEY_URL_ALIAS] = ALIAS; - expectedParams[BRANCH_REQUEST_KEY_URL_CHANNEL] = CHANNEL; - expectedParams[BRANCH_REQUEST_KEY_URL_DATA] = PARAMS; - expectedParams[BRANCH_REQUEST_KEY_URL_DURATION] = @(DURATION); - expectedParams[BRANCH_REQUEST_KEY_URL_FEATURE] = FEATURE; - expectedParams[BRANCH_REQUEST_KEY_URL_LINK_TYPE] = @(LINK_TYPE); - expectedParams[BRANCH_REQUEST_KEY_URL_SOURCE] = @"ios"; - expectedParams[BRANCH_REQUEST_KEY_URL_STAGE] = STAGE; - expectedParams[BRANCH_REQUEST_KEY_URL_TAGS] = TAGS; - - BranchShortUrlSyncRequest *request = - [[BranchShortUrlSyncRequest alloc] - initWithTags:TAGS - alias:ALIAS - type:LINK_TYPE - matchDuration:DURATION - channel:CHANNEL - feature:FEATURE - stage:STAGE - campaign:CAMPAIGN - params:PARAMS - linkData:LINK_DATA - linkCache:LINK_CACHE]; - - id serverInterfaceMock = OCMClassMock([BNCServerInterface class]); - [[serverInterfaceMock expect] - postRequestSynchronous:expectedParams - url:[self stringMatchingPattern:BRANCH_REQUEST_ENDPOINT_GET_SHORT_URL] - key:[OCMArg any]]; - - [request makeRequest:serverInterfaceMock key:nil]; - - [serverInterfaceMock verify]; -} - -- (void)testRequestBodyWhenOptionalValuesArentProvided { - BranchLinkType const LINK_TYPE = BranchLinkTypeOneTimeUse; - BNCLinkData * const LINK_DATA = [[BNCLinkData alloc] init]; - BNCLinkCache * const LINK_CACHE = [[BNCLinkCache alloc] init]; - - [LINK_DATA setupType:LINK_TYPE]; - - BNCPreferenceHelper *preferenceHelper = [BNCPreferenceHelper sharedInstance]; - NSMutableDictionary * const expectedParams = NSMutableDictionary.new; - expectedParams[BRANCH_REQUEST_KEY_SESSION_ID] = preferenceHelper.sessionID; - expectedParams[BRANCH_REQUEST_KEY_RANDOMIZED_BUNDLE_TOKEN] = preferenceHelper.randomizedBundleToken; - expectedParams[BRANCH_REQUEST_KEY_RANDOMIZED_DEVICE_TOKEN] = preferenceHelper.randomizedDeviceToken; - expectedParams[BRANCH_REQUEST_KEY_URL_SOURCE] = @"ios"; - expectedParams[BRANCH_REQUEST_KEY_URL_LINK_TYPE] = @(LINK_TYPE); - - BranchShortUrlSyncRequest *request = - [[BranchShortUrlSyncRequest alloc] - initWithTags:nil - alias:nil - type:LINK_TYPE - matchDuration:0 - channel:nil - feature:nil - stage:nil - campaign:nil - params:nil - linkData:LINK_DATA - linkCache:LINK_CACHE]; - id serverInterfaceMock = OCMClassMock([BNCServerInterface class]); - [[serverInterfaceMock expect] - postRequestSynchronous:expectedParams - url:[OCMArg any] - key:[OCMArg any]]; - - [request makeRequest:serverInterfaceMock key:nil]; - - [serverInterfaceMock verify]; -} - -- (void)testBasicSuccess { - NSString * URL = @"http://foo"; - NSDictionary * const REFERRAL_RESPONSE_DATA = @{ BRANCH_RESPONSE_KEY_URL: URL }; - BNCServerResponse *response = [[BNCServerResponse alloc] init]; - response.data = REFERRAL_RESPONSE_DATA; - response.statusCode = @200; - - BranchShortUrlSyncRequest *request = - [[BranchShortUrlSyncRequest alloc] - initWithTags:nil - alias:nil - type:BranchLinkTypeOneTimeUse - matchDuration:1 - channel:nil - feature:nil - stage:nil - campaign:nil - params:nil - linkData:nil - linkCache:nil]; - NSString *url = [request processResponse:response]; - - XCTAssertEqualObjects(url, URL); -} - -- (void)testFailureWithUserUrlAvailable { - BNCServerResponse *response = [[BNCServerResponse alloc] init]; - response.statusCode = @400; - NSString * USER_URL = @"http://foo"; - - NSString * TAG1 = @"foo-tag"; - NSString * TAG2 = @"bar-tag"; - NSArray * const TAGS = @[ TAG1, TAG2 ]; - NSString * const ALIAS = @"foo-alias"; - BranchLinkType const LINK_TYPE = BranchLinkTypeOneTimeUse; - NSInteger const DURATION = 1; - NSString * const CHANNEL = @"foo-channel"; - NSString * const FEATURE = @"foo-feature"; - NSString * const STAGE = @"foo-stage"; - NSString * const CAMPAIGN = @"foo-campaign"; - NSDictionary * const PARAMS = @{ @"foo-param": @"bar-value" }; - NSData * const PARAMS_DATA = [BNCEncodingUtils encodeDictionaryToJsonData:PARAMS]; - NSString * const ENCODED_PARAMS = [BNCEncodingUtils base64EncodeData:PARAMS_DATA]; - NSString * const URL_ENCODED_PARAMS = [BNCEncodingUtils urlEncodedString:ENCODED_PARAMS]; - - NSString * EXPECTED_URL = - [NSString stringWithFormat: - @"%@?tags=%@&tags=%@&alias=%@&channel=%@&feature=%@&stage=%@&type=%ld" - "&duration=%ld&source=ios&data=%@", - USER_URL, TAG1, TAG2, ALIAS, CHANNEL, FEATURE, STAGE, - (long)LINK_TYPE, (long)DURATION, URL_ENCODED_PARAMS]; - - BNCPreferenceHelper *preferenceHelper = [BNCPreferenceHelper sharedInstance]; - preferenceHelper.userUrl = USER_URL; - - BranchShortUrlSyncRequest *request = - [[BranchShortUrlSyncRequest alloc] - initWithTags:TAGS - alias:ALIAS - type:LINK_TYPE - matchDuration:DURATION - channel:CHANNEL - feature:FEATURE - stage:STAGE - campaign:CAMPAIGN - params:PARAMS - linkData:nil - linkCache:nil]; - NSString *url = [request processResponse:response]; - - XCTAssertEqualObjects(url, EXPECTED_URL); -} - -- (void)testFailureWithoutUserUrlAvailable { - BNCServerResponse *response = [[BNCServerResponse alloc] init]; - response.statusCode = @400; - - NSString * TAG1 = @"foo-tag"; - NSString * TAG2 = @"bar-tag"; - NSArray * const TAGS = @[ TAG1, TAG2 ]; - NSString * const ALIAS = @"foo-alias"; - BranchLinkType const LINK_TYPE = BranchLinkTypeOneTimeUse; - NSInteger const DURATION = 1; - NSString * const CHANNEL = @"foo-channel"; - NSString * const FEATURE = @"foo-feature"; - NSString * const STAGE = @"foo-stage"; - NSString * const CAMPAIGN = @"foo-campaign"; - NSDictionary * const PARAMS = @{ @"foo-param": @"bar-value" }; - - BNCPreferenceHelper *preferenceHelper = [BNCPreferenceHelper sharedInstance]; - preferenceHelper.userUrl = nil; - - BranchShortUrlSyncRequest *request = - [[BranchShortUrlSyncRequest alloc] - initWithTags:TAGS - alias:ALIAS - type:LINK_TYPE - matchDuration:DURATION - channel:CHANNEL - feature:FEATURE - stage:STAGE - campaign:CAMPAIGN - params:PARAMS - linkData:nil - linkCache:nil]; - NSString *url = [request processResponse:response]; - - XCTAssertNil(url); -} - -@end diff --git a/Branch-TestBed/Branch-TestBed.xcodeproj/project.pbxproj b/Branch-TestBed/Branch-TestBed.xcodeproj/project.pbxproj index ff1e1681c..434d42e9f 100644 --- a/Branch-TestBed/Branch-TestBed.xcodeproj/project.pbxproj +++ b/Branch-TestBed/Branch-TestBed.xcodeproj/project.pbxproj @@ -31,7 +31,6 @@ 4D1683B72098C902008819E3 /* BNCTestCase.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D16838D2098C901008819E3 /* BNCTestCase.m */; }; 4D1683B82098C902008819E3 /* BNCEncodingUtilsTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D16838E2098C901008819E3 /* BNCEncodingUtilsTests.m */; }; 4D1683B92098C902008819E3 /* BNCSystemObserverTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D16838F2098C901008819E3 /* BNCSystemObserverTests.m */; }; - 4D1683BA2098C902008819E3 /* BNCLogTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D1683902098C901008819E3 /* BNCLogTests.m */; }; 4D1683C02098C902008819E3 /* BranchUniversalObjectTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D1683962098C901008819E3 /* BranchUniversalObjectTests.m */; }; 4D1683C12098C902008819E3 /* BNCApplicationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D1683972098C901008819E3 /* BNCApplicationTests.m */; }; 4D1683C62098C902008819E3 /* BranchEvent.Test.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D16839C2098C901008819E3 /* BranchEvent.Test.m */; }; @@ -53,6 +52,9 @@ 5F42763325DB3694005B9BBC /* AdServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5F42763225DB3694005B9BBC /* AdServices.framework */; }; 5F437E38237DE1320052064B /* CoreTelephony.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5F437E37237DE1320052064B /* CoreTelephony.framework */; settings = {ATTRIBUTES = (Required, ); }; }; 5F437E40237E1A560052064B /* BNCDeviceSystemTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F437E3F237E1A560052064B /* BNCDeviceSystemTests.m */; }; + 5F5FDA102B7DE20800F14A43 /* BranchLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F5FDA0F2B7DE20800F14A43 /* BranchLogger.m */; }; + 5F5FDA122B7DE22A00F14A43 /* BranchLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 5F5FDA112B7DE22A00F14A43 /* BranchLogger.h */; }; + 5F5FDA142B7DE27D00F14A43 /* BranchLoggerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F5FDA132B7DE27D00F14A43 /* BranchLoggerTests.m */; }; 5F644BB92B7AA811000DCD78 /* NSError+Branch.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F644B262B7AA810000DCD78 /* NSError+Branch.m */; }; 5F644BBA2B7AA811000DCD78 /* BNCUserAgentCollector.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F644B272B7AA810000DCD78 /* BNCUserAgentCollector.m */; }; 5F644BBB2B7AA811000DCD78 /* BNCEncodingUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F644B282B7AA810000DCD78 /* BNCEncodingUtils.m */; }; @@ -321,7 +323,6 @@ 4D16838D2098C901008819E3 /* BNCTestCase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BNCTestCase.m; sourceTree = ""; }; 4D16838E2098C901008819E3 /* BNCEncodingUtilsTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BNCEncodingUtilsTests.m; sourceTree = ""; }; 4D16838F2098C901008819E3 /* BNCSystemObserverTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BNCSystemObserverTests.m; sourceTree = ""; }; - 4D1683902098C901008819E3 /* BNCLogTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BNCLogTests.m; sourceTree = ""; }; 4D1683952098C901008819E3 /* BranchEvent.Test.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BranchEvent.Test.swift; sourceTree = ""; }; 4D1683962098C901008819E3 /* BranchUniversalObjectTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BranchUniversalObjectTests.m; sourceTree = ""; }; 4D1683972098C901008819E3 /* BNCApplicationTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BNCApplicationTests.m; sourceTree = ""; }; @@ -353,6 +354,9 @@ 5F42763225DB3694005B9BBC /* AdServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AdServices.framework; path = System/Library/Frameworks/AdServices.framework; sourceTree = SDKROOT; }; 5F437E37237DE1320052064B /* CoreTelephony.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreTelephony.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreTelephony.framework; sourceTree = DEVELOPER_DIR; }; 5F437E3F237E1A560052064B /* BNCDeviceSystemTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = BNCDeviceSystemTests.m; sourceTree = ""; }; + 5F5FDA0F2B7DE20800F14A43 /* BranchLogger.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BranchLogger.m; sourceTree = ""; }; + 5F5FDA112B7DE22A00F14A43 /* BranchLogger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BranchLogger.h; sourceTree = ""; }; + 5F5FDA132B7DE27D00F14A43 /* BranchLoggerTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BranchLoggerTests.m; sourceTree = ""; }; 5F644B262B7AA810000DCD78 /* NSError+Branch.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSError+Branch.m"; sourceTree = ""; }; 5F644B272B7AA810000DCD78 /* BNCUserAgentCollector.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BNCUserAgentCollector.m; sourceTree = ""; }; 5F644B282B7AA810000DCD78 /* BNCEncodingUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BNCEncodingUtils.m; sourceTree = ""; }; @@ -643,7 +647,6 @@ 5F73FC8023314697000EBD32 /* BNCJSONUtilityTests.m */, 5F8BB66D278771890055D2DC /* BNCKeyChainTests.m */, 4D1683842098C901008819E3 /* BNCLinkDataTests.m */, - 4D1683902098C901008819E3 /* BNCLogTests.m */, 5FA9112E29BC662000F3D35C /* BNCNetworkInterfaceTests.m */, 5FDF91582581CDF4009BE5A3 /* BNCPartnerParametersTests.m */, 5FD1786D26DEE49C009696E3 /* BNCPasteboardTests.m */, @@ -670,6 +673,7 @@ 4D1683952098C901008819E3 /* BranchEvent.Test.swift */, 4D1683822098C901008819E3 /* BranchInstallRequestTests.m */, 5F909B712332BEF600A774D2 /* BranchLastAttributedTouchDataTests.m */, + 5F5FDA132B7DE27D00F14A43 /* BranchLoggerTests.m */, 4D16837F2098C901008819E3 /* BranchOpenRequestTests.m */, C10F393927A0872800BF5D36 /* BranchPluginSupportTests.m */, C12320B42808DB90007771C0 /* BranchQRCodeTests.m */, @@ -760,6 +764,7 @@ 5F644BA42B7AA811000DCD78 /* BranchLastAttributedTouchData.m */, 5F644B4C2B7AA810000DCD78 /* BranchLATDRequest.m */, 5F644BA92B7AA811000DCD78 /* BranchLinkProperties.m */, + 5F5FDA0F2B7DE20800F14A43 /* BranchLogger.m */, 5F644BB42B7AA811000DCD78 /* BranchOpenRequest.m */, 5F644B2A2B7AA810000DCD78 /* BranchPasteControl.m */, 5F644B352B7AA810000DCD78 /* BranchPluginSupport.m */, @@ -773,9 +778,9 @@ 5F644B262B7AA810000DCD78 /* NSError+Branch.m */, 5F644B2D2B7AA810000DCD78 /* NSMutableDictionary+Branch.m */, 5F644B362B7AA810000DCD78 /* NSString+Branch.m */, + 5F644BAF2B7AA811000DCD78 /* UIViewController+Branch.m */, 5F644B6E2B7AA810000DCD78 /* Private */, 5F644B522B7AA810000DCD78 /* Public */, - 5F644BAF2B7AA811000DCD78 /* UIViewController+Branch.m */, ); name = BranchSDK; path = ../Sources/BranchSDK; @@ -804,6 +809,7 @@ 5F644B622B7AA810000DCD78 /* BranchEvent.h */, 5F644B5B2B7AA810000DCD78 /* BranchLastAttributedTouchData.h */, 5F644B582B7AA810000DCD78 /* BranchLinkProperties.h */, + 5F5FDA112B7DE22A00F14A43 /* BranchLogger.h */, 5F644B652B7AA810000DCD78 /* BranchPasteControl.h */, 5F644B692B7AA810000DCD78 /* BranchPluginSupport.h */, 5F644B552B7AA810000DCD78 /* BranchQRCode.h */, @@ -1017,6 +1023,7 @@ 5F644C1C2B7AA811000DCD78 /* NSString+Branch.h in Headers */, 5F644C132B7AA811000DCD78 /* NSMutableDictionary+Branch.h in Headers */, 5F644C122B7AA811000DCD78 /* BNCApplication.h in Headers */, + 5F5FDA122B7DE22A00F14A43 /* BranchLogger.h in Headers */, 5F644C102B7AA811000DCD78 /* BranchShortUrlRequest.h in Headers */, 5F644C232B7AA811000DCD78 /* BranchContentDiscoverer.h in Headers */, 5F644C032B7AA811000DCD78 /* BranchContentPathProperties.h in Headers */, @@ -1295,6 +1302,7 @@ 5F644C482B7AA811000DCD78 /* BNCCallbackMap.m in Sources */, 5F644BBE2B7AA811000DCD78 /* BNCApplication.m in Sources */, 5F644C302B7AA811000DCD78 /* BranchDelegate.m in Sources */, + 5F5FDA102B7DE20800F14A43 /* BranchLogger.m in Sources */, 5F644C3D2B7AA811000DCD78 /* BNCSpotlightService.m in Sources */, 5F644BC02B7AA811000DCD78 /* NSMutableDictionary+Branch.m in Sources */, 5F644BBC2B7AA811000DCD78 /* BranchUniversalObject.m in Sources */, @@ -1414,12 +1422,12 @@ 4D1683B92098C902008819E3 /* BNCSystemObserverTests.m in Sources */, 4D1683CA2098C902008819E3 /* BNCPreferenceHelperTests.m in Sources */, 4AB16368239E3A2700D42931 /* DispatchToIsolationQueueTests.m in Sources */, + 5F5FDA142B7DE27D00F14A43 /* BranchLoggerTests.m in Sources */, 5F8BB66E278771890055D2DC /* BNCKeyChainTests.m in Sources */, C1CC888229BAAFC000BDD2B5 /* BNCReferringURLUtilityTests.m in Sources */, 5FE694382405FA2700E3AEE2 /* BNCCallbackMapTests.m in Sources */, 5FDB04F424E6156800F2F267 /* BNCSKAdNetworkTests.m in Sources */, 5FB6CC13264F0C7C0020E478 /* BNCServerRequestQueueTests.m in Sources */, - 4D1683BA2098C902008819E3 /* BNCLogTests.m in Sources */, 4D1683AE2098C902008819E3 /* BNCLinkDataTests.m in Sources */, 4D7881FF209CF2D4002B750F /* BNCApplication+BNCTest.m in Sources */, C15CC9E02ABCF8C8003CC339 /* BranchActivityItemTests.m in Sources */, diff --git a/Branch-TestBed/Branch-TestBed/AppDelegate.m b/Branch-TestBed/Branch-TestBed/AppDelegate.m index 09925169f..a8c160cea 100644 --- a/Branch-TestBed/Branch-TestBed/AppDelegate.m +++ b/Branch-TestBed/Branch-TestBed/AppDelegate.m @@ -12,10 +12,9 @@ #import "ViewController.h" #import "Branch.h" #import "BNCEncodingUtils.h" -#import "BNCLog.h" AppDelegate* appDelegate = nil; -void APPLogHookFunction(NSDate*_Nonnull timestamp, BNCLogLevel level, NSString*_Nullable message); +void APPLogHookFunction(NSDate*_Nonnull timestamp, BranchLogLevel level, NSString*_Nullable message); @implementation AppDelegate @@ -23,8 +22,6 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { appDelegate = self; - BNCLogSetOutputFunction(APPLogHookFunction); - BNCLogSetDisplayLevel(BNCLogLevelAll); /* Set Branch.useTestBranchKey = YES; to have Branch use the test key that's in the app's @@ -34,14 +31,20 @@ - (BOOL)application:(UIApplication *)application // Branch.useTestBranchKey = YES; // Make sure to comment this line out for production apps!!! Branch *branch = [Branch getInstance]; - + + // Change the Branch base API URL + //[Branch setAPIUrl:@"https://api3.branch.io"]; + // test pre init support //[self testDispatchToIsolationQueue:branch] - - // Comment out (for match guarantee testing) / or un-comment to toggle debugging: - // Note: Unit tests will fail if 'setDebug' is set. - // [branch setDebug]; - [branch enableLogging]; + [branch enableLoggingAtLevel:BranchLogLevelVerbose withCallback:^(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error) { + // Handle the log message and error here. For example, printing to the console: + if (error) { + NSLog(@"[BranchLog] Level: %lu, Message: %@, Error: %@", (unsigned long)logLevel, message, error.localizedDescription); + } else { + NSLog(@"[BranchLog] Level: %lu, Message: %@", (unsigned long)logLevel, message); + } + }]; // Comment out in production. Un-comment to test your Branch SDK Integration: //[branch validateSDKIntegration]; @@ -209,7 +212,7 @@ -(void)application:(UIApplication *)application */ // hook Function for SDK - Its for taking control of Logging messages. -void APPLogHookFunction(NSDate*_Nonnull timestamp, BNCLogLevel level, NSString*_Nullable message) { +void APPLogHookFunction(NSDate*_Nonnull timestamp, BranchLogLevel level, NSString*_Nullable message) { [appDelegate processLogMessage:message]; } diff --git a/Branch-TestBed/Branch-TestBed/Branch-TestBed-Info.plist b/Branch-TestBed/Branch-TestBed/Branch-TestBed-Info.plist index ee2bcc7d9..e7f466f5c 100644 --- a/Branch-TestBed/Branch-TestBed/Branch-TestBed-Info.plist +++ b/Branch-TestBed/Branch-TestBed/Branch-TestBed-Info.plist @@ -4,8 +4,6 @@ AppIdentifierPrefix $(AppIdentifierPrefix) - BranchLogLevel - BNCLogLevelAll CFBundleDevelopmentRegion en CFBundleDisplayName diff --git a/BranchSDK.xcodeproj/project.pbxproj b/BranchSDK.xcodeproj/project.pbxproj index bf896017d..e439b09b9 100644 --- a/BranchSDK.xcodeproj/project.pbxproj +++ b/BranchSDK.xcodeproj/project.pbxproj @@ -63,6 +63,12 @@ 5F2211892894A9C100C5B190 /* TestHostTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F2211882894A9C100C5B190 /* TestHostTests.swift */; }; 5F2211932894A9C100C5B190 /* TestHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F2211922894A9C100C5B190 /* TestHostUITests.swift */; }; 5F2211952894A9C100C5B190 /* TestHostUITestsLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F2211942894A9C100C5B190 /* TestHostUITestsLaunchTests.swift */; }; + 5F5FDA162B7DE2FE00F14A43 /* BranchLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F5FDA152B7DE2FE00F14A43 /* BranchLogger.m */; }; + 5F5FDA172B7DE2FE00F14A43 /* BranchLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F5FDA152B7DE2FE00F14A43 /* BranchLogger.m */; }; + 5F5FDA182B7DE2FE00F14A43 /* BranchLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F5FDA152B7DE2FE00F14A43 /* BranchLogger.m */; }; + 5F5FDA1A2B7DE31E00F14A43 /* BranchLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 5F5FDA192B7DE31E00F14A43 /* BranchLogger.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5F5FDA1B2B7DE31E00F14A43 /* BranchLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 5F5FDA192B7DE31E00F14A43 /* BranchLogger.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5F5FDA1C2B7DE31E00F14A43 /* BranchLogger.h in Headers */ = {isa = PBXBuildFile; fileRef = 5F5FDA192B7DE31E00F14A43 /* BranchLogger.h */; settings = {ATTRIBUTES = (Public, ); }; }; 5F6DD2482894AEBD00AE9FB0 /* BranchSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5F22101D2894A0DB00C5B190 /* BranchSDK.framework */; }; 5F6DD24C2894AF5E00AE9FB0 /* NSURLSession+Branch.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F6DD24A2894AF5E00AE9FB0 /* NSURLSession+Branch.m */; }; 5F73EBFA28ECE65400608601 /* BranchSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5F73EBF428ECE65400608601 /* BranchSDK.framework */; }; @@ -544,6 +550,8 @@ 5F22118E2894A9C100C5B190 /* TestHostUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = TestHostUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5F2211922894A9C100C5B190 /* TestHostUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHostUITests.swift; sourceTree = ""; }; 5F2211942894A9C100C5B190 /* TestHostUITestsLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHostUITestsLaunchTests.swift; sourceTree = ""; }; + 5F5FDA152B7DE2FE00F14A43 /* BranchLogger.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BranchLogger.m; sourceTree = ""; }; + 5F5FDA192B7DE31E00F14A43 /* BranchLogger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BranchLogger.h; sourceTree = ""; }; 5F6DD2492894AF5E00AE9FB0 /* TestHost-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "TestHost-Bridging-Header.h"; sourceTree = ""; }; 5F6DD24A2894AF5E00AE9FB0 /* NSURLSession+Branch.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSURLSession+Branch.m"; sourceTree = ""; }; 5F6DD24B2894AF5E00AE9FB0 /* NSURLSession+Branch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSURLSession+Branch.h"; sourceTree = ""; }; @@ -866,6 +874,7 @@ 5FCDD3EA2B7AC6A100EAF29F /* BranchLastAttributedTouchData.m */, 5FCDD3922B7AC6A100EAF29F /* BranchLATDRequest.m */, 5FCDD3EF2B7AC6A100EAF29F /* BranchLinkProperties.m */, + 5F5FDA152B7DE2FE00F14A43 /* BranchLogger.m */, 5FCDD3FA2B7AC6A100EAF29F /* BranchOpenRequest.m */, 5FCDD3702B7AC6A100EAF29F /* BranchPasteControl.m */, 5FCDD37B2B7AC6A100EAF29F /* BranchPluginSupport.m */, @@ -910,6 +919,7 @@ 5FCDD3A82B7AC6A100EAF29F /* BranchEvent.h */, 5FCDD3A12B7AC6A100EAF29F /* BranchLastAttributedTouchData.h */, 5FCDD39E2B7AC6A100EAF29F /* BranchLinkProperties.h */, + 5F5FDA192B7DE31E00F14A43 /* BranchLogger.h */, 5FCDD3AB2B7AC6A100EAF29F /* BranchPasteControl.h */, 5FCDD3AF2B7AC6A100EAF29F /* BranchPluginSupport.h */, 5FCDD39B2B7AC6A100EAF29F /* BranchQRCode.h */, @@ -1032,6 +1042,7 @@ 5FCDD5072B7AC6A300EAF29F /* BNCUrlQueryParameter.h in Headers */, 5FCDD5462B7AC6A300EAF29F /* BNCConfig.h in Headers */, 5FCDD4E62B7AC6A200EAF29F /* UIViewController+Branch.h in Headers */, + 5F5FDA1A2B7DE31E00F14A43 /* BranchLogger.h in Headers */, 5FCDD5492B7AC6A300EAF29F /* BranchConstants.h in Headers */, 5FCDD5402B7AC6A300EAF29F /* BranchSpotlightUrlRequest.h in Headers */, 5FCDD5552B7AC6A300EAF29F /* BNCCrashlyticsWrapper.h in Headers */, @@ -1112,6 +1123,7 @@ 5FCDD49F2B7AC6A200EAF29F /* Branch.h in Headers */, 5FCDD5082B7AC6A300EAF29F /* BNCUrlQueryParameter.h in Headers */, 5FCDD5472B7AC6A300EAF29F /* BNCConfig.h in Headers */, + 5F5FDA1B2B7DE31E00F14A43 /* BranchLogger.h in Headers */, 5FCDD4E72B7AC6A200EAF29F /* UIViewController+Branch.h in Headers */, 5FCDD54A2B7AC6A300EAF29F /* BranchConstants.h in Headers */, 5FCDD5412B7AC6A300EAF29F /* BranchSpotlightUrlRequest.h in Headers */, @@ -1192,6 +1204,7 @@ 5FCDD5482B7AC6A300EAF29F /* BNCConfig.h in Headers */, 5FCDD4E82B7AC6A200EAF29F /* UIViewController+Branch.h in Headers */, 5FCDD54B2B7AC6A300EAF29F /* BranchConstants.h in Headers */, + 5F5FDA1C2B7DE31E00F14A43 /* BranchLogger.h in Headers */, 5FCDD5422B7AC6A300EAF29F /* BranchSpotlightUrlRequest.h in Headers */, 5FCDD5B42B7AC89200EAF29F /* BranchSDK.h in Headers */, 5FCDD5572B7AC6A300EAF29F /* BNCCrashlyticsWrapper.h in Headers */, @@ -1556,6 +1569,7 @@ 5FCDD5AC2B7AC6A400EAF29F /* BNCCallbackMap.m in Sources */, 5FCDD40E2B7AC6A100EAF29F /* BNCApplication.m in Sources */, 5FCDD5642B7AC6A300EAF29F /* BranchDelegate.m in Sources */, + 5F5FDA162B7DE2FE00F14A43 /* BranchLogger.m in Sources */, 5FCDD58B2B7AC6A400EAF29F /* BNCSpotlightService.m in Sources */, 5FCDD4142B7AC6A100EAF29F /* NSMutableDictionary+Branch.m in Sources */, 5FCDD4082B7AC6A100EAF29F /* BranchUniversalObject.m in Sources */, @@ -1660,6 +1674,7 @@ 5FCDD5AD2B7AC6A400EAF29F /* BNCCallbackMap.m in Sources */, 5FCDD40F2B7AC6A100EAF29F /* BNCApplication.m in Sources */, 5FCDD5652B7AC6A300EAF29F /* BranchDelegate.m in Sources */, + 5F5FDA172B7DE2FE00F14A43 /* BranchLogger.m in Sources */, 5FCDD58C2B7AC6A400EAF29F /* BNCSpotlightService.m in Sources */, 5FCDD4152B7AC6A100EAF29F /* NSMutableDictionary+Branch.m in Sources */, 5FCDD4092B7AC6A100EAF29F /* BranchUniversalObject.m in Sources */, @@ -1743,6 +1758,7 @@ 5FCDD4762B7AC6A100EAF29F /* BNCPartnerParameters.m in Sources */, 5FCDD4732B7AC6A100EAF29F /* BranchLATDRequest.m in Sources */, 5FCDD57E2B7AC6A400EAF29F /* BNCPasteboard.m in Sources */, + 5F5FDA182B7DE2FE00F14A43 /* BranchLogger.m in Sources */, 5FCDD4612B7AC6A100EAF29F /* BNCRequestFactory.m in Sources */, 5FCDD41F2B7AC6A100EAF29F /* BNCDeepLinkViewControllerInstance.m in Sources */, 5FCDD58A2B7AC6A400EAF29F /* BNCLinkCache.m in Sources */, diff --git a/Framework/BranchSDK.h b/Framework/BranchSDK.h index 40c60ed55..c57177260 100644 --- a/Framework/BranchSDK.h +++ b/Framework/BranchSDK.h @@ -24,6 +24,7 @@ FOUNDATION_EXPORT const unsigned char BranchSDKVersionString[]; #import #import #import +#import #import diff --git a/Sources/BranchSDK/BNCAppGroupsData.m b/Sources/BranchSDK/BNCAppGroupsData.m index e7885d9d9..8ce782b95 100644 --- a/Sources/BranchSDK/BNCAppGroupsData.m +++ b/Sources/BranchSDK/BNCAppGroupsData.m @@ -7,8 +7,6 @@ // #import "BNCAppGroupsData.h" - -#import "BNCLog.h" #import "BNCApplication.h" #import "BNCPreferenceHelper.h" #import "BNCSystemObserver.h" diff --git a/Sources/BranchSDK/BNCApplication.m b/Sources/BranchSDK/BNCApplication.m index f5e0b8996..2bbecb03a 100644 --- a/Sources/BranchSDK/BNCApplication.m +++ b/Sources/BranchSDK/BNCApplication.m @@ -9,7 +9,7 @@ */ #import "BNCApplication.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "BNCKeyChain.h" static NSString*const kBranchKeychainService = @"BranchKeychainService"; @@ -87,12 +87,12 @@ + (NSDate*) currentBuildDate { NSFileManager *fileManager = [NSFileManager defaultManager]; NSDictionary *attributes = [fileManager attributesOfItemAtPath:appURL.path error:&error]; if (error) { - BNCLogError([NSString stringWithFormat:@"Can't get build date: %@.", error]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Can't get build date: %@.", error] error:error]; return nil; } NSDate * buildDate = [attributes fileCreationDate]; if (buildDate == nil || [buildDate timeIntervalSince1970] <= 0.0) { - BNCLogError([NSString stringWithFormat:@"Invalid build date: %@.", buildDate]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Invalid build date: %@.", buildDate] error:nil]; } return buildDate; } @@ -111,7 +111,8 @@ + (NSDate*) firstInstallBuildDate { forService:kBranchKeychainService key:kBranchKeychainFirstBuildKey cloudAccessGroup:nil]; - if (error) BNCLogError([NSString stringWithFormat:@"Keychain store: %@.", error]); + if (error) [[BranchLogger shared] logError:[NSString stringWithFormat:@"Keychain store: %@.", error] error:error]; + return firstBuildDate; } @@ -124,7 +125,7 @@ + (NSDate *) currentInstallDate { #endif if (installDate == nil || [installDate timeIntervalSince1970] <= 0.0) { - BNCLogWarning([NSString stringWithFormat:@"Invalid install date, using [NSDate date]."]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Invalid install date, using [NSDate date]."]]; } return installDate; } @@ -135,7 +136,7 @@ + (NSDate *)creationDateForLibraryDirectory { NSURL *directoryURL = [[fileManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] firstObject]; NSDictionary *attributes = [fileManager attributesOfItemAtPath:directoryURL.path error:&error]; if (error) { - BNCLogError([NSString stringWithFormat:@"Can't get creation date for Library directory: %@", error]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Can't get creation date for Library directory: %@", error] error:error]; return nil; } return [attributes fileCreationDate]; @@ -155,7 +156,7 @@ + (NSDate*) firstInstallDate { // save filesystem time to keychain error = [BNCKeyChain storeDate:firstInstallDate forService:kBranchKeychainService key:kBranchKeychainFirstInstalldKey cloudAccessGroup:nil]; if (error) { - BNCLogError([NSString stringWithFormat:@"Keychain store: %@.", error]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Keychain store: %@.", error] error:error]; } return firstInstallDate; } diff --git a/Sources/BranchSDK/BNCDeviceInfo.m b/Sources/BranchSDK/BNCDeviceInfo.m index b9d2ed5ea..ef933b86d 100644 --- a/Sources/BranchSDK/BNCDeviceInfo.m +++ b/Sources/BranchSDK/BNCDeviceInfo.m @@ -9,7 +9,6 @@ #import "BNCDeviceInfo.h" #import "BNCPreferenceHelper.h" #import "BNCSystemObserver.h" -#import "BNCLog.h" #import "BNCConfig.h" #import "BNCNetworkInterface.h" #import "BNCReachability.h" diff --git a/Sources/BranchSDK/BNCEncodingUtils.m b/Sources/BranchSDK/BNCEncodingUtils.m index 8d53e3750..57cf9e16c 100644 --- a/Sources/BranchSDK/BNCEncodingUtils.m +++ b/Sources/BranchSDK/BNCEncodingUtils.m @@ -8,8 +8,8 @@ #import "BNCEncodingUtils.h" #import "BNCPreferenceHelper.h" -#import "BNCLog.h" #import +#import "BranchLogger.h" #pragma mark BNCWireFormat @@ -167,7 +167,7 @@ + (NSString *)encodeDictionaryToJsonString:(NSDictionary *)dictionary { // protect against non-string keys if (![key isKindOfClass:[NSString class]]) { - BNCLogError([NSString stringWithFormat:@"Unexpected key type %@. Skipping key.", [key class]]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Unexpected key type %@. Skipping key.", [key class]] error:nil]; continue; } @@ -208,7 +208,7 @@ + (NSString *)encodeDictionaryToJsonString:(NSDictionary *)dictionary { } else { // If this type is not a known type, don't attempt to encode it. - BNCLogError([NSString stringWithFormat:@"Cannot encode value for key %@. The value is not an accepted type.", key]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Cannot encode value for key %@. The value is not an accepted type.", key] error:nil]; continue; } @@ -230,7 +230,7 @@ + (NSString *)encodeDictionaryToJsonString:(NSDictionary *)dictionary { [encodedDictionary appendString:@"}"]; - BNCLogDebugSDK([NSString stringWithFormat:@"Encoded dictionary: %@.", encodedDictionary]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Encoded dictionary: %@.", encodedDictionary]]; return encodedDictionary; } @@ -272,7 +272,7 @@ + (NSString *)encodeArrayToJsonString:(NSArray *)array { } else { // If this type is not a known type, don't attempt to encode it. - BNCLogError([NSString stringWithFormat:@"Cannot encode value %@. The value is not an accepted type.", obj]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Cannot encode value %@. The value is not an accepted type.", obj] error:nil]; continue; } @@ -290,7 +290,8 @@ + (NSString *)encodeArrayToJsonString:(NSArray *)array { [encodedArray deleteCharactersInRange:NSMakeRange([encodedArray length] - 1, 1)]; [encodedArray appendString:@"]"]; - BNCLogDebugSDK([NSString stringWithFormat:@"Encoded array: %@.", encodedArray]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Encoded array: %@.", encodedArray]]; + return encodedArray; } @@ -323,7 +324,7 @@ + (NSString *)encodeDictionaryToQueryString:(NSDictionary *)dictionary { } else { // If this type is not a known type, don't attempt to encode it. - BNCLogError([NSString stringWithFormat:@"Cannot encode value %@. The value is not an accepted type.", obj]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Cannot encode value %@. The value is not an accepted type.", obj] error:nil]; continue; } diff --git a/Sources/BranchSDK/BNCKeyChain.m b/Sources/BranchSDK/BNCKeyChain.m index 6edd76ac9..c2e1da340 100644 --- a/Sources/BranchSDK/BNCKeyChain.m +++ b/Sources/BranchSDK/BNCKeyChain.m @@ -9,7 +9,7 @@ */ #import "BNCKeyChain.h" -#import "BNCLog.h" +#import "BranchLogger.h" // Apple Keychain Reference: // https://developer.apple.com/library/content/documentation/Conceptual/ @@ -57,7 +57,7 @@ + (NSDate *) retrieveDateForService:(NSString *)service key:(NSString *)key erro OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)dictionary, (CFTypeRef *)&valueData); if (status != errSecSuccess) { NSError *localError = [self errorWithKey:key OSStatus:status]; - BNCLogDebugSDK([NSString stringWithFormat:@"Can't retrieve key: %@.", localError]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Can't retrieve key: %@.", localError]]; if (error) *error = localError; if (valueData) CFRelease(valueData); return nil; @@ -106,7 +106,7 @@ + (NSError *) storeDate:(NSDate *)date OSStatus status = SecItemDelete((__bridge CFDictionaryRef)dictionary); if (status != errSecSuccess && status != errSecItemNotFound) { NSError *error = [self errorWithKey:key OSStatus:status]; - BNCLogDebugSDK([NSString stringWithFormat:@"Can't clear to store key: %@.", error]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Can't clear to store key: %@.", error]]; } dictionary[(__bridge id)kSecValueData] = valueData; @@ -122,7 +122,7 @@ + (NSError *) storeDate:(NSDate *)date status = SecItemAdd((__bridge CFDictionaryRef)dictionary, NULL); if (status) { NSError *error = [self errorWithKey:key OSStatus:status]; - BNCLogDebugSDK([NSString stringWithFormat:@"Can't store key: %@.", error]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Can't store key: %@.", error]]; return error; } return nil; @@ -140,7 +140,7 @@ + (NSError*) removeValuesForService:(NSString *)service key:(NSString *)key { if (status == errSecItemNotFound) status = errSecSuccess; if (status) { NSError *error = [self errorWithKey:key OSStatus:status]; - BNCLogDebugSDK([NSString stringWithFormat:@"Can't remove key: %@.", error]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Can't remove key: %@.", error]]; return error; } return nil; @@ -154,8 +154,8 @@ + (NSString * _Nullable) securityAccessGroup { // First store a value: NSError *error = [self storeDate:[NSDate date] forService:@"BranchKeychainService" key:@"Temp" cloudAccessGroup:nil]; - if (error) BNCLogDebugSDK([NSString stringWithFormat:@"Error storing temp value: %@.", error]); - + if (error) [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Error storing temp value: %@.", error]]; + NSDictionary* dictionary = @{ (__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword, (__bridge id)kSecAttrService: @"BranchKeychainService", @@ -167,8 +167,8 @@ + (NSString * _Nullable) securityAccessGroup { OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)dictionary, (CFTypeRef*)&resultDictionary); if (status == errSecItemNotFound) return nil; if (status != errSecSuccess) { - BNCLogDebugSDK([NSString stringWithFormat:@"Get securityAccessGroup returned(%ld): %@.", - (long) status, [self errorWithKey:nil OSStatus:status]]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Get securityAccessGroup returned(%ld): %@.", + (long) status, [self errorWithKey:nil OSStatus:status]]]; return nil; } NSString*group = diff --git a/Sources/BranchSDK/BNCNetworkInterface.m b/Sources/BranchSDK/BNCNetworkInterface.m index 7f384660c..87dffc8b2 100644 --- a/Sources/BranchSDK/BNCNetworkInterface.m +++ b/Sources/BranchSDK/BNCNetworkInterface.m @@ -7,7 +7,7 @@ // #import "BNCNetworkInterface.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import #import @@ -49,16 +49,14 @@ - (NSString*) description { // Retrieve the current interfaces - returns 0 on success if (getifaddrs(&interfaces) != 0) { int e = errno; - BNCLogError([NSString stringWithFormat:@"Can't read ip address: (%d): %s.", e, strerror(e)]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Can't read ip address: (%d): %s.", e, strerror(e)] error:nil]; goto exit; } // Loop through linked list of interfaces -- struct ifaddrs *interface = NULL; for (interface=interfaces; interface; interface=interface->ifa_next) { - - // BNCLogDebugSDK(@"Found %s: %x.", interface->ifa_name, interface->ifa_flags); - + // Check the state: IFF_RUNNING, IFF_UP, IFF_LOOPBACK, etc. if ((interface->ifa_flags & IFF_UP) && (interface->ifa_flags & IFF_RUNNING) && !(interface->ifa_flags & IFF_LOOPBACK)) { } else { diff --git a/Sources/BranchSDK/BNCNetworkService.m b/Sources/BranchSDK/BNCNetworkService.m index 48b7edba0..ea3ee4d16 100644 --- a/Sources/BranchSDK/BNCNetworkService.m +++ b/Sources/BranchSDK/BNCNetworkService.m @@ -8,8 +8,9 @@ #import "BNCNetworkService.h" #import "BNCEncodingUtils.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "NSError+Branch.h" +#import "BranchLogger.h" #pragma mark BNCNetworkOperation @@ -152,7 +153,7 @@ - (BNCNetworkOperation*) networkOperationWithURLRequest:(NSMutableURLRequest*)re BNCNetworkOperation *operation = [BNCNetworkOperation new]; if (![request isKindOfClass:[NSMutableURLRequest class]]) { - BNCLogError(@"A `NSMutableURLRequest` request parameter was expected."); + [[BranchLogger shared] logError:@"A `NSMutableURLRequest` request parameter was expected." error:nil]; return nil; } operation.request = request; @@ -166,45 +167,44 @@ - (void) startOperation:(BNCNetworkOperation*)operation { if (!operation.startDate) { operation.startDate = [NSDate date]; } + if (!operation.timeoutDate) { NSTimeInterval timeoutInterval = operation.request.timeoutInterval; if (timeoutInterval < 0.0) timeoutInterval = self.defaultTimeoutInterval; operation.timeoutDate = - [[operation startDate] dateByAddingTimeInterval:timeoutInterval]; + [[operation startDate] dateByAddingTimeInterval:timeoutInterval]; } + if ([operation.request isKindOfClass:[NSMutableURLRequest class]]) { ((NSMutableURLRequest*)operation.request).timeoutInterval = - [operation.timeoutDate timeIntervalSinceDate:[NSDate date]]; + [operation.timeoutDate timeIntervalSinceDate:[NSDate date]]; } else { - BNCLogError(@"SDK logic error. Expected mutable request in `start` method."); + [[BranchLogger shared] logError:@"SDK logic error. Expected mutable request in `start` method." error:nil]; } + operation.sessionTask = - [self.session dataTaskWithRequest:operation.request - completionHandler: - ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { - operation.responseData = data; - operation.response = (NSHTTPURLResponse*) response; - operation.error = error; - if (operation.response.statusCode == 404) { - /* Don't print 404 messages because they look like an error. - BNCLogDebugSDK(@"Network finish operation %@ %1.3fs. Status %ld.", - operation.request.URL.absoluteString, - [[NSDate date] timeIntervalSinceDate:operation.startDate], - (long)operation.response.statusCode); - */ - } else { - BNCLogDebug([NSString stringWithFormat:@"Network finish operation %@ %1.3fs. Status %ld error %@.\n%@.", - operation.request.URL.absoluteString, - [[NSDate date] timeIntervalSinceDate:operation.startDate], - (long)operation.response.statusCode, - operation.error, - operation.stringFromResponseData]); - } - if (operation.completionBlock) - operation.completionBlock(operation); - }]; - BNCLogDebug([NSString stringWithFormat:@"Network start operation %@.", operation.request.URL]); + [self.session dataTaskWithRequest:operation.request + completionHandler: + ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { + operation.responseData = data; + operation.response = (NSHTTPURLResponse*) response; + operation.error = error; + + if (operation.response.statusCode != 404) { + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Network finish operation %@ %1.3fs. Status %ld error %@.\n%@.", + operation.request.URL.absoluteString, + [[NSDate date] timeIntervalSinceDate:operation.startDate], + (long)operation.response.statusCode, + operation.error, + operation.stringFromResponseData]]; + } + if (operation.completionBlock) + operation.completionBlock(operation); + }]; + + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Network start operation %@.", operation.request.URL]]; + [operation.sessionTask resume]; } diff --git a/Sources/BranchSDK/BNCPartnerParameters.m b/Sources/BranchSDK/BNCPartnerParameters.m index 8981aba3e..828edc1dc 100644 --- a/Sources/BranchSDK/BNCPartnerParameters.m +++ b/Sources/BranchSDK/BNCPartnerParameters.m @@ -7,7 +7,7 @@ // #import "BNCPartnerParameters.h" -#import "BNCLog.h" +#import "BranchLogger.h" @interface BNCPartnerParameters() @property (nonatomic, strong, readwrite) NSMutableDictionary *> *parameters; @@ -54,7 +54,7 @@ - (void)addFacebookParameterWithName:(NSString *)name value:(NSString *)value { if ([self sha256HashSanityCheckValue:value]) { [self addParameterWithName:name value:value partnerName:@"fb"]; } else { - BNCLogWarning(@"Partner parameter does not appear to be SHA256 hashed. Dropping the parameter."); + [[BranchLogger shared] logWarning:@"Partner parameter does not appear to be SHA256 hashed. Dropping the parameter."]; } } @@ -62,7 +62,7 @@ - (void)addSnapParameterWithName:(NSString *)name value:(NSString *)value { if ([self sha256HashSanityCheckValue:value]) { [self addParameterWithName:name value:value partnerName:@"snap"]; } else { - BNCLogWarning(@"Partner parameter does not appear to be SHA256 hashed. Dropping the parameter."); + [[BranchLogger shared] logWarning:@"Partner parameter does not appear to be SHA256 hashed. Dropping the parameter."]; } } diff --git a/Sources/BranchSDK/BNCPreferenceHelper.m b/Sources/BranchSDK/BNCPreferenceHelper.m index fb7a3ca58..cee6cbbb4 100644 --- a/Sources/BranchSDK/BNCPreferenceHelper.m +++ b/Sources/BranchSDK/BNCPreferenceHelper.m @@ -10,7 +10,7 @@ #import "BNCEncodingUtils.h" #import "BNCConfig.h" #import "Branch.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "BranchConstants.h" #import "NSString+Branch.h" #import "BNCSKAdNetwork.h" @@ -26,7 +26,6 @@ static NSString * const BRANCH_PREFS_KEY_LAST_RUN_BRANCH_KEY = @"bnc_last_run_branch_key"; static NSString * const BRANCH_PREFS_KEY_LAST_STRONG_MATCH_DATE = @"bnc_strong_match_created_date"; -static NSString * const BRANCH_PREFS_KEY_API_URL = @"bnc_api_url"; static NSString * const BRANCH_PREFS_KEY_PATTERN_LIST_URL = @"bnc_pattern_list_url"; static NSString * const BRANCH_PREFS_KEY_RANDOMIZED_DEVICE_TOKEN = @"bnc_randomized_device_token"; @@ -61,6 +60,10 @@ static NSString * const BRANCH_PREFS_KEY_LOG_IAP_AS_EVENTS = @"bnc_log_iap_as_events"; +static NSString * const BRANCH_PREFS_KEY_DMA_EEA = @"bnc_dma_eea"; +static NSString * const BRANCH_PREFS_KEY_DMA_AD_PERSONALIZATION = @"bnc_dma_ad_personalization"; +static NSString * const BRANCH_PREFS_KEY_DMA_AD_USER_DATA = @"bnc_dma_ad_user_data"; + NSURL* /* _Nonnull */ BNCURLForBranchDirectory_Unthreaded(void); @@ -68,7 +71,6 @@ @interface BNCPreferenceHelper () { NSOperationQueue *_persistPrefsQueue; NSString *_lastSystemBuildVersion; NSString *_browserUserAgentString; - NSString *_branchAPIURL; NSString *_referringURL; } @@ -114,7 +116,10 @@ @implementation BNCPreferenceHelper highestConversionValueSent = _highestConversionValueSent, referringURLQueryParameters = _referringURLQueryParameters, anonID = _anonID, - patternListURL = _patternListURL; + patternListURL = _patternListURL, + eeaRegion = _eeaRegion, + adPersonalizationConsent = _adPersonalizationConsent, + adUserDataUsageConsent = _adUserDataUsageConsent; + (BNCPreferenceHelper *)sharedInstance { static BNCPreferenceHelper *preferenceHelper; @@ -156,34 +161,6 @@ - (void) dealloc { #pragma mark - API methods -- (void)setBranchAPIURL:(NSString *)url { - if ([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"] ){ - @synchronized (self) { - _branchAPIURL = [url copy]; - [self writeObjectToDefaults:BRANCH_PREFS_KEY_API_URL value:_branchAPIURL]; - } - } else { - BNCLogWarning(@"Ignoring invalid custom API URL"); - } -} - -// TODO: This method is not used with the Tracking domain change. See SDK-2118 -- (NSString *)branchAPIURL { - @synchronized (self) { - if (!_branchAPIURL) { - _branchAPIURL = [self readStringFromDefaults:BRANCH_PREFS_KEY_API_URL]; - } - - // return the default URL in the event there's nothing in storage - if (_branchAPIURL == nil || [_branchAPIURL isEqualToString:@""]) { - _branchAPIURL = [BNC_API_URL copy]; - [self writeObjectToDefaults:BRANCH_PREFS_KEY_API_URL value:_branchAPIURL]; - } - - return _branchAPIURL; - } -} - - (void)setPatternListURL:(NSString *)url { if ([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"] ){ @synchronized (self) { @@ -191,7 +168,7 @@ - (void)setPatternListURL:(NSString *)url { [self writeObjectToDefaults:BRANCH_PREFS_KEY_PATTERN_LIST_URL value:url]; } } else { - BNCLogWarning(@"Ignoring invalid custom CDN URL"); + [[BranchLogger shared] logWarning:@"Ignoring invalid custom CDN URL"]; } } @@ -791,6 +768,60 @@ - (void) setInvokeRegisterApp:(BOOL)invoke { } } +- (BOOL) eeaRegionInitialized { + @synchronized(self) { + if([self readObjectFromDefaults:BRANCH_PREFS_KEY_DMA_EEA]) + return YES; + return NO; + } +} + +- (BOOL) eeaRegion { + @synchronized(self) { + NSNumber *b = (id) [self readObjectFromDefaults:BRANCH_PREFS_KEY_DMA_EEA]; + if ([b isKindOfClass:NSNumber.class]) return [b boolValue]; + return NO; + } +} + +- (void) setEeaRegion:(BOOL)isEEARegion { + @synchronized(self) { + NSNumber *b = [NSNumber numberWithBool:isEEARegion]; + [self writeObjectToDefaults:BRANCH_PREFS_KEY_DMA_EEA value:b]; + } +} + +- (BOOL) adPersonalizationConsent { + @synchronized(self) { + NSNumber *b = (id) [self readObjectFromDefaults:BRANCH_PREFS_KEY_DMA_AD_PERSONALIZATION]; + if ([b isKindOfClass:NSNumber.class]) return [b boolValue]; + return NO; + } +} + +- (void) setAdPersonalizationConsent:(BOOL)hasConsent { + @synchronized(self) { + NSNumber *b = [NSNumber numberWithBool:hasConsent]; + [self writeObjectToDefaults:BRANCH_PREFS_KEY_DMA_AD_PERSONALIZATION value:b]; + } +} + +- (BOOL) adUserDataUsageConsent { + @synchronized(self) { + NSNumber *b = (id) [self readObjectFromDefaults:BRANCH_PREFS_KEY_DMA_AD_USER_DATA]; + if ([b isKindOfClass:NSNumber.class]) return [b boolValue]; + return NO; + } +} + +- (void) setAdUserDataUsageConsent:(BOOL)hasConsent { + @synchronized(self) { + NSNumber *b = [NSNumber numberWithBool:hasConsent]; + [self writeObjectToDefaults:BRANCH_PREFS_KEY_DMA_AD_USER_DATA value:b]; + } +} + + - (void) clearTrackingInformation { @synchronized(self) { /* @@ -892,7 +923,7 @@ - (void)persistPrefsToDisk { NSError *error = nil; [data writeToURL:prefsURL options:NSDataWritingAtomic error:&error]; if (error) { - BNCLogWarning([NSString stringWithFormat:@"Failed to persist preferences: %@.", error]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Failed to persist preferences: %@.", error]]; } }]; [_persistPrefsQueue addOperation:newPersistOp]; @@ -907,7 +938,7 @@ - (NSData *)serializePrefDict:(NSMutableDictionary *)dict { @try { data = [NSKeyedArchiver archivedDataWithRootObject:dict requiringSecureCoding:YES error:NULL]; } @catch (id exception) { - BNCLogWarning([NSString stringWithFormat:@"Exception serializing preferences dict: %@.", exception]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Exception serializing preferences dict: %@.", exception]]; } return data; } @@ -938,10 +969,10 @@ - (NSData *)loadPrefData { NSError *error = nil; data = [NSData dataWithContentsOfURL:self.class.URLForPrefsFile options:0 error:&error]; if (error || !data) { - BNCLogWarning(@"Failed to load preferences from storage."); + [[BranchLogger shared] logWarning:@"Failed to load preferences from storage."]; } } @catch (NSException *) { - BNCLogWarning(@"Failed to load preferences from storage."); + [[BranchLogger shared] logWarning:@"Failed to load preferences from storage."]; } return data; } @@ -954,7 +985,7 @@ - (NSMutableDictionary *)deserializePrefDictFromData:(NSData *)data { dict = [NSKeyedUnarchiver unarchivedObjectOfClasses:classes fromData:data error:&error]; if (error) { - BNCLogWarning(@"Failed to load preferences from storage."); + [[BranchLogger shared] logWarning:@"Failed to load preferences from storage."]; } } @@ -1054,8 +1085,7 @@ + (NSURL* _Nonnull) URLForPrefsFile { if (success) { return branchURL; } else { - // BNCLog is dependent on BNCCreateDirectoryForBranchURLWithSearchPath_Unthreaded and cannot be used to log errors from it. - NSLog(@"CreateBranchURL failed: %@ URL: %@.", error, branchURL); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"CreateBranchURL failed: %@ URL: %@.", error, branchURL] error:error]; } } return nil; @@ -1094,8 +1124,7 @@ + (NSURL* _Nonnull) URLForPrefsFile { attributes:nil error:&error]; if (!success) { - // BNCLog is dependent on BNCURLForBranchDirectory_Unthreaded and cannot be used to log errors from it. - NSLog(@"Worst case CreateBranchURL error was: %@ URL: %@.", error, branchURL); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Worst case CreateBranchURL error was: %@ URL: %@.", error, branchURL] error:error]; } return branchURL; } diff --git a/Sources/BranchSDK/BNCReferringURLUtility.m b/Sources/BranchSDK/BNCReferringURLUtility.m index f026b7379..c4a9c965a 100644 --- a/Sources/BranchSDK/BNCReferringURLUtility.m +++ b/Sources/BranchSDK/BNCReferringURLUtility.m @@ -10,7 +10,7 @@ #import "BNCPreferenceHelper.h" #import "BranchConstants.h" #import "BNCUrlQueryParameter.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import @interface BNCReferringURLUtility() @@ -286,7 +286,7 @@ - (void)checkForAndMigrateOldGbraid { self.preferenceHelper.referrerGBRAIDValidityWindow = 0; self.preferenceHelper.referrerGBRAIDInitDate = nil; - BNCLogDebug(@"Updated old Gbraid to new BNCUrlQueryParameter"); + [[BranchLogger shared] logDebug:@"Updated old Gbraid to new BNCUrlQueryParameter"]; } } diff --git a/Sources/BranchSDK/BNCRequestFactory.m b/Sources/BranchSDK/BNCRequestFactory.m index 7386e9641..c9ca42c18 100644 --- a/Sources/BranchSDK/BNCRequestFactory.m +++ b/Sources/BranchSDK/BNCRequestFactory.m @@ -110,6 +110,9 @@ - (NSDictionary *)dataForInstall { // TODO: refactor to simply request values for install [self addReferringURLsToJSON:json forEndpoint:@"/v1/install"]; + // Add DMA Compliance Params for Google + [self addDMAConsentParamsToJSON:json]; + return json; } @@ -150,6 +153,9 @@ - (NSDictionary *)dataForOpen { // TODO: refactor to simply request values for open [self addReferringURLsToJSON:json forEndpoint:@"/v1/open"]; + // Add DMA Compliance Params for Google + [self addDMAConsentParamsToJSON:json]; + return json; } @@ -181,6 +187,7 @@ - (NSDictionary *)dataForEventWithEventDictionary:(NSMutableDictionary *)diction // TODO: refactor to simply request values for event [self addReferringURLsToJSON:json forEndpoint:@"/v2/event"]; + return json; } @@ -319,6 +326,16 @@ - (void)addPartnerParametersToJSON:(NSMutableDictionary *)json { } } +- (void)addDMAConsentParamsToJSON:(NSMutableDictionary *)json { + + if([self.preferenceHelper eeaRegionInitialized]){ + [self safeSetValue:@([self.preferenceHelper eeaRegion]) forKey:BRANCH_REQUEST_KEY_DMA_EEA onDict:json]; + [self safeSetValue:@([self.preferenceHelper adPersonalizationConsent]) forKey:BRANCH_REQUEST_KEY_DMA_AD_PEROSALIZATION onDict:json]; + [self safeSetValue:@([self.preferenceHelper adUserDataUsageConsent]) forKey:BRANCH_REQUEST_KEY_DMA_AD_USER_DATA onDict:json]; + } +} + + - (void)addLocalURLToInstallJSON:(NSMutableDictionary *)json { if ([BNCPasteboard sharedInstance].checkOnInstall) { NSURL *pasteboardURL = nil; @@ -523,6 +540,9 @@ - (NSDictionary *)v2dictionary { dictionary[@"sdk"] = @"ios"; } + // Add DMA Compliance Params for Google + [self addDMAConsentParamsToJSON:dictionary]; + return dictionary; } diff --git a/Sources/BranchSDK/BNCSKAdNetwork.m b/Sources/BranchSDK/BNCSKAdNetwork.m index f29a1ccec..71ff70b93 100644 --- a/Sources/BranchSDK/BNCSKAdNetwork.m +++ b/Sources/BranchSDK/BNCSKAdNetwork.m @@ -10,7 +10,7 @@ #import "BNCApplication.h" #import "BNCPreferenceHelper.h" #import "BranchConstants.h" -#import "BNCLog.h" +#import "BranchLogger.h" @interface BNCSKAdNetwork() @@ -73,8 +73,7 @@ - (BOOL)shouldAttemptSKAdNetworkCallout { - (void)registerAppForAdNetworkAttribution { if (@available(iOS 14.0, macCatalyst 14.0, *)) { if ([self shouldAttemptSKAdNetworkCallout] && [self.skAdNetworkClass respondsToSelector:self.skAdNetworkRegisterAppForAdNetworkAttribution]) { - BNCLogDebug(@"Calling registerAppForAdNetworkAttribution"); - + [[BranchLogger shared] logDebug:@"Calling registerAppForAdNetworkAttribution"]; // Equivalent call [SKAdNetwork registerAppForAdNetworkAttribution]; ((id (*)(id, SEL))[self.skAdNetworkClass methodForSelector:self.skAdNetworkRegisterAppForAdNetworkAttribution])(self.skAdNetworkClass, self.skAdNetworkRegisterAppForAdNetworkAttribution); } @@ -84,8 +83,8 @@ - (void)registerAppForAdNetworkAttribution { - (void)updateConversionValue:(NSInteger)conversionValue { if (@available(iOS 14.0, macCatalyst 14.0, *)) { if ([self shouldAttemptSKAdNetworkCallout] && [self.skAdNetworkClass respondsToSelector:self.skAdNetworkUpdateConversionValue]) { - BNCLogDebug([NSString stringWithFormat:@"Calling updateConversionValue:%ld", (long)conversionValue]); - + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Calling updateConversionValue:%ld", (long)conversionValue]]; + // Equivalent call [SKAdNetwork updateConversionValue:conversionValue]; ((id (*)(id, SEL, NSInteger))[self.skAdNetworkClass methodForSelector:self.skAdNetworkUpdateConversionValue])(self.skAdNetworkClass, self.skAdNetworkUpdateConversionValue, conversionValue); } @@ -95,7 +94,7 @@ - (void)updateConversionValue:(NSInteger)conversionValue { - (void)updatePostbackConversionValue:(NSInteger)conversionValue completionHandler:(void (^)(NSError *error))completion { if (@available(iOS 15.4, macCatalyst 15.4, *)) { if ([self shouldAttemptSKAdNetworkCallout] && [self.skAdNetworkClass respondsToSelector:self.skAdNetworkUpdatePostbackConversionValue]) { - BNCLogDebug([NSString stringWithFormat:@"Calling updatePostbackConversionValue:%ld completionHandler:completion", (long)conversionValue]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Calling updatePostbackConversionValue:%ld completionHandler:completion", (long)conversionValue]]; // Equivalent call [SKAdNetwork updatePostbackConversionValue:completionHandler:]; ((id (*)(id, SEL, NSInteger,void (^)(NSError *error)))[self.skAdNetworkClass methodForSelector:self.skAdNetworkUpdatePostbackConversionValue])(self.skAdNetworkClass, self.skAdNetworkUpdatePostbackConversionValue, conversionValue, completion); @@ -110,8 +109,7 @@ - (void)updatePostbackConversionValue:(NSInteger)fineValue completionHandler:(void (^)(NSError *error))completion { if (@available(iOS 16.1, macCatalyst 16.1, *)) { if ([self shouldAttemptSKAdNetworkCallout] && [self.skAdNetworkClass respondsToSelector:self.skAdNetworkUpdatePostbackConversionValueCoarseValueLockWindow]) { - BNCLogDebug([NSString stringWithFormat:@"Calling updatePostbackConversionValue:%ld coarseValue:%@ lockWindow:%d completionHandler:completion", (long)fineValue, coarseValue, lockWindow]); - + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Calling updatePostbackConversionValue:%ld coarseValue:%@ lockWindow:%d completionHandler:completion", (long)fineValue, coarseValue, lockWindow]]; // Equivalent call [SKAdNetwork updatePostbackConversionValue:coarseValue:lockWindow:completionHandler:]; ((id (*)(id, SEL, NSInteger, NSString *, BOOL, void (^)(NSError *error)))[self.skAdNetworkClass methodForSelector:self.skAdNetworkUpdatePostbackConversionValueCoarseValueLockWindow])(self.skAdNetworkClass, self.skAdNetworkUpdatePostbackConversionValueCoarseValueLockWindow, fineValue, coarseValue, lockWindow, completion); } diff --git a/Sources/BranchSDK/BNCServerAPI.m b/Sources/BranchSDK/BNCServerAPI.m index 2e9bc5c2a..73f8cb253 100644 --- a/Sources/BranchSDK/BNCServerAPI.m +++ b/Sources/BranchSDK/BNCServerAPI.m @@ -9,6 +9,7 @@ #import "BNCSystemObserver.h" #import "BNCConfig.h" #import "BranchConstants.h" +#import "BNCPreferenceHelper.h" @implementation BNCServerAPI @@ -29,6 +30,7 @@ - (instancetype)init { self.useTrackingDomain = NO; self.useEUServers = NO; self.automaticallyEnableTrackingDomain = YES; + self.customAPIURL = nil; } return self; } @@ -77,6 +79,10 @@ - (BOOL)optedIntoIDFA { // Linking endpoints are not used for Ads tracking - (NSString *)getBaseURLForLinkingEndpoints { + if (self.customAPIURL) { + return self.customAPIURL; + } + NSString * urlString; if (self.useEUServers){ urlString = BNC_EU_API_URL; @@ -88,6 +94,11 @@ - (NSString *)getBaseURLForLinkingEndpoints { } - (NSString *)getBaseURL { + //Check if user has set a custom API base URL + if (self.customAPIURL) { + return self.customAPIURL; + } + if (self.automaticallyEnableTrackingDomain) { self.useTrackingDomain = [self optedIntoIDFA]; } diff --git a/Sources/BranchSDK/BNCServerInterface.m b/Sources/BranchSDK/BNCServerInterface.m index ac6287033..030a993bf 100644 --- a/Sources/BranchSDK/BNCServerInterface.m +++ b/Sources/BranchSDK/BNCServerInterface.m @@ -11,10 +11,12 @@ #import "BNCEncodingUtils.h" #import "NSError+Branch.h" #import "BranchConstants.h" -#import "BNCLog.h" +#import "NSMutableDictionary+Branch.h" +#import "BranchLogger.h" #import "Branch.h" #import "BNCSKAdNetwork.h" #import "BNCReferringURLUtility.h" +#import "BranchLogger.h" @interface BNCServerInterface () @property (copy, nonatomic) NSString *requestEndpoint; @@ -116,7 +118,7 @@ - (void)genericHTTPRequest:(NSURLRequest *)request retryNumber:(NSInteger)retryN dispatch_time(DISPATCH_TIME_NOW, self.preferenceHelper.retryInterval * NSEC_PER_SEC); dispatch_after(dispatchTime, dispatch_get_main_queue(), ^{ if (retryHandler) { - BNCLogDebug([NSString stringWithFormat:@"Retrying request with url %@", request.URL.relativePath]); + [[BranchLogger shared] logDebug: [NSString stringWithFormat:@"Retrying request with url %@", request.URL.relativePath]]; // Create the next request NSURLRequest *retryRequest = retryHandler(retryNumber); [self genericHTTPRequest:retryRequest @@ -153,8 +155,7 @@ - (void)genericHTTPRequest:(NSURLRequest *)request retryNumber:(NSInteger)retryN } if (branchError) { - BNCLogError([NSString stringWithFormat:@"An error prevented request to %@ from completing: %@", - request.URL.absoluteString, branchError]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"An error prevented request to %@ from completing: %@", request.URL.absoluteString, branchError] error:branchError]; } // Don't call on the main queue since it might be blocked. @@ -169,7 +170,7 @@ - (void)genericHTTPRequest:(NSURLRequest *)request retryNumber:(NSInteger)retryN if (![self isLinkingRelatedRequest:endpoint]) { [[BNCPreferenceHelper sharedInstance] clearTrackingInformation]; NSError *error = [NSError branchErrorWithCode:BNCTrackingDisabledError]; - BNCLogWarning([NSString stringWithFormat:@"Dropping Request %@: - %@", endpoint, error]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Dropping Request %@: - %@", endpoint, error]]; if (callback) { callback(nil, error); } @@ -182,7 +183,7 @@ - (void)genericHTTPRequest:(NSURLRequest *)request retryNumber:(NSInteger)retryN [operation start]; NSError *error = [self verifyNetworkOperation:operation]; if (error) { - BNCLogError([NSString stringWithFormat:@"Network service error: %@.", error]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Network service error: %@.", error] error:error]; if (callback) { callback(nil, error); } @@ -277,8 +278,7 @@ - (NSURLRequest *)prepareGetRequest:(NSDictionary *)params url:(NSString *)url k NSDictionary *tmp = [self addRetryCount:retryNumber toJSON:params]; NSString *requestUrlString = [NSString stringWithFormat:@"%@%@", url, [BNCEncodingUtils encodeDictionaryToQueryString:tmp]]; - BNCLogDebug([NSString stringWithFormat:@"URL: %@", requestUrlString]); - + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"URL: %@", requestUrlString]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestUrlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:self.preferenceHelper.timeout]; @@ -295,11 +295,10 @@ - (NSURLRequest *)preparePostRequest:(NSDictionary *)params url:(NSString *)url NSData *postData = [BNCEncodingUtils encodeDictionaryToJsonData:tmp]; NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; - BNCLogDebug([NSString stringWithFormat:@"URL: %@.\n", url]); - BNCLogDebug([NSString stringWithFormat:@"Body: %@\nJSON: %@.", - params, - [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]] - ); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"URL: %@.\n", url]]; + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Body: %@\nJSON: %@.", + params, + [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] @@ -328,8 +327,9 @@ - (BNCServerResponse *)processServerResponse:(NSURLResponse *)response data:(NSD serverResponse.data = error.userInfo; serverResponse.requestId = requestId; } + + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Server returned: %@.", serverResponse]]; - BNCLogDebug([NSString stringWithFormat:@"Server returned: %@.", serverResponse]); return serverResponse; } diff --git a/Sources/BranchSDK/BNCServerRequest.m b/Sources/BranchSDK/BNCServerRequest.m index ede44b0d8..decdf92db 100644 --- a/Sources/BranchSDK/BNCServerRequest.m +++ b/Sources/BranchSDK/BNCServerRequest.m @@ -7,16 +7,16 @@ // #import "BNCServerRequest.h" -#import "BNCLog.h" +#import "BranchLogger.h" @implementation BNCServerRequest - (void)makeRequest:(BNCServerInterface *)serverInterface key:(NSString *)key callback:(BNCServerCallback)callback { - BNCLogError(@"BNCServerRequest subclasses must implement makeRequest:key:callback:."); + [[BranchLogger shared] logError:@"BNCServerRequest subclasses must implement makeRequest:key:callback:." error:nil]; } - (void)processResponse:(BNCServerResponse *)response error:(NSError *)error { - BNCLogError(@"BNCServerRequest subclasses must implement processResponse:error:."); + [[BranchLogger shared] logError:@"BNCServerRequest subclasses must implement processResponse:error:." error:nil]; } - (id)initWithCoder:(NSCoder *)aDecoder { diff --git a/Sources/BranchSDK/BNCServerRequestQueue.m b/Sources/BranchSDK/BNCServerRequestQueue.m index dea5a88f7..60b528e67 100755 --- a/Sources/BranchSDK/BNCServerRequestQueue.m +++ b/Sources/BranchSDK/BNCServerRequestQueue.m @@ -15,7 +15,7 @@ #import "BranchOpenRequest.h" #import "BranchEvent.h" -#import "BNCLog.h" +#import "BranchLogger.h" static NSString * const BRANCH_QUEUE_FILE = @"BNCServerRequestQueue"; @@ -68,7 +68,7 @@ - (void)enqueue:(BNCServerRequest *)request { - (void)insert:(BNCServerRequest *)request at:(NSUInteger)index { @synchronized (self) { if (index > self.queue.count) { - BNCLogError(@"Invalid queue operation: index out of bound!"); + [[BranchLogger shared] logError:@"Invalid queue operation: index out of bound!" error:nil]; return; } if (request) { @@ -94,7 +94,7 @@ - (BNCServerRequest *)removeAt:(NSUInteger)index { @synchronized (self) { BNCServerRequest *request = nil; if (index >= self.queue.count) { - BNCLogError(@"Invalid queue operation: index out of bound!"); + [[BranchLogger shared] logError:@"Invalid queue operation: index out of bound!" error:nil]; return nil; } request = [self.queue objectAtIndex:index]; @@ -120,7 +120,7 @@ - (BNCServerRequest *)peek { - (BNCServerRequest *)peekAt:(NSUInteger)index { @synchronized (self) { if (index >= self.queue.count) { - BNCLogError(@"Invalid queue operation: index out of bound!"); + [[BranchLogger shared] logError:@"Invalid queue operation: index out of bound!" error:nil]; return nil; } BNCServerRequest *request = nil; @@ -167,7 +167,7 @@ - (BOOL)removeInstallOrOpen { BNCServerRequest *request = [self.queue objectAtIndex:i]; // Install extends open, so only need to check open. if ([request isKindOfClass:[BranchOpenRequest class]]) { - BNCLogDebugSDK(@"Removing open request."); + [[BranchLogger shared] logDebug:@"Removing open request."]; ((BranchOpenRequest *)request).callback = nil; [self remove:request]; return YES; @@ -199,7 +199,7 @@ - (BranchOpenRequest *)moveInstallOrOpenToFront:(NSInteger)networkCount { } if (!openOrInstallRequest) { - BNCLogError(@"No install or open request in queue while trying to move it to the front."); + [[BranchLogger shared] logError:@"No install or open request in queue while trying to move it to the front." error:nil]; return nil; } @@ -265,10 +265,10 @@ - (void)persistImmediately { [data writeToURL:self.class.URLForQueueFile options:NSDataWritingAtomic error:&error]; if (error) { - BNCLogError([NSString stringWithFormat:@"Failed to persist queue to disk: %@.", error]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Failed to persist queue to disk: %@.", error] error:error]; } } else { - BNCLogError([NSString stringWithFormat:@"Failed to encode queue."]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Failed to encode queue."] error:nil]; } } } @@ -306,7 +306,7 @@ - (NSData *)archiveObject:(NSObject *)object { data = [NSKeyedArchiver archivedDataWithRootObject:object requiringSecureCoding:YES error:&error]; if (!data && error) { - BNCLogWarning([NSString stringWithFormat:@"Failed to archive: %@", error]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Failed to archive: %@", error]]; } return data; } @@ -356,7 +356,7 @@ - (id)unarchiveObjectFromData:(NSData *)data { id object = [NSKeyedUnarchiver unarchivedObjectOfClasses:[BNCServerRequestQueue encodableClasses] fromData:data error:&error]; if (error) { - BNCLogWarning([NSString stringWithFormat:@"Failed to unarchive: %@", error]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Failed to unarchive: %@", error]]; } return object; @@ -412,7 +412,7 @@ + (instancetype)getInstance { dispatch_once(&onceToken, ^ { sharedQueue = [[BNCServerRequestQueue alloc] init]; [sharedQueue retrieve]; - BNCLogDebugSDK([NSString stringWithFormat:@"Retrieved from storage: %@.", sharedQueue]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Retrieved from storage: %@.", sharedQueue]]; }); return sharedQueue; } diff --git a/Sources/BranchSDK/BNCSystemObserver.m b/Sources/BranchSDK/BNCSystemObserver.m index cc4944302..9944bb409 100644 --- a/Sources/BranchSDK/BNCSystemObserver.m +++ b/Sources/BranchSDK/BNCSystemObserver.m @@ -7,7 +7,7 @@ // #import "BNCSystemObserver.h" -#import "BNCLog.h" +#import "BranchLogger.h" #if __has_feature(modules) @import UIKit; @import SystemConfiguration; @@ -54,7 +54,7 @@ + (NSString *)appleAttributionToken { // Apple said this API should respond within 50ms, lets give up after 500 ms dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(500 * NSEC_PER_MSEC))); if (token == nil) { - BNCLogDebug([NSString stringWithFormat:@"AppleAttributionToken request timed out"]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"AppleAttributionToken request timed out"]]; } } #endif diff --git a/Sources/BranchSDK/BNCURLFilter.m b/Sources/BranchSDK/BNCURLFilter.m index 4278ddda4..367ba2ae3 100644 --- a/Sources/BranchSDK/BNCURLFilter.m +++ b/Sources/BranchSDK/BNCURLFilter.m @@ -10,7 +10,7 @@ #import "BNCURLFilter.h" #import "Branch.h" -#import "BNCLog.h" +#import "BranchLogger.h" @interface BNCURLFilter () @@ -58,7 +58,7 @@ - (void)useDefaultPatternList { if (regex && !regexError) { [array addObject:regex]; } else { - BNCLogError([NSString stringWithFormat:@"Invalid regular expression '%@': %@.", pattern, regexError]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Invalid regular expression '%@': %@.", pattern, regexError] error:regexError]; } } return array; @@ -127,12 +127,13 @@ - (BOOL)foundUpdatedURLList:(id)operation { } if (statusCode == 404) { - BNCLogDebug([NSString stringWithFormat:@"No update for URL ignore list found."]); + [[BranchLogger shared] logDebug: [NSString stringWithFormat:@"No update for URL ignore list found."]]; return NO; } else if (statusCode != 200 || error != nil || jsonString == nil) { - BNCLogError([NSString stringWithFormat:@"Failed to update URL ignore list. error: %@ status: %ld", operation.error, (long)operation.response.statusCode]); - BNCLogDebug([NSString stringWithFormat:@"URL ignore JSON: %@", jsonString]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Failed to update URL ignore list. error: %@ status: %ld", operation.error, (long)operation.response.statusCode] error:operation.error]; + [[BranchLogger shared] logDebug: [NSString stringWithFormat:@"URL ignore JSON: %@", jsonString]]; + return NO; } else { @@ -145,19 +146,19 @@ - (nullable NSDictionary *)parseJSONFromData:(NSData *)data { NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (error) { - BNCLogError([NSString stringWithFormat:@"Can't parse URL ignore JSON: %@.", error]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Can't parse URL ignore JSON: %@.", error] error:error]; return nil; } NSArray *urls = dictionary[@"uri_skip_list"]; if (![urls isKindOfClass:NSArray.class]) { - BNCLogError([NSString stringWithFormat:@"Can't parse URL ignore JSON, uri_skip_list is not a NSArray."]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Can't parse URL ignore JSON, uri_skip_list is not a NSArray."] error:nil]; return nil; } NSNumber *version = dictionary[@"version"]; if (![version isKindOfClass:NSNumber.class]) { - BNCLogError([NSString stringWithFormat:@"Can't parse URL ignore JSON, version is not a NSNumber."]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Can't parse URL ignore JSON, version is not a NSNumber."] error:nil]; return nil; } diff --git a/Sources/BranchSDK/Branch.m b/Sources/BranchSDK/Branch.m index 897b71b5c..1d81d2f6e 100644 --- a/Sources/BranchSDK/Branch.m +++ b/Sources/BranchSDK/Branch.m @@ -39,11 +39,12 @@ #import "BranchEvent.h" #import "BNCPasteboard.h" #import "NSError+Branch.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "UIViewController+Branch.h" #import "BNCReferringURLUtility.h" #import "BNCServerAPI.h" #import "BranchPluginSupport.h" +#import "BranchLogger.h" #if !TARGET_OS_TV #import "BNCUserAgentCollector.h" @@ -81,7 +82,6 @@ NSString * const BNCShareInitiatedEvent = @"Share Started"; NSString * const BNCShareCompletedEvent = @"Share Completed"; -static NSString * const BNCLogLevelKey = @"io.branch.sdk.BNCLogLevel"; NSString * const BNCSpotlightFeature = @"spotlight"; #ifndef CSSearchableItemActivityIdentifier @@ -251,14 +251,14 @@ - (id)initWithInterface:(BNCServerInterface *)interface + (void)setNetworkServiceClass:(Class)networkServiceClass { @synchronized ([Branch class]) { if (bnc_networkServiceClass) { - BNCLogError(@"The Branch network service class is already set. It can be set only once."); + [[BranchLogger shared] logError:@"The Branch network service class is already set. It can be set only once." error:nil]; return; } if (![networkServiceClass conformsToProtocol:@protocol(BNCNetworkServiceProtocol)]) { - BNCLogError([NSString stringWithFormat:@"Class '%@' doesn't conform to protocol '%@'.", - NSStringFromClass(networkServiceClass), - NSStringFromProtocol(@protocol(BNCNetworkServiceProtocol))] - ); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Class '%@' doesn't conform to protocol '%@'.", + NSStringFromClass(networkServiceClass), + NSStringFromProtocol(@protocol(BNCNetworkServiceProtocol))] error:nil]; + return; } bnc_networkServiceClass = networkServiceClass; @@ -317,7 +317,7 @@ + (void)resetBranchKey { + (void)setUseTestBranchKey:(BOOL)useTestKey { @synchronized (self) { if (bnc_branchKey && !!useTestKey != !!bnc_useTestBranchKey) { - BNCLogError(@"Can't switch the Branch key once it's in use."); + [[BranchLogger shared] logError:@"Can't switch the Branch key once it's in use." error:nil]; return; } bnc_useTestBranchKey = useTestKey; @@ -335,7 +335,7 @@ + (void)setBranchKey:(NSString *)branchKey { [self setBranchKey:branchKey error:&error]; if (error) { - BNCLogError([NSString stringWithFormat:@"Branch init error: %@", error.localizedDescription]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Branch init error: %@", error.localizedDescription] error:error]; } } @@ -350,6 +350,8 @@ + (void)setBranchKey:(NSString*)branchKey error:(NSError **)error { NSString *errorMessage = [NSString stringWithFormat:@"Branch key can only be set once."]; *error = [NSError branchErrorWithCode:BNCInitError localizedMessage:errorMessage]; + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Branch key can only be set once."] error:*error]; + return; } @@ -358,15 +360,13 @@ + (void)setBranchKey:(NSString*)branchKey error:(NSError **)error { NSString *errorMessage = [NSString stringWithFormat:@"Invalid Branch key of type '%@'.", typeName]; *error = [NSError branchErrorWithCode:BNCInitError localizedMessage:errorMessage]; + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Invalid Branch key of type '%@'.", typeName] error:*error]; return; } if ([branchKey hasPrefix:@"key_test"]) { bnc_useTestBranchKey = YES; - BNCLogWarning( - @"You are using your test app's Branch Key. " - "Remember to change it to live Branch Key for production deployment." - ); + [[BranchLogger shared] logWarning: @"You are using your test app's Branch Key. Remember to change it to live Branch Key for production deployment."]; } else if ([branchKey hasPrefix:@"key_live"]) { bnc_useTestBranchKey = NO; @@ -374,6 +374,7 @@ + (void)setBranchKey:(NSString*)branchKey error:(NSError **)error { } else { NSString *errorMessage = [NSString stringWithFormat:@"Invalid Branch key format. Did you add your Branch key to your Info.plist? Passed key is '%@'.", branchKey]; *error = [NSError branchErrorWithCode:BNCInitError localizedMessage:errorMessage]; + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Invalid Branch key format. Did you add your Branch key to your Info.plist? Passed key is '%@'.", branchKey] error:*error]; return; } @@ -405,9 +406,7 @@ + (NSString *)branchKey { self.branchKey = branchKey; if (!bnc_branchKey) { - BNCLogError(@"Your Branch key is not set in your Info.plist file. See " - "https://dev.branch.io/getting-started/sdk-integration-guide/guide/ios/#configure-xcode-project" - " for configuration instructions."); + [[BranchLogger shared] logError:@"Your Branch key is not set in your Info.plist file. See https://dev.branch.io/getting-started/sdk-integration-guide/guide/ios/#configure-xcode-project for configuration instructions." error:nil]; } return bnc_branchKey; } @@ -420,20 +419,28 @@ + (BOOL)branchKeyIsSet { } - (void)enableLogging { - BNCLogSetDisplayLevel(BNCLogLevelDebug); + BranchLogger *logger = [BranchLogger shared]; + logger.loggingEnabled = YES; + logger.logLevelThreshold = BranchLogLevelDebug; +} + +- (void)enableLoggingAtLevel:(BranchLogLevel)logLevel withCallback:(nullable BranchLogCallback)callback { + BranchLogger *logger = [BranchLogger shared]; + logger.loggingEnabled = YES; + logger.logLevelThreshold = logLevel; + logger.logCallback = callback; } - (void)useEUEndpoints { [BNCServerAPI sharedInstance].useEUServers = YES; } -- (void)setDebug { - NSLog(@"Branch setDebug is deprecated and all functionality has been disabled. " - "If you wish to enable logging, please invoke enableLogging. " - "If you wish to simulate installs, please see add a Test Device " - "(https://help.branch.io/using-branch/docs/adding-test-devices) " - "then reset your test device's data " - "(https://help.branch.io/using-branch/docs/adding-test-devices#section-resetting-your-test-device-data)."); ++ (void)setAPIUrl:(NSString *)url { + if ([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"] ){ + [BNCServerAPI sharedInstance].customAPIURL = url; + } else { + [[BranchLogger shared] logWarning:(@"Ignoring invalid custom API URL")]; + } } - (void)validateSDKIntegration { @@ -474,11 +481,6 @@ - (void)accountForFacebookSDKPreventingAppLaunch { // deprecated } -- (void)suppressWarningLogs { - NSLog(@"suppressWarningLogs is deprecated and all functionality has been disabled. " - "If you wish to turn off all logging, please invoke BNCLogSetDisplayLevel(BNCLogLevelNone)."); -} - - (void)setRequestMetadataKey:(NSString *)key value:(NSObject *)value { [self.preferenceHelper setRequestMetadataKey:key value:value]; } @@ -541,6 +543,12 @@ + (void)setReferrerGbraidValidityWindow:(NSTimeInterval)validityWindow{ } } ++ (void) setDMAParamsForEEA:(BOOL)eeaRegion AdPersonalizationConsent:(BOOL)adPersonalizationConsent AdUserDataUsageConsent:(BOOL)adUserDataUsageConsent{ + [BNCPreferenceHelper sharedInstance].eeaRegion = eeaRegion; + [BNCPreferenceHelper sharedInstance].adPersonalizationConsent = adPersonalizationConsent; + [BNCPreferenceHelper sharedInstance].adUserDataUsageConsent = adUserDataUsageConsent; +} + #pragma mark - InitSession Permutation methods - (void)initSessionWithLaunchOptions:(NSDictionary *)options { @@ -795,8 +803,6 @@ - (BOOL)continueUserActivity:(NSUserActivity *)userActivity { } - (BOOL)continueUserActivity:(NSUserActivity *)userActivity sceneIdentifier:(NSString *)sceneIdentifier { - BNCLogDebugSDK(@"continueUserActivity:"); - if (userActivity.referrerURL) { self.preferenceHelper.initialReferrer = userActivity.referrerURL.absoluteString; } @@ -952,7 +958,7 @@ - (void)handleATTAuthorizationStatus:(NSUInteger)status { - (void)setSKAdNetworkCalloutMaxTimeSinceInstall:(NSTimeInterval)maxTimeInterval { if (@available(iOS 16.1, macCatalyst 16.1, *)) { - BNCLogDebug(@"This is no longer supported for iOS 16.1+ - SKAN4.0"); + [[BranchLogger shared] logDebug:@"This is no longer supported for iOS 16.1+ - SKAN4.0"]; } else { [BNCSKAdNetwork sharedInstance].maxTimeSinceInstall = maxTimeInterval; } @@ -1024,7 +1030,7 @@ - (void)logoutWithCallback:(callbackWithStatus)callback { (Branch.trackingDisabled) ? [NSError branchErrorWithCode:BNCTrackingDisabledError] : [NSError branchErrorWithCode:BNCInitError]; - BNCLogError(@"Branch is not initialized, cannot logout."); + [[BranchLogger shared] logError:@"Branch is not initialized, cannot logout." error:error]; if (callback) {callback(NO, error);} return; } @@ -1434,7 +1440,7 @@ - (void)passPasteItemProviders:(NSArray *)itemProviders { // 2. Check if URL is branch URL and if yes -> store it. [item loadItemForTypeIdentifier:UTTypeURL.identifier options:NULL completionHandler:^(NSURL *url, NSError * _Null_unspecified error) { if (error) { - BNCLogError([NSString stringWithFormat:@"%@", error]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"%@", error] error:error]; } else if ([Branch isBranchLink:url.absoluteString]) { [self.preferenceHelper setLocalUrl:[url absoluteString]]; @@ -1460,8 +1466,7 @@ + (Branch *)getInstanceInternal:(NSString *)key { // If there was stored key and it isn't the same as the currently used (or doesn't exist), we need to clean up // Note: Link Click Identifier is not cleared because of the potential for that to mess up a deep link if (preferenceHelper.lastRunBranchKey && ![key isEqualToString:preferenceHelper.lastRunBranchKey]) { - BNCLogWarning(@"The Branch Key has changed, clearing relevant items."); - + [[BranchLogger shared] logWarning:@"The Branch Key has changed, clearing relevant items."]; preferenceHelper.appVersion = nil; preferenceHelper.randomizedDeviceToken = nil; preferenceHelper.sessionID = nil; @@ -1590,7 +1595,7 @@ - (NSString *)generateShortUrl:(NSArray *)tags linkData:linkData linkCache:self.linkCache]; - BNCLogDebug(@"Creating a custom URL synchronously."); + [[BranchLogger shared] logDebug:@"Creating a custom URL synchronously."]; BNCServerResponse *serverResponse = [req makeRequest:self.serverInterface key:self.class.branchKey]; shortURL = [req processResponse:serverResponse]; @@ -1740,7 +1745,7 @@ - (void)applicationWillResignActive { self.initializationStatus = BNCInitStatusUninitialized; [self.requestQueue persistImmediately]; [BranchOpenRequest setWaitNeededForOpenResponseLock]; - BNCLogDebugSDK(@"Application resigned active."); + [[BranchLogger shared] logDebug:@"Application resigned active."]; } } @@ -1804,8 +1809,7 @@ - (void) processRequest:(BNCServerRequest*)req } // On network problems, or Branch down, call the other callbacks and stop processing. else { - BNCLogDebugSDK(@"Network error: failing queued requests."); - + [[BranchLogger shared] logDebug:@"Network error: failing queued requests."]; // First, gather all the requests to fail NSMutableArray *requestsToFail = [[NSMutableArray alloc] init]; for (int i = 0; i < self.requestQueue.queueDepth; i++) { @@ -1877,7 +1881,7 @@ - (void)processNextQueueItem { // If tracking is disabled, then do not check for install event. It won't exist. if (!Branch.trackingDisabled) { if (![req isKindOfClass:[BranchInstallRequest class]] && !self.preferenceHelper.randomizedBundleToken) { - BNCLogError(@"User session has not been initialized!"); + [[BranchLogger shared] logError:@"User session has not been initialized!" error:nil]; BNCPerformBlockOnMainThreadSync(^{ [req processResponse:nil error:[NSError branchErrorWithCode:BNCInitError]]; }); @@ -1885,7 +1889,7 @@ - (void)processNextQueueItem { } else if (![req isKindOfClass:[BranchOpenRequest class]] && (!self.preferenceHelper.randomizedDeviceToken || !self.preferenceHelper.sessionID)) { - BNCLogError(@"Missing session items!"); + [[BranchLogger shared] logError:@"Missing session items!" error:nil]; BNCPerformBlockOnMainThreadSync(^{ [req processResponse:nil error:[NSError branchErrorWithCode:BNCInitError]]; }); @@ -1948,7 +1952,7 @@ - (void)notifyNativeToInit { // Some methods require init before they are called. Instead of returning an error, we try to fix the situation by calling init ourselves. - (void)initSafetyCheck { if (self.initializationStatus == BNCInitStatusUninitialized) { - BNCLogDebug(@"Branch avoided an error by preemptively initializing."); + [[BranchLogger shared] logDebug:@"Branch avoided an error by preemptively initializing."]; [self initUserSessionAndCallCallback:NO sceneIdentifier:nil]; } } @@ -1958,8 +1962,6 @@ - (void)initUserSessionAndCallCallback:(BOOL)callCallback sceneIdentifier:(NSStr // ignore lifecycle calls while waiting for a plugin runtime. @synchronized (self) { if (self.deferInitForPluginRuntime) { - //NSString *debug = [NSString stringWithFormat:@"Init is deferred, ignoring call: %@", NSThread.callStackSymbols]; - //BNCLogDebug(debug); return; } } @@ -1972,18 +1974,6 @@ - (void)initUserSessionAndCallCallback:(BOOL)callCallback sceneIdentifier:(NSStr urlstring = self.preferenceHelper.externalIntentURI; } - if (urlstring.length) { - NSArray *queryItems = [BNCEncodingUtils queryItems:[NSURL URLWithString:urlstring]]; - for (BNCKeyValue*item in queryItems) { - if ([item.key isEqualToString:@"BranchLogLevel"]) { - BNCLogLevel logLevel = BNCLogLevelFromString(item.value); - [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:logLevel] forKey:BNCLogLevelKey]; - BNCLogSetDisplayLevel(logLevel); - NSLog(@"[io.branch.sdk] BNCLogLevel set to %ld.", (long) logLevel); - } - } - } - // If the session is not yet initialized if (self.initializationStatus == BNCInitStatusUninitialized) { [self initializeSessionAndCallCallback:callCallback sceneIdentifier:sceneIdentifier]; @@ -2121,8 +2111,7 @@ - (void)automaticallyDeeplinkWithReferringParams:(NSDictionary *)latestReferring [branchSharingController configureControlWithData:latestReferringParams]; } else { - BNCLogWarning([NSString stringWithFormat:@"The automatic deeplink view controller '%@' for key '%@' does not implement 'configureControlWithData:'.", - branchSharingController, key]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"The automatic deeplink view controller '%@' for key '%@' does not implement 'configureControlWithData:'.", branchSharingController, key]]; } self.deepLinkPresentingController = [UIViewController bnc_currentViewController]; @@ -2134,7 +2123,7 @@ - (void)automaticallyDeeplinkWithReferringParams:(NSDictionary *)latestReferring [branchSharingController configureControlWithData:latestReferringParams]; } else { - BNCLogWarning(@"View controller does not implement configureControlWithData:"); + [[BranchLogger shared] logWarning:@"View controller does not implement configureControlWithData:"]; } branchSharingController.deepLinkingCompletionDelegate = self; switch (deepLinkInstance.option) { @@ -2196,7 +2185,7 @@ - (void)automaticallyDeeplinkWithReferringParams:(NSDictionary *)latestReferring [branchSharingController configureControlWithData:latestReferringParams]; } else { - BNCLogWarning(@"View controller does not implement configureControlWithData:"); + [[BranchLogger shared] logWarning:@"View controller does not implement configureControlWithData:"]; } branchSharingController.deepLinkingCompletionDelegate = self; if ([self.deepLinkPresentingController presentedViewController]) { diff --git a/Sources/BranchSDK/BranchCSSearchableItemAttributeSet.m b/Sources/BranchSDK/BranchCSSearchableItemAttributeSet.m index 01802dbf1..0465b81f7 100644 --- a/Sources/BranchSDK/BranchCSSearchableItemAttributeSet.m +++ b/Sources/BranchSDK/BranchCSSearchableItemAttributeSet.m @@ -10,7 +10,7 @@ #import "NSError+Branch.h" #import "BranchConstants.h" #import "BranchConstants.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "Branch.h" #import "BNCSystemObserver.h" @@ -45,7 +45,7 @@ - (instancetype)initWithItemContentType:(nonnull NSString *)type { - (void)setIdentifier:(NSString *)identifier { if (![identifier hasPrefix:BRANCH_SPOTLIGHT_PREFIX]) { - BNCLogWarning(@"Do not set BranchCSSearchableItemAttributeSet's identifier. It will be overwritten."); + [[BranchLogger shared] logWarning:@"Do not set BranchCSSearchableItemAttributeSet's identifier. It will be overwritten."]; } } diff --git a/Sources/BranchSDK/BranchConstants.m b/Sources/BranchSDK/BranchConstants.m index f4d12989d..96749379b 100644 --- a/Sources/BranchSDK/BranchConstants.m +++ b/Sources/BranchSDK/BranchConstants.m @@ -161,3 +161,8 @@ NSString * const BRANCH_REQUEST_KEY_VALUE_POSTBACK_SEQUENCE_INDEX_0 = @"postback-sequence-index-0"; NSString * const BRANCH_REQUEST_KEY_VALUE_POSTBACK_SEQUENCE_INDEX_1 = @"postback-sequence-index-1"; NSString * const BRANCH_REQUEST_KEY_VALUE_POSTBACK_SEQUENCE_INDEX_2 = @"postback-sequence-index-2"; + +NSString * const BRANCH_REQUEST_KEY_DMA_EEA = @"dma_eea"; +NSString * const BRANCH_REQUEST_KEY_DMA_AD_PEROSALIZATION = @"dma_ad_personalization"; +NSString * const BRANCH_REQUEST_KEY_DMA_AD_USER_DATA = @"dma_ad_user_data"; + diff --git a/Sources/BranchSDK/BranchContentDiscoverer.m b/Sources/BranchSDK/BranchContentDiscoverer.m index b8ab1da9c..c9fa3394e 100644 --- a/Sources/BranchSDK/BranchContentDiscoverer.m +++ b/Sources/BranchSDK/BranchContentDiscoverer.m @@ -13,7 +13,7 @@ #import "BNCPreferenceHelper.h" #import "BranchConstants.h" #import "BNCEncodingUtils.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "UIViewController+Branch.h" @interface BranchContentDiscoverer () @@ -51,7 +51,7 @@ - (void) startDiscoveryTaskWithManifest:(BranchContentDiscoveryManifest*)manifes - (void)startDiscoveryTask { if (![NSThread isMainThread]) { - BNCLogError(@"Discovery should be called on main thread."); + [[BranchLogger shared] logError:@"Discovery should be called on main thread." error:nil]; } [_contentDiscoveryTimer invalidate]; _contentDiscoveryTimer = diff --git a/Sources/BranchSDK/BranchEvent.m b/Sources/BranchSDK/BranchEvent.m index 1798970f9..392cc9952 100644 --- a/Sources/BranchSDK/BranchEvent.m +++ b/Sources/BranchSDK/BranchEvent.m @@ -9,7 +9,7 @@ #import "BranchEvent.h" #import "BranchConstants.h" #import "NSError+Branch.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "BNCCallbackMap.h" #import "BNCReachability.h" #import "BNCSKAdNetwork.h" @@ -97,14 +97,13 @@ - (void)processResponse:(BNCServerResponse*)response error:(NSError*)error { BOOL lockWin = [[BNCSKAdNetwork sharedInstance] getLockedStatusFromDataResponse:dictionary]; BOOL shouldCallUpdatePostback = [[BNCSKAdNetwork sharedInstance] shouldCallPostbackForDataResponse:dictionary]; - BNCLogDebug([NSString stringWithFormat:@"SKAN 4.0 params - conversionValue:%@ coarseValue:%@, locked:%d, shouldCallPostback:%d, currentWindow:%d, firstAppLaunchTime: %@", conversionValue, coarseConversionValue, lockWin, shouldCallUpdatePostback, (int)[BNCPreferenceHelper sharedInstance].skanCurrentWindow, [BNCPreferenceHelper sharedInstance].firstAppLaunchTime]); - + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"SKAN 4.0 params - conversionValue:%@ coarseValue:%@, locked:%d, shouldCallPostback:%d, currentWindow:%d, firstAppLaunchTime: %@", conversionValue, coarseConversionValue, lockWin, shouldCallUpdatePostback, (int)[BNCPreferenceHelper sharedInstance].skanCurrentWindow, [BNCPreferenceHelper sharedInstance].firstAppLaunchTime]]; if(shouldCallUpdatePostback){ [[BNCSKAdNetwork sharedInstance] updatePostbackConversionValue: conversionValue.longValue coarseValue:coarseConversionValue lockWindow:lockWin completionHandler:^(NSError * _Nullable error) { if (error) { - BNCLogError([NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]] error:error]; } else { - BNCLogDebug([NSString stringWithFormat:@"Update conversion value was successful. Conversion Value - %@", conversionValue]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Update conversion value was successful. Conversion Value - %@", conversionValue]]; } }]; } @@ -112,9 +111,9 @@ - (void)processResponse:(BNCServerResponse*)response error:(NSError*)error { } else if (@available(iOS 15.4, macCatalyst 15.4, *)) { [[BNCSKAdNetwork sharedInstance] updatePostbackConversionValue:conversionValue.intValue completionHandler: ^(NSError *error){ if (error) { - BNCLogError([NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]] error:error]; } else { - BNCLogDebug([NSString stringWithFormat:@"Update conversion value was successful. Conversion Value - %@", conversionValue]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Update conversion value was successful. Conversion Value - %@", conversionValue]]; } }]; } else { @@ -273,7 +272,8 @@ - (NSDictionary*) dictionary { - (void)logEventWithCompletion:(void (^_Nullable)(BOOL success, NSError * _Nullable error))completion { if (![_eventName isKindOfClass:[NSString class]] || _eventName.length == 0) { - BNCLogError([NSString stringWithFormat:@"Invalid event type '%@' or empty string.", NSStringFromClass(_eventName.class)]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Invalid event type '%@' or empty string.", NSStringFromClass(_eventName.class)] error:nil]; + if (completion) { NSError *error = [NSError branchErrorWithCode:BNCGeneralError localizedMessage: @"Invalid event type"]; completion(NO, error); @@ -449,15 +449,15 @@ - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProdu } [self logEvent]; - BNCLogDebug([NSString stringWithFormat:@"Created and logged event from transaction: %@", self.description]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Created and logged event from transaction: %@", self.description]]; } else { - BNCLogError([NSString stringWithFormat:@"Unable to log Branch event from transaction. No products were found with the product ID."]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Unable to log Branch event from transaction. No products were found with the product ID."] error:nil]; } }); } - (void)request:(SKRequest *)request didFailWithError:(NSError *)error { - BNCLogError([NSString stringWithFormat:@"Product request failed: %@", error]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Product request failed: %@", error] error:error]; [[BNCEventUtils shared] removeEvent:self]; } diff --git a/Sources/BranchSDK/BranchJsonConfig.m b/Sources/BranchSDK/BranchJsonConfig.m index cf40aacec..aa3bbb077 100644 --- a/Sources/BranchSDK/BranchJsonConfig.m +++ b/Sources/BranchSDK/BranchJsonConfig.m @@ -6,7 +6,7 @@ // // -#import "BNCLog.h" +#import "BranchLogger.h" #import "BranchJsonConfig.h" NSString * _Nonnull const BranchJsonConfigDebugModeOption = @"debugMode"; @@ -56,12 +56,13 @@ - (void)loadConfigFile NSError *error; id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; if (!object || error) { - BNCLogError([NSString stringWithFormat:@"Failed to parse branch.json. Error: %@", error.localizedDescription]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Failed to parse branch.json. Error: %@", error.localizedDescription] error:error]; return; } if (![object isKindOfClass:NSDictionary.class]) { - BNCLogError(@"Contents of branch.json should be a JSON object."); + [[BranchLogger shared] logError:@"Contents of branch.json should be a JSON object." error:nil]; + return; } @@ -71,12 +72,11 @@ - (void)loadConfigFile - (NSData *)configFileContents { if (!self.configFileURL) return nil; - BNCLogDebug([NSString stringWithFormat:@"Loading %@", self.configFileURL.pathComponents.lastObject]); - + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Loading %@", self.configFileURL.pathComponents.lastObject]]; NSError *error; NSData *data = [NSData dataWithContentsOfURL:self.configFileURL options:0 error:&error]; if (!data || error) { - BNCLogError([NSString stringWithFormat:@"Failed to load %@. Error: %@", self.configFileURL, error.localizedDescription]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Failed to load %@. Error: %@", self.configFileURL, error.localizedDescription] error:error]; return nil; } return data; @@ -109,7 +109,7 @@ - (void)findConfigFile } if (!configFileURL) { - BNCLogDebug(@"No branch.json in app bundle."); + [[BranchLogger shared] logDebug:@"No branch.json in app bundle."]; return; } diff --git a/Sources/BranchSDK/BranchLastAttributedTouchData.m b/Sources/BranchSDK/BranchLastAttributedTouchData.m index 2193e943b..99316a32d 100644 --- a/Sources/BranchSDK/BranchLastAttributedTouchData.m +++ b/Sources/BranchSDK/BranchLastAttributedTouchData.m @@ -9,7 +9,7 @@ #import "BranchLastAttributedTouchData.h" #import "BranchLATDRequest.h" #import "BNCJSONUtility.h" -#import "BNCLog.h" +#import "BranchLogger.h" @implementation BranchLastAttributedTouchData @@ -33,7 +33,7 @@ + (void)requestLastTouchAttributedData:(BNCServerInterface *)serverInterface key if (window > -1 && window < 365) { request.attributionWindow = window; } else { - BNCLogWarning(@"Attribution window is outside the expected range, using 30 days."); + [[BranchLogger shared] logWarning:@"Attribution window is outside the expected range, using 30 days."]; } [request makeRequest:serverInterface key:key callback:^(BNCServerResponse *response, NSError *error) { diff --git a/Sources/BranchSDK/BranchLogger.m b/Sources/BranchSDK/BranchLogger.m new file mode 100644 index 000000000..e85a16fad --- /dev/null +++ b/Sources/BranchSDK/BranchLogger.m @@ -0,0 +1,119 @@ +// +// BranchLogger.m +// Branch +// +// Created by Nipun Singh on 2/1/24. +// Copyright © 2024 Branch, Inc. All rights reserved. +// + +#import "BranchLogger.h" +#import + +@implementation BranchLogger + +- (instancetype)init { + if ((self = [super init])) { + _loggingEnabled = NO; + _logLevelThreshold = BranchLogLevelDebug; + _includeCallerDetails = YES; + } + return self; +} + ++ (instancetype)shared { + static BranchLogger *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[BranchLogger alloc] init]; + sharedInstance.loggingEnabled = NO; + sharedInstance.logLevelThreshold = BranchLogLevelDebug; + sharedInstance.includeCallerDetails = YES; + }); + return sharedInstance; +} + +- (void)disableCallerDetails { + self.includeCallerDetails = NO; +} + +- (void)logError:(NSString *)message error:(NSError *_Nullable)error { + [self logMessage:message withLevel:BranchLogLevelError error:error]; +} + +- (void)logWarning:(NSString *)message { + [self logMessage:message withLevel:BranchLogLevelWarning error:nil]; +} + +- (void)logInfo:(NSString *)message { + [self logMessage:message withLevel:BranchLogLevelInfo error:nil]; +} + +- (void)logDebug:(NSString *)message { + [self logMessage:message withLevel:BranchLogLevelDebug error:nil]; +} + +- (void)logVerbose:(NSString *)message { + [self logMessage:message withLevel:BranchLogLevelVerbose error:nil]; +} + +- (void)logMessage:(NSString *)message withLevel:(BranchLogLevel)level error:(NSError *_Nullable)error { + if (!self.loggingEnabled || message.length == 0 || level < self.logLevelThreshold) { + return; + } + + NSString *callerDetails = self.includeCallerDetails ? [self callingClass] : @""; + NSString *logLevelString = [self stringForLogLevel:level]; + NSString *logTag = [NSString stringWithFormat:@"[BranchSDK][%@]", logLevelString]; + NSMutableString *fullMessage = [NSMutableString stringWithFormat:@"%@%@ %@", logTag, callerDetails, message]; + + if (error) { + [fullMessage appendFormat:@", Error: %@ (Domain: %@, Code: %ld)", error.localizedDescription, error.domain, (long)error.code]; + } + + if (self.logCallback) { + self.logCallback(fullMessage, level, error); + } else { + os_log_t log = os_log_create("io.branch.sdk", "BranchSDK"); + os_log_type_t osLogType = [self osLogTypeForBranchLogLevel:level]; + os_log_with_type(log, osLogType, "%{private}@", fullMessage); + } +} + +//MARK: Helper Methods +- (os_log_type_t)osLogTypeForBranchLogLevel:(BranchLogLevel)level { + switch (level) { + case BranchLogLevelError: return OS_LOG_TYPE_FAULT; + case BranchLogLevelWarning: return OS_LOG_TYPE_ERROR; + case BranchLogLevelInfo: return OS_LOG_TYPE_INFO; + case BranchLogLevelDebug: return OS_LOG_TYPE_DEBUG; + case BranchLogLevelVerbose: return OS_LOG_TYPE_DEFAULT; + default: return OS_LOG_TYPE_DEFAULT; + } +} + +- (NSString *)stringForLogLevel:(BranchLogLevel)level { + switch (level) { + case BranchLogLevelVerbose: return @"Verbose"; + case BranchLogLevelDebug: return @"Debug"; + case BranchLogLevelInfo: return @"Info"; + case BranchLogLevelWarning: return @"Warning"; + case BranchLogLevelError: return @"Error"; + default: return @"Unknown"; + } +} + +- (NSString *)callingClass { + NSArray *stackSymbols = [NSThread callStackSymbols]; + NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[([^\\]]+)\\]" options:0 error:nil]; + if (stackSymbols.count > 3 && regex) { + NSString *callSite = stackSymbols[3]; + NSTextCheckingResult *match = [regex firstMatchInString:callSite options:0 range:NSMakeRange(0, [callSite length])]; + if (match && match.range.location != NSNotFound) { + NSString *callerDetails = [callSite substringWithRange:[match rangeAtIndex:0]]; + return callerDetails; + } + } + return @""; +} + +@end diff --git a/Sources/BranchSDK/BranchOpenRequest.m b/Sources/BranchSDK/BranchOpenRequest.m index 2b2ec894c..89517f15f 100644 --- a/Sources/BranchSDK/BranchOpenRequest.m +++ b/Sources/BranchSDK/BranchOpenRequest.m @@ -20,7 +20,7 @@ // handle app clip data for installs. This shouldn't be here imho #import "BNCAppGroupsData.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "BNCRequestFactory.h" #import "BNCServerAPI.h" @@ -102,17 +102,14 @@ - (void)processResponse:(BNCServerResponse *)response error:(NSError *)error { if (sessionData == nil || [sessionData isKindOfClass:[NSString class]]) { } else if ([sessionData isKindOfClass:[NSDictionary class]]) { - BNCLogWarning([NSString stringWithFormat:@"Received session data of type '%@' data is '%@'.", - NSStringFromClass(sessionData.class), sessionData]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Received session data of type '%@' data is '%@'.", NSStringFromClass(sessionData.class), sessionData]]; sessionData = [BNCEncodingUtils encodeDictionaryToJsonString:(NSDictionary*)sessionData]; } else if ([sessionData isKindOfClass:[NSArray class]]) { - BNCLogWarning([NSString stringWithFormat:@"Received session data of type '%@' data is '%@'.", - NSStringFromClass(sessionData.class), sessionData]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Received session data of type '%@' data is '%@'.", NSStringFromClass(sessionData.class), sessionData]]; sessionData = [BNCEncodingUtils encodeArrayToJsonString:(NSArray*)sessionData]; } else { - BNCLogError([NSString stringWithFormat:@"Received session data of type '%@' data is '%@'.", - NSStringFromClass(sessionData.class), sessionData]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Received session data of type '%@' data is '%@'.", NSStringFromClass(sessionData.class), sessionData] error:error]; sessionData = nil; } @@ -193,17 +190,17 @@ - (void)processResponse:(BNCServerResponse *)response error:(NSError *)error { [[BNCSKAdNetwork sharedInstance] updatePostbackConversionValue:0 coarseValue:defaultCoarseConValue lockWindow:NO completionHandler:^(NSError * _Nullable error) { if (error) { - BNCLogError([NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]] error:error]; } else { - BNCLogDebug([NSString stringWithFormat:@"Update conversion value was successful for INSTALL Event"]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Update conversion value was successful for INSTALL Event"]]; } }]; } else if (@available(iOS 15.4, macCatalyst 15.4, *)){ [[BNCSKAdNetwork sharedInstance] updatePostbackConversionValue:0 completionHandler:^(NSError * _Nullable error) { if (error) { - BNCLogError([NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]] error:error]; } else { - BNCLogDebug([NSString stringWithFormat:@"Update conversion value was successful for INSTALL Event"]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Update conversion value was successful for INSTALL Event"]]; } }]; } @@ -225,23 +222,23 @@ - (void)processResponse:(BNCServerResponse *)response error:(NSError *)error { BOOL lockWin = [[BNCSKAdNetwork sharedInstance] getLockedStatusFromDataResponse:data]; BOOL shouldCallUpdatePostback = [[BNCSKAdNetwork sharedInstance] shouldCallPostbackForDataResponse:data]; - BNCLogDebug([NSString stringWithFormat:@"SKAN 4.0 params - conversionValue:%@ coarseValue:%@, locked:%d, shouldCallPostback:%d, currentWindow:%d, firstAppLaunchTime: %@", conversionValue, coarseConversionValue, lockWin, shouldCallUpdatePostback, (int)preferenceHelper.skanCurrentWindow, preferenceHelper.firstAppLaunchTime]); + [[BranchLogger shared] logDebug: [NSString stringWithFormat:@"SKAN 4.0 params - conversionValue:%@ coarseValue:%@, locked:%d, shouldCallPostback:%d, currentWindow:%d, firstAppLaunchTime: %@", conversionValue, coarseConversionValue, lockWin, shouldCallUpdatePostback, (int)preferenceHelper.skanCurrentWindow, preferenceHelper.firstAppLaunchTime]]; if(shouldCallUpdatePostback){ [[BNCSKAdNetwork sharedInstance] updatePostbackConversionValue: conversionValue.longValue coarseValue:coarseConversionValue lockWindow:lockWin completionHandler:^(NSError * _Nullable error) { if (error) { - BNCLogError([NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]] error:error]; } else { - BNCLogDebug([NSString stringWithFormat:@"Update conversion value was successful. Conversion Value - %@", conversionValue]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Update conversion value was successful. Conversion Value - %@", conversionValue]]; } }]; } } else if (@available(iOS 15.4, macCatalyst 15.4, *)) { [[BNCSKAdNetwork sharedInstance] updatePostbackConversionValue:conversionValue.intValue completionHandler: ^(NSError *error){ if (error) { - BNCLogError([NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Update conversion value failed with error - %@", [error description]] error:error]; } else { - BNCLogDebug([NSString stringWithFormat:@"Update conversion value was successful. Conversion Value - %@", conversionValue]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Update conversion value was successful. Conversion Value - %@", conversionValue]]; } }]; } else { @@ -284,7 +281,7 @@ + (void) initialize { + (void) setWaitNeededForOpenResponseLock { @synchronized (self) { if (!openRequestWaitQueueIsSuspended) { - BNCLogDebugSDK(@"Suspended for openRequestWaitQueue."); + [[BranchLogger shared] logDebug:@"Suspended for openRequestWaitQueue."]; openRequestWaitQueueIsSuspended = YES; dispatch_suspend(openRequestWaitQueue); } @@ -292,16 +289,16 @@ + (void) setWaitNeededForOpenResponseLock { } + (void) waitForOpenResponseLock { - BNCLogDebugSDK(@"Waiting for openRequestWaitQueue."); + [[BranchLogger shared] logDebug:@"Waiting for openRequestWaitQueue."]; dispatch_sync(openRequestWaitQueue, ^ { - BNCLogDebugSDK(@"Finished waitForOpenResponseLock."); + [[BranchLogger shared] logDebug:@"Finished waitForOpenResponseLock."]; }); } + (void) releaseOpenResponseLock { @synchronized (self) { if (openRequestWaitQueueIsSuspended) { - BNCLogDebugSDK(@"Resuming openRequestWaitQueue."); + [[BranchLogger shared] logDebug:@"Resuming openRequestWaitQueue."]; openRequestWaitQueueIsSuspended = NO; dispatch_resume(openRequestWaitQueue); } diff --git a/Sources/BranchSDK/BranchPluginSupport.m b/Sources/BranchSDK/BranchPluginSupport.m index ca07797ed..c975d930b 100644 --- a/Sources/BranchSDK/BranchPluginSupport.m +++ b/Sources/BranchSDK/BranchPluginSupport.m @@ -11,7 +11,6 @@ #import "BNCDeviceInfo.h" #import "BNCPreferenceHelper.h" #import "Branch.h" -#import "BNCLog.h" #import "BNCConfig.h" @implementation BranchPluginSupport @@ -54,12 +53,6 @@ + (BranchPluginSupport *)instance { #pragma mark - Server URL methods -// With the change to support Apple's tracking domain feature, this API no longer works. See SDK-2118 -// Overrides base API URL -+ (void)setAPIUrl:(NSString *)url { - [[BNCPreferenceHelper sharedInstance] setBranchAPIURL:url]; -} - // Overrides base CDN URL + (void)setCDNBaseUrl:(NSString *)url { [[BNCPreferenceHelper sharedInstance] setPatternListURL:url]; diff --git a/Sources/BranchSDK/BranchQRCode.m b/Sources/BranchSDK/BranchQRCode.m index 6000e6a1a..1e55e35e4 100644 --- a/Sources/BranchSDK/BranchQRCode.m +++ b/Sources/BranchSDK/BranchQRCode.m @@ -13,7 +13,7 @@ #import "BranchConstants.h" #import "NSError+Branch.h" #import "UIViewController+Branch.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "BNCServerAPI.h" @interface BranchQRCode() @@ -35,11 +35,11 @@ - (instancetype) init { - (void) setMargin:(NSNumber *)margin { if (margin.intValue > 20) { margin = @(20); - BNCLogWarning(@"Margin was reduced to the maximum of 20."); + [[BranchLogger shared] logWarning:@"QR code margin was reduced to the maximum of 20."]; } if (margin.intValue < 1) { margin = @(1); - BNCLogWarning(@"Margin was increased to the minimum of 1."); + [[BranchLogger shared] logWarning:@"QR code margin was increased to the minimum of 1."]; } _margin = margin; } @@ -47,11 +47,11 @@ - (void) setMargin:(NSNumber *)margin { - (void) setWidth:(NSNumber *)width { if (width.intValue > 2000) { width = @(2000); - BNCLogWarning(@"Width was reduced to the maximum of 2000."); + [[BranchLogger shared] logWarning:@"QR code width was reduced to the maximum of 2000."]; } if (width.intValue < 300) { width = @(300); - BNCLogWarning(@"Width was increased to the minimum of 500."); + [[BranchLogger shared] logWarning:@"QR code width was increased to the minimum of 500."]; } _width = width; } @@ -73,7 +73,7 @@ - (void)getQRCodeAsData:(nullable BranchUniversalObject *)buo NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString: self.centerLogo]]; UIImage *image=[UIImage imageWithData:data]; if (image == nil) { - BNCLogWarning(@"QR code center logo was an invalid URL string."); + [[BranchLogger shared] logWarning:@"QR code center logo was an invalid URL string."]; } else { settings[@"center_logo_url"] = self.centerLogo; } @@ -137,14 +137,13 @@ - (void)callQRCodeAPI:(nullable NSDictionary *)params NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error]; [request setHTTPBody:postData]; - BNCLogDebug([NSString stringWithFormat:@"Network start operation %@.", request.URL.absoluteString]); - + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Network start operation %@.", request.URL.absoluteString]]; NSDate *startDate = [NSDate date]; NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { - BNCLogError([NSString stringWithFormat:@"QR Code Post Request Error: %@", [error localizedDescription]]); + [[BranchLogger shared] logError:[NSString stringWithFormat:@"QR Code Post Request Error: %@", [error localizedDescription]] error:error]; completion(nil, error); return; } @@ -153,25 +152,23 @@ - (void)callQRCodeAPI:(nullable NSDictionary *)params if (httpResponse.statusCode == 200) { - BNCLogDebug([NSString stringWithFormat:@"Network finish operation %@ %1.3fs. Status %ld.", - request.URL.absoluteString, - [[NSDate date] timeIntervalSinceDate:startDate], - (long)httpResponse.statusCode]); + [[BranchLogger shared] logDebug:[NSString stringWithFormat:@"Network finish operation %@ %1.3fs. Status %ld.", + request.URL.absoluteString, + [[NSDate date] timeIntervalSinceDate:startDate], + (long)httpResponse.statusCode]]; completion(data, nil); } else { NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; - BNCLogError([NSString stringWithFormat:@"Network finish operation %@ %1.3fs. Status %ld error %@.\n%@.", - request.URL.absoluteString, - [[NSDate date] timeIntervalSinceDate:startDate], - (long)httpResponse.statusCode, - error, - responseDictionary]); - error = [NSError branchErrorWithCode: BNCBadRequestError localizedMessage: responseDictionary[@"message"]]; - + [[BranchLogger shared] logError:[NSString stringWithFormat:@"Network finish operation %@ %1.3fs. Status %ld error %@.\n%@.", + request.URL.absoluteString, + [[NSDate date] timeIntervalSinceDate:startDate], + (long)httpResponse.statusCode, + error, + responseDictionary] error:error]; completion(nil, error); } }]; @@ -208,7 +205,7 @@ - (void)showShareSheetWithQRCodeFromViewController:(nullable UIViewController *) } if (!presentingViewController) { - BNCLogError(@"No view controller is present to show the share sheet. Not showing sheet."); + [[BranchLogger shared] logError:@"No view controller is present to show the share sheet. Not showing sheet." error:nil]; return; } diff --git a/Sources/BranchSDK/BranchScene.m b/Sources/BranchSDK/BranchScene.m index eca3d011a..f6c8480b4 100644 --- a/Sources/BranchSDK/BranchScene.m +++ b/Sources/BranchSDK/BranchScene.m @@ -8,7 +8,7 @@ #import "BranchScene.h" #import "Branch.h" -#import "BNCLog.h" +#import "BranchLogger.h" @implementation BranchScene @@ -40,7 +40,7 @@ - (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivi - (void)scene:(UIScene *)scene openURLContexts:(NSSet *)URLContexts NS_EXTENSION_UNAVAILABLE("BranchScene does not support Extensions") { if (URLContexts.count != 1) { - BNCLogWarning(@"Branch only supports a single URLContext"); + [[BranchLogger shared] logWarning:@"Branch only supports a single URLContext"]; } UIOpenURLContext *context = [URLContexts allObjects].firstObject; diff --git a/Sources/BranchSDK/BranchShareLink.m b/Sources/BranchSDK/BranchShareLink.m index c6f1eef7a..2cd4b874b 100644 --- a/Sources/BranchSDK/BranchShareLink.m +++ b/Sources/BranchSDK/BranchShareLink.m @@ -9,7 +9,7 @@ #import "BranchShareLink.h" #import "BranchConstants.h" #import "BranchActivityItemProvider.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "Branch.h" #import "BranchEvent.h" #import "UIViewController+Branch.h" @@ -115,10 +115,7 @@ - (void) shareDidComplete:(BOOL)completed activityError:(NSError*)error { // Make sure we can share if (!(self.universalObject.canonicalIdentifier || self.universalObject.canonicalUrl || self.universalObject.title)) { - BNCLogWarning(@"A canonicalIdentifier, canonicalURL, or title are required to uniquely" - " identify content. In order to not break the end user experience with sharing," - " Branch SDK will proceed to create a URL, but content analytics may not properly" - " include this URL."); + [[BranchLogger shared] logWarning:@"A canonicalIdentifier, canonicalURL, or title are required to uniquely identify content. In order to not break the end user experience with sharing, Branch SDK will proceed to create a URL, but content analytics may not properly include this URL."]; } self.serverParameters = [[self.universalObject getParamsForServerRequestWithAddedLinkProperties:self.linkProperties] mutableCopy]; @@ -204,9 +201,7 @@ - (void) presentActivityViewControllerFromViewController:(UIViewController*_Null [shareViewController setValue:emailSubject forKey:@"subject"]; } @catch (NSException*) { - BNCLogWarning( - @"Unable to setValue 'emailSubject' forKey 'subject' on UIActivityViewController." - ); + [[BranchLogger shared] logWarning: @"Unable to setValue 'emailSubject' forKey 'subject' on UIActivityViewController."]; } } @@ -221,7 +216,7 @@ - (void) presentActivityViewControllerFromViewController:(UIViewController*_Null } if (!presentingViewController) { - BNCLogError(@"No view controller is present to show the share sheet. Not showing sheet."); + [[BranchLogger shared] logError:@"No view controller is present to show the share sheet. Not showing sheet." error:nil]; return; } diff --git a/Sources/BranchSDK/BranchShortUrlSyncRequest.m b/Sources/BranchSDK/BranchShortUrlSyncRequest.m index 2526af572..8f026b8df 100644 --- a/Sources/BranchSDK/BranchShortUrlSyncRequest.m +++ b/Sources/BranchSDK/BranchShortUrlSyncRequest.m @@ -11,7 +11,7 @@ #import "BNCEncodingUtils.h" #import "BranchConstants.h" #import "BNCConfig.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "BNCRequestFactory.h" #import "BNCServerAPI.h" @@ -62,8 +62,8 @@ - (BNCServerResponse *)makeRequest:(BNCServerInterface *)serverInterface key:(NS - (NSString *)processResponse:(BNCServerResponse *)response { if (![response.statusCode isEqualToNumber:@200]) { - BNCLogWarning([NSString stringWithFormat:@"Short link creation received HTTP status code %@. Using long link instead.", - response.statusCode]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"Short link creation received HTTP status code %@. Using long link instead.", + response.statusCode]]; NSString *failedUrl = nil; NSString *userUrl = [BNCPreferenceHelper sharedInstance].userUrl; if (userUrl) { diff --git a/Sources/BranchSDK/BranchUniversalObject.m b/Sources/BranchSDK/BranchUniversalObject.m index d94002ad5..a21348065 100644 --- a/Sources/BranchSDK/BranchUniversalObject.m +++ b/Sources/BranchSDK/BranchUniversalObject.m @@ -9,7 +9,7 @@ #import "BranchUniversalObject.h" #import "NSError+Branch.h" #import "BranchConstants.h" -#import "BNCLog.h" +#import "BranchLogger.h" #import "BNCEncodingUtils.h" #import "Branch.h" #import "BranchEvent.h" @@ -331,7 +331,7 @@ - (void)registerViewWithCallback:(callbackWithParams)callback { if (!self.canonicalIdentifier && !self.title) { NSString *message = @"Could not register view."; NSError *error = [NSError branchErrorWithCode:BNCContentIdentifierError localizedMessage:message]; - BNCLogWarning([NSString stringWithFormat:@"%@", error]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"%@", error]]; if (callback) callback([[NSDictionary alloc] init], error); return; } @@ -350,7 +350,8 @@ - (void)registerViewWithCallback:(callbackWithParams)callback { - (NSString *)getShortUrlWithLinkProperties:(BranchLinkProperties *)linkProperties { if (!self.canonicalIdentifier && !self.title) { - BNCLogWarning(@"A canonicalIdentifier or title are required to uniquely identify content, so could not generate a URL."); + [[BranchLogger shared] logWarning:@"A canonicalIdentifier or title are required to uniquely identify content, so could not generate a URL."]; + return nil; } @@ -368,7 +369,7 @@ - (void)getShortUrlWithLinkProperties:(BranchLinkProperties *)linkProperties and if (!self.canonicalIdentifier && !self.title) { NSString *message = @"Could not generate a URL."; NSError *error = [NSError branchErrorWithCode:BNCContentIdentifierError localizedMessage:message]; - BNCLogWarning([NSString stringWithFormat:@"%@", error]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"%@", error]]; if (callback) callback([BNCPreferenceHelper sharedInstance].userUrl, error); return; } @@ -388,7 +389,7 @@ - (NSString *)getShortUrlWithLinkPropertiesAndIgnoreFirstClick:(BranchLinkProper if (!self.canonicalIdentifier && !self.title) { NSString *message = @"Could not generate a URL."; NSError *error = [NSError branchErrorWithCode:BNCContentIdentifierError localizedMessage:message]; - BNCLogWarning([NSString stringWithFormat:@"%@", error]); + [[BranchLogger shared] logWarning:[NSString stringWithFormat:@"%@", error]]; return nil; } diff --git a/Sources/BranchSDK/Private/BNCServerAPI.h b/Sources/BranchSDK/Private/BNCServerAPI.h index 6fc218e65..c44c80577 100644 --- a/Sources/BranchSDK/Private/BNCServerAPI.h +++ b/Sources/BranchSDK/Private/BNCServerAPI.h @@ -33,6 +33,8 @@ NS_ASSUME_NONNULL_BEGIN // Used to enable unit tests without regard for ATT authorization status @property (nonatomic, assign, readwrite) BOOL automaticallyEnableTrackingDomain; +@property (nonatomic, copy, readwrite, nullable) NSString *customAPIURL; + @end NS_ASSUME_NONNULL_END diff --git a/Sources/BranchSDK/Private/BranchConstants.h b/Sources/BranchSDK/Private/BranchConstants.h index 013622446..da64586c4 100644 --- a/Sources/BranchSDK/Private/BranchConstants.h +++ b/Sources/BranchSDK/Private/BranchConstants.h @@ -163,3 +163,7 @@ extern NSString * const BRANCH_REQUEST_KEY_SKAN_POSTBACK_INDEX; extern NSString * const BRANCH_REQUEST_KEY_VALUE_POSTBACK_SEQUENCE_INDEX_0; extern NSString * const BRANCH_REQUEST_KEY_VALUE_POSTBACK_SEQUENCE_INDEX_1; extern NSString * const BRANCH_REQUEST_KEY_VALUE_POSTBACK_SEQUENCE_INDEX_2; + +extern NSString * const BRANCH_REQUEST_KEY_DMA_EEA; +extern NSString * const BRANCH_REQUEST_KEY_DMA_AD_PEROSALIZATION; +extern NSString * const BRANCH_REQUEST_KEY_DMA_AD_USER_DATA; diff --git a/Sources/BranchSDK/Public/BNCPreferenceHelper.h b/Sources/BranchSDK/Public/BNCPreferenceHelper.h index d7f56047b..8c0fba2d0 100644 --- a/Sources/BranchSDK/Public/BNCPreferenceHelper.h +++ b/Sources/BranchSDK/Public/BNCPreferenceHelper.h @@ -51,7 +51,6 @@ NSURL* /* _Nonnull */ BNCURLForBranchDirectory(void); @property (copy, nonatomic) NSString *lastSystemBuildVersion; @property (copy, nonatomic) NSString *browserUserAgentString; @property (copy, nonatomic) NSString *referringURL; -@property (copy, nonatomic) NSString *branchAPIURL; @property (assign, nonatomic) BOOL limitFacebookTracking; @property (strong, nonatomic) NSDate *previousAppBuildDate; @property (assign, nonatomic, readwrite) BOOL disableAdNetworkCallouts; @@ -73,11 +72,14 @@ NSURL* /* _Nonnull */ BNCURLForBranchDirectory(void); @property (strong, nonatomic) NSDate *firstAppLaunchTime; @property (assign, nonatomic) BOOL invokeRegisterApp; +@property (assign, nonatomic) BOOL eeaRegion; +@property (assign, nonatomic) BOOL adPersonalizationConsent; +@property (assign, nonatomic) BOOL adUserDataUsageConsent; + - (void) clearTrackingInformation; + (BNCPreferenceHelper *)sharedInstance; -- (void)setBranchAPIURL:(NSString *)url; - (void)setPatternListURL:(NSString *)url; - (void)setRequestMetadataKey:(NSString *)key value:(NSObject *)value; @@ -97,5 +99,6 @@ NSURL* /* _Nonnull */ BNCURLForBranchDirectory(void); - (NSMutableString*) sanitizedMutableBaseURL:(NSString*)baseUrl; - (void) synchronize; // Flushes preference queue to persistence. + (void) clearAll; +- (BOOL) eeaRegionInitialized; @end diff --git a/Sources/BranchSDK/Public/Branch.h b/Sources/BranchSDK/Public/Branch.h index d4ab71e10..1ef83a061 100644 --- a/Sources/BranchSDK/Public/Branch.h +++ b/Sources/BranchSDK/Public/Branch.h @@ -39,6 +39,7 @@ #import "BNCServerInterface.h" #import "BNCServerRequestQueue.h" +#import "BranchLogger.h" // Not used by Branch singleton public API //#import "BranchEvent.h" //#import "BranchScene.h" @@ -46,7 +47,6 @@ //#import "BranchQRCode.h" //#import "BNCConfig.h" //#import "NSError+Branch.h" -//#import "BNCLog.h" //#import "BranchConstants.h" //#import "UIViewController+Branch.h" @@ -564,9 +564,10 @@ extern NSString * __nonnull const BNCSpotlightFeature; ///-------------------- /** - Enable debug messages to NSLog. + Enable debug messages to os_log. */ - (void)enableLogging; +- (void)enableLoggingAtLevel:(BranchLogLevel)logLevel withCallback:(nullable BranchLogCallback)callback; /** Send requests to EU endpoints. @@ -576,13 +577,10 @@ extern NSString * __nonnull const BNCSpotlightFeature; - (void)useEUEndpoints; /** - setDebug is deprecated and all functionality has been disabled. - - If you wish to enable logging, please invoke enableLogging. - - If you wish to simulate installs, please see add a Test Device (https://help.branch.io/using-branch/docs/adding-test-devices) then reset your test device's data (https://help.branch.io/using-branch/docs/adding-test-devices#section-resetting-your-test-device-data). - */ -- (void)setDebug __attribute__((deprecated(("setDebug is replaced by enableLogging and test devices. https://help.branch.io/using-branch/docs/adding-test-devices")))); +Sets a custom base URL for all calls to the Branch API. +@param url Base URL that the Branch API will use. +*/ ++ (void)setAPIUrl:(NSString *)url; /** @brief Use the `validateSDKIntegration` method as a debugging aid to assure that you've @@ -763,8 +761,6 @@ extern NSString * __nonnull const BNCSpotlightFeature; */ - (void)accountForFacebookSDKPreventingAppLaunch __attribute__((deprecated(("Please ensure application:didFinishLaunchingWithOptions: always returns YES/true instead of using this method. It will be removed in a future release.")))); -- (void)suppressWarningLogs __attribute__((deprecated(("suppressWarningLogs is deprecated and all functionality has been disabled. If you wish to turn off all logging, please invoke BNCLogSetDisplayLevel(BNCLogLevelNone).")))); - /** For use by other Branch SDKs @@ -834,6 +830,16 @@ extern NSString * __nonnull const BNCSpotlightFeature; */ + (void) setReferrerGbraidValidityWindow:(NSTimeInterval) validityWindow; +/* + + Sets the value of parameters required by Google Conversion APIs for DMA Compliance in EEA region. + + @param eeaRegion -(BOOL) If European regulations, including the DMA, apply to this user and conversion. + @param adPersonalizationConsent - (BOOL) If End user has granted/denied ads personalization consent. + @param adUserDataUsageConsent - (BOOL) If User has granted/denied consent for 3P transmission of user level data for ads + */ ++ (void) setDMAParamsForEEA:(BOOL) eeaRegion AdPersonalizationConsent:(BOOL) adPersonalizationConsent AdUserDataUsageConsent:(BOOL) adUserDataUsageConsent; + #pragma mark - Session Item methods ///-------------------- diff --git a/Sources/BranchSDK/Public/BranchLogger.h b/Sources/BranchSDK/Public/BranchLogger.h new file mode 100644 index 000000000..70c6e55b1 --- /dev/null +++ b/Sources/BranchSDK/Public/BranchLogger.h @@ -0,0 +1,42 @@ +// +// BranchLogger.h +// Branch +// +// Created by Nipun Singh on 2/1/24. +// Copyright © 2024 Branch, Inc. All rights reserved. +// + +#import + +typedef NS_ENUM(NSUInteger, BranchLogLevel) { + BranchLogLevelVerbose, + BranchLogLevelDebug, + BranchLogLevelInfo, + BranchLogLevelWarning, + BranchLogLevelError, +}; + +typedef void(^BranchLogCallback)(NSString * _Nonnull message, BranchLogLevel logLevel, NSError * _Nullable error); + +NS_ASSUME_NONNULL_BEGIN + +@interface BranchLogger : NSObject + +@property (nonatomic, assign) BOOL loggingEnabled; +@property (nonatomic, assign) BOOL includeCallerDetails; +@property (nonatomic, copy, nullable) BranchLogCallback logCallback; +@property (nonatomic, assign) BranchLogLevel logLevelThreshold; + ++ (instancetype _Nonnull)shared; + +- (void)disableCallerDetails; + +- (void)logError:(NSString * _Nonnull)message error:(NSError * _Nullable)error; +- (void)logWarning:(NSString * _Nonnull)message; +- (void)logInfo:(NSString * _Nonnull)message; +- (void)logDebug:(NSString * _Nonnull)message; +- (void)logVerbose:(NSString * _Nonnull)message; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sources/BranchSDK/Public/BranchPluginSupport.h b/Sources/BranchSDK/Public/BranchPluginSupport.h index d2f4cfe20..e344dcc8b 100644 --- a/Sources/BranchSDK/Public/BranchPluginSupport.h +++ b/Sources/BranchSDK/Public/BranchPluginSupport.h @@ -14,12 +14,6 @@ NS_ASSUME_NONNULL_BEGIN + (BranchPluginSupport *)instance; -/** -Sets a custom base URL for all calls to the Branch API. -@param url Base URL that the Branch API will use. -*/ -+ (void)setAPIUrl:(NSString *)url; - /** Sets a custom CDN base URL. @param url Base URL for CDN endpoints. diff --git a/Sources/BranchSDK/Public/BranchSDK.h b/Sources/BranchSDK/Public/BranchSDK.h index 4ecdabebe..843bcf8ae 100644 --- a/Sources/BranchSDK/Public/BranchSDK.h +++ b/Sources/BranchSDK/Public/BranchSDK.h @@ -28,6 +28,7 @@ FOUNDATION_EXPORT const unsigned char BranchSDKVersionString[]; #import "BranchLastAttributedTouchData.h" #import "BranchDeepLinkingController.h" +#import "BranchLogger.h" #if !TARGET_OS_TV // tvOS does not support these features