FIRDynamicLinks.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. /*
  2. * Copyright 2018 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <TargetConditionals.h>
  17. #if TARGET_OS_IOS
  18. #import "FirebaseDynamicLinks/Sources/Public/FirebaseDynamicLinks/FIRDynamicLinks.h"
  19. #import <UIKit/UIKit.h>
  20. #ifdef FIRDynamicLinks3P
  21. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  22. #import "FirebaseDynamicLinks/Sources/FIRDLScionLogging.h"
  23. #import "Interop/Analytics/Public/FIRAnalyticsInterop.h"
  24. #else
  25. #import "FirebaseCore/Sources/Public/FirebaseCore/FIRVersion.h"
  26. #endif
  27. #ifdef FIRDynamicLinks3P
  28. #import "FirebaseDynamicLinks/Sources/FDLURLComponents/FDLURLComponents+Private.h"
  29. #endif
  30. #import "FirebaseDynamicLinks/Sources/FIRDLRetrievalProcessFactory.h"
  31. #import "FirebaseDynamicLinks/Sources/FIRDLRetrievalProcessProtocols.h"
  32. #import "FirebaseDynamicLinks/Sources/FIRDLRetrievalProcessResult.h"
  33. #import "FirebaseDynamicLinks/Sources/FIRDynamicLink+Private.h"
  34. #import "FirebaseDynamicLinks/Sources/FIRDynamicLinkNetworking.h"
  35. #import "FirebaseDynamicLinks/Sources/FIRDynamicLinks+FirstParty.h"
  36. #import "FirebaseDynamicLinks/Sources/FIRDynamicLinks+Private.h"
  37. #import "FirebaseDynamicLinks/Sources/Logging/FDLLogging.h"
  38. #import "FirebaseDynamicLinks/Sources/Utilities/FDLUtilities.h"
  39. // We should only read the deeplink after install once. We use the following key to store the state
  40. // in the user defaults.
  41. NSString *const kFIRDLReadDeepLinkAfterInstallKey =
  42. @"com.google.appinvite.readDeeplinkAfterInstall";
  43. // We should only open url once. We use the following key to store the state in the user defaults.
  44. static NSString *const kFIRDLOpenURLKey = @"com.google.appinvite.openURL";
  45. // Custom domains to be allowed are optionally added as an array to the info.plist.
  46. static NSString *const kInfoPlistCustomDomainsKey = @"FirebaseDynamicLinksCustomDomains";
  47. NS_ASSUME_NONNULL_BEGIN
  48. @interface FIRDynamicLinks () <FIRDLRetrievalProcessDelegate>
  49. // API Key for API access.
  50. @property(nonatomic, copy) NSString *APIKey;
  51. // Custom URL scheme.
  52. @property(nonatomic, copy) NSString *URLScheme;
  53. // Networking object for Dynamic Links
  54. @property(nonatomic, readonly) FIRDynamicLinkNetworking *dynamicLinkNetworking;
  55. @property(atomic, assign) BOOL retrievingPendingDynamicLink;
  56. @end
  57. #ifdef FIRDynamicLinks3P
  58. // Error code from FDL.
  59. static const NSInteger FIRErrorCodeDurableDeepLinkFailed = -119;
  60. @interface FIRDynamicLinks () {
  61. /// Stored Analytics reference, if it exists.
  62. id<FIRAnalyticsInterop> _Nullable _analytics;
  63. }
  64. @end
  65. // DynamicLinks doesn't provide any functionality to other components,
  66. // so it provides a private, empty protocol that it conforms to and use it for registration.
  67. @protocol FIRDynamicLinksInstanceProvider
  68. @end
  69. @interface FIRDynamicLinks () <FIRDynamicLinksInstanceProvider, FIRLibrary>
  70. @end
  71. #endif
  72. @implementation FIRDynamicLinks {
  73. // User defaults passed.
  74. NSUserDefaults *_userDefaults;
  75. FIRDynamicLinkNetworking *_dynamicLinkNetworking;
  76. id<FIRDLRetrievalProcessProtocol> _retrievalProcess;
  77. }
  78. #pragma mark - Object lifecycle
  79. #ifdef FIRDynamicLinks3P
  80. + (void)load {
  81. [FIRApp registerInternalLibrary:self withName:@"fire-dl"];
  82. }
  83. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  84. // Product requirement is enforced by CocoaPod. Not technical requirement for analytics.
  85. FIRDependency *analyticsDep = [FIRDependency dependencyWithProtocol:@protocol(FIRAnalyticsInterop)
  86. isRequired:NO];
  87. FIRComponentCreationBlock creationBlock =
  88. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  89. // Don't return an instance when it's not the default app.
  90. if (!container.app.isDefaultApp) {
  91. // Only configure for the default FIRApp.
  92. FDLLog(FDLLogLevelInfo, FDLLogIdentifierSetupNonDefaultApp,
  93. @"Firebase Dynamic Links only "
  94. "works with the default app.");
  95. return nil;
  96. }
  97. // Ensure it's cached so it returns the same instance every time dynamicLinks is called.
  98. *isCacheable = YES;
  99. id<FIRAnalyticsInterop> analytics = FIR_COMPONENT(FIRAnalyticsInterop, container);
  100. FIRDynamicLinks *dynamicLinks = [[FIRDynamicLinks alloc] initWithAnalytics:analytics];
  101. [dynamicLinks configureDynamicLinks:container.app];
  102. if ([FIRDynamicLinks isAutomaticRetrievalEnabled]) {
  103. [dynamicLinks checkForPendingDynamicLink];
  104. }
  105. return dynamicLinks;
  106. };
  107. FIRComponent *dynamicLinksProvider =
  108. [FIRComponent componentWithProtocol:@protocol(FIRDynamicLinksInstanceProvider)
  109. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  110. dependencies:@[ analyticsDep ]
  111. creationBlock:creationBlock];
  112. return @[ dynamicLinksProvider ];
  113. }
  114. - (void)configureDynamicLinks:(FIRApp *)app {
  115. FIROptions *options = app.options;
  116. NSError *error;
  117. NSMutableString *errorDescription;
  118. NSString *urlScheme;
  119. if (options.APIKey.length == 0) {
  120. errorDescription = [@"API key must not be nil or empty." mutableCopy];
  121. }
  122. if (!errorDescription) {
  123. // setup FDL if no error detected
  124. urlScheme = options.deepLinkURLScheme ?: [NSBundle mainBundle].bundleIdentifier;
  125. [self setUpWithLaunchOptions:nil apiKey:options.APIKey urlScheme:urlScheme userDefaults:nil];
  126. } else {
  127. NSString *description =
  128. [NSString stringWithFormat:@"Configuration failed for service DynamicLinks."];
  129. NSDictionary *errorDict = @{
  130. NSLocalizedDescriptionKey : description,
  131. NSLocalizedFailureReasonErrorKey : errorDescription
  132. };
  133. error = [NSError errorWithDomain:kFirebaseDurableDeepLinkErrorDomain
  134. code:FIRErrorCodeDurableDeepLinkFailed
  135. userInfo:errorDict];
  136. }
  137. if (error) {
  138. NSString *message = nil;
  139. if (options.usingOptionsFromDefaultPlist) {
  140. // Configured using plist file
  141. message = [NSString
  142. stringWithFormat:
  143. @"Firebase Dynamic Links has stopped your project "
  144. @"because there are missing or incorrect values provided in %@.%@ that may "
  145. @"prevent your app from behaving as expected:\n\n"
  146. @"Error: %@\n\n"
  147. @"Please fix these issues to ensure that Firebase is correctly configured in "
  148. @"your project.",
  149. kServiceInfoFileName, kServiceInfoFileType, error.localizedFailureReason];
  150. } else {
  151. // Configured manually
  152. message = [NSString
  153. stringWithFormat:
  154. @"Firebase Dynamic Links has stopped your project "
  155. @"because there are incorrect values provided in Firebase's configuration "
  156. @"options that may prevent your app from behaving as expected:\n\n"
  157. @"Error: %@\n\n"
  158. @"Please fix these issues to ensure that Firebase is correctly configured in "
  159. @"your project.",
  160. error.localizedFailureReason];
  161. }
  162. [NSException raise:kFirebaseDurableDeepLinkErrorDomain format:@"%@", message];
  163. }
  164. [self checkForCustomDomainEntriesInInfoPlist];
  165. }
  166. - (instancetype)initWithAnalytics:(nullable id<FIRAnalyticsInterop>)analytics {
  167. self = [super init];
  168. if (self) {
  169. _analytics = analytics;
  170. }
  171. return self;
  172. }
  173. + (instancetype)dynamicLinks {
  174. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  175. id<FIRDynamicLinksInstanceProvider> instance =
  176. FIR_COMPONENT(FIRDynamicLinksInstanceProvider, defaultApp.container);
  177. return (FIRDynamicLinks *)instance;
  178. }
  179. #else
  180. + (instancetype)dynamicLinks {
  181. static FIRDynamicLinks *dynamicLinks;
  182. static dispatch_once_t onceToken;
  183. dispatch_once(&onceToken, ^{
  184. dynamicLinks = [[self alloc] init];
  185. });
  186. return dynamicLinks;
  187. }
  188. #endif
  189. #pragma mark - Custom domains
  190. - (instancetype)init {
  191. self = [super init];
  192. if (self) {
  193. [self checkForCustomDomainEntriesInInfoPlist];
  194. }
  195. return self;
  196. }
  197. // Check for custom domains entry in PLIST file.
  198. - (void)checkForCustomDomainEntriesInInfoPlist {
  199. // Check to see if FirebaseDynamicLinksCustomDomains array is present.
  200. NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary;
  201. NSArray *customDomains = infoDictionary[kInfoPlistCustomDomainsKey];
  202. if (customDomains) {
  203. FIRDLAddToAllowListForCustomDomainsArray(customDomains);
  204. }
  205. }
  206. #pragma mark - First party interface
  207. - (BOOL)setUpWithLaunchOptions:(nullable NSDictionary *)launchOptions
  208. apiKey:(NSString *)apiKey
  209. urlScheme:(nullable NSString *)urlScheme
  210. userDefaults:(nullable NSUserDefaults *)userDefaults {
  211. if (apiKey == nil) {
  212. FDLLog(FDLLogLevelError, FDLLogIdentifierSetupNilAPIKey, @"API Key must not be nil.");
  213. return NO;
  214. }
  215. _APIKey = [apiKey copy];
  216. _URLScheme = urlScheme.length ? [urlScheme copy] : [NSBundle mainBundle].bundleIdentifier;
  217. if (!userDefaults) {
  218. _userDefaults = [NSUserDefaults standardUserDefaults];
  219. } else {
  220. _userDefaults = userDefaults;
  221. }
  222. NSURL *url = launchOptions[UIApplicationLaunchOptionsURLKey];
  223. if (url) {
  224. if ([self canParseCustomSchemeURL:url] || [self canParseUniversalLinkURL:url]) {
  225. // Make sure we don't call |checkForPendingDynamicLink| again if
  226. // a strong deep link is found.
  227. [_userDefaults setBool:YES forKey:kFIRDLReadDeepLinkAfterInstallKey];
  228. }
  229. }
  230. return YES;
  231. }
  232. - (void)checkForPendingDynamicLinkUsingExperimentalRetrievalProcess {
  233. [self checkForPendingDynamicLink];
  234. }
  235. - (void)checkForPendingDynamicLink {
  236. // Make sure this method is called only once after the application was installed.
  237. // kFIRDLOpenURLKey marks checkForPendingDynamic link had been called already so no need to do it
  238. // again. kFIRDLReadDeepLinkAfterInstallKey marks we have already read a deeplink after the
  239. // install and so no need to do check for pending dynamic link.
  240. BOOL appInviteDeepLinkRead = [_userDefaults boolForKey:kFIRDLOpenURLKey] ||
  241. [_userDefaults boolForKey:kFIRDLReadDeepLinkAfterInstallKey];
  242. if (appInviteDeepLinkRead || self.retrievingPendingDynamicLink) {
  243. NSString *errorDescription =
  244. appInviteDeepLinkRead ? NSLocalizedString(@"Link was already retrieved", @"Error message")
  245. : NSLocalizedString(@"Already retrieving link", @"Error message");
  246. [self handlePendingDynamicLinkRetrievalFailureWithErrorCode:-1
  247. errorDescription:errorDescription
  248. underlyingError:nil];
  249. return;
  250. }
  251. self.retrievingPendingDynamicLink = YES;
  252. FIRDLRetrievalProcessFactory *factory =
  253. [[FIRDLRetrievalProcessFactory alloc] initWithNetworkingService:self.dynamicLinkNetworking
  254. URLScheme:_URLScheme
  255. APIKey:_APIKey
  256. FDLSDKVersion:FIRFirebaseVersion()
  257. delegate:self];
  258. _retrievalProcess = [factory automaticRetrievalProcess];
  259. [_retrievalProcess retrievePendingDynamicLink];
  260. }
  261. // Disable deprecated warning for internal methods.
  262. #pragma clang diagnostic push
  263. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  264. + (instancetype)sharedInstance {
  265. return [self dynamicLinks];
  266. }
  267. - (BOOL)setUpWithLaunchOptions:(nullable NSDictionary *)launchOptions
  268. apiKey:(NSString *)apiKey
  269. clientID:(NSString *)clientID
  270. urlScheme:(nullable NSString *)urlScheme
  271. userDefaults:(nullable NSUserDefaults *)userDefaults {
  272. return [self setUpWithLaunchOptions:launchOptions
  273. apiKey:apiKey
  274. urlScheme:urlScheme
  275. userDefaults:userDefaults];
  276. }
  277. - (void)checkForPendingDeepLink {
  278. [self checkForPendingDynamicLink];
  279. }
  280. - (nullable FIRDynamicLink *)deepLinkFromCustomSchemeURL:(NSURL *)url {
  281. return [self dynamicLinkFromCustomSchemeURL:url];
  282. }
  283. - (nullable FIRDynamicLink *)deepLinkFromUniversalLinkURL:(NSURL *)url {
  284. return [self dynamicLinkFromUniversalLinkURL:url];
  285. }
  286. - (BOOL)shouldHandleDeepLinkFromCustomSchemeURL:(NSURL *)url {
  287. return [self shouldHandleDynamicLinkFromCustomSchemeURL:url];
  288. }
  289. #pragma clang pop
  290. #pragma mark - Public interface
  291. - (BOOL)shouldHandleDynamicLinkFromCustomSchemeURL:(NSURL *)url {
  292. // Return NO if the URL scheme does not match.
  293. if (![self canParseCustomSchemeURL:url]) {
  294. return NO;
  295. }
  296. // We can handle "/link" and "/link/dismiss". The latter will return a nil deep link.
  297. return ([url.path hasPrefix:@"/link"] && [url.host isEqualToString:@"google"]);
  298. }
  299. - (nullable FIRDynamicLink *)dynamicLinkFromCustomSchemeURL:(NSURL *)url {
  300. // Return nil if the URL scheme does not match.
  301. if (![self canParseCustomSchemeURL:url]) {
  302. return nil;
  303. }
  304. if ([url.path isEqualToString:@"/link"] && [url.host isEqualToString:@"google"]) {
  305. // This URL is a callback url from a fingerprint match
  306. // Extract information from query.
  307. NSString *query = url.query;
  308. NSDictionary *parameters = FIRDLDictionaryFromQuery(query);
  309. // As long as the deepLink has some parameter, return it.
  310. if (parameters.count > 0) {
  311. FIRDynamicLink *dynamicLink =
  312. [[FIRDynamicLink alloc] initWithParametersDictionary:parameters];
  313. #ifdef GIN_SCION_LOGGING
  314. if (dynamicLink.url) {
  315. BOOL isFirstOpen = ![_userDefaults boolForKey:kFIRDLReadDeepLinkAfterInstallKey];
  316. FIRDLLogEvent event = isFirstOpen ? FIRDLLogEventFirstOpen : FIRDLLogEventAppOpen;
  317. FIRDLLogEventToScion(event, parameters[kFIRDLParameterSource],
  318. parameters[kFIRDLParameterMedium], parameters[kFIRDLParameterCampaign],
  319. _analytics);
  320. }
  321. #endif
  322. // Make sure we don't call |checkForPendingDynamicLink| again if we did this already.
  323. if ([_userDefaults boolForKey:kFIRDLOpenURLKey]) {
  324. [_userDefaults setBool:YES forKey:kFIRDLReadDeepLinkAfterInstallKey];
  325. }
  326. return dynamicLink;
  327. }
  328. }
  329. return nil;
  330. }
  331. - (nullable FIRDynamicLink *)
  332. dynamicLinkInternalFromUniversalLinkURL:(NSURL *)url
  333. completion:
  334. (nullable FIRDynamicLinkUniversalLinkHandler)completion {
  335. // Make sure the completion is always called on the main queue.
  336. FIRDynamicLinkUniversalLinkHandler mainQueueCompletion =
  337. ^(FIRDynamicLink *_Nullable dynamicLink, NSError *_Nullable error) {
  338. if (completion) {
  339. dispatch_async(dispatch_get_main_queue(), ^{
  340. completion(dynamicLink, error);
  341. });
  342. }
  343. };
  344. if ([self canParseUniversalLinkURL:url]) {
  345. if (url.query.length > 0) {
  346. NSDictionary<NSString *, NSString *> *parameters = FIRDLDictionaryFromQuery(url.query);
  347. if (parameters[kFIRDLParameterLink]) {
  348. NSString *urlString = parameters[kFIRDLParameterLink];
  349. NSURL *deepLinkURL = [NSURL URLWithString:urlString];
  350. if (deepLinkURL) {
  351. FIRDynamicLink *dynamicLink = [[FIRDynamicLink alloc] initWithParametersDictionary:@{
  352. kFIRDLParameterDeepLinkIdentifier : urlString,
  353. kFIRDLParameterCampaign : parameters[kFIRDLParameterCampaign] ?: [NSNull null],
  354. kFIRDLParameterContent : parameters[kFIRDLParameterContent] ?: [NSNull null],
  355. kFIRDLParameterMedium : parameters[kFIRDLParameterMedium] ?: [NSNull null],
  356. kFIRDLParameterSource : parameters[kFIRDLParameterSource] ?: [NSNull null],
  357. kFIRDLParameterTerm : parameters[kFIRDLParameterTerm] ?: [NSNull null],
  358. kFIRDLParameterMinimumAppVersion : parameters[kFIRDLParameterMinimumAppVersion]
  359. ?: [NSNull null],
  360. }];
  361. dynamicLink.matchType = FIRDLMatchTypeUnique;
  362. // Call resolveShortLink:completion: to do logging.
  363. // TODO: Create dedicated logging function to prevent this.
  364. [self.dynamicLinkNetworking
  365. resolveShortLink:url
  366. FDLSDKVersion:FIRFirebaseVersion()
  367. completion:^(NSURL *_Nullable resolverURL, NSError *_Nullable resolverError) {
  368. mainQueueCompletion(dynamicLink, resolverError);
  369. }];
  370. #ifdef GIN_SCION_LOGGING
  371. FIRDLLogEventToScion(FIRDLLogEventAppOpen, parameters[kFIRDLParameterSource],
  372. parameters[kFIRDLParameterMedium],
  373. parameters[kFIRDLParameterCampaign], _analytics);
  374. #endif
  375. return dynamicLink;
  376. }
  377. }
  378. }
  379. }
  380. mainQueueCompletion(
  381. nil, [[NSError alloc] initWithDomain:@"com.firebase.dynamicLinks"
  382. code:1
  383. userInfo:@{
  384. NSLocalizedFailureReasonErrorKey :
  385. @"Universal link URL could not be parsed by Dynamic Links."
  386. }]);
  387. return nil;
  388. }
  389. - (nullable FIRDynamicLink *)dynamicLinkFromUniversalLinkURL:(NSURL *)url {
  390. return [self dynamicLinkInternalFromUniversalLinkURL:url completion:nil];
  391. }
  392. - (void)dynamicLinkFromUniversalLinkURL:(NSURL *)url
  393. completion:(FIRDynamicLinkUniversalLinkHandler)completion {
  394. [self dynamicLinkInternalFromUniversalLinkURL:url completion:completion];
  395. }
  396. - (BOOL)handleUniversalLink:(NSURL *)universalLinkURL
  397. completion:(FIRDynamicLinkUniversalLinkHandler)completion {
  398. if ([self matchesShortLinkFormat:universalLinkURL]) {
  399. __weak __typeof__(self) weakSelf = self;
  400. [self resolveShortLink:universalLinkURL
  401. completion:^(NSURL *url, NSError *error) {
  402. __typeof__(self) strongSelf = weakSelf;
  403. if (strongSelf) {
  404. FIRDynamicLink *dynamicLink = [strongSelf dynamicLinkFromCustomSchemeURL:url];
  405. dispatch_async(dispatch_get_main_queue(), ^{
  406. completion(dynamicLink, error);
  407. });
  408. } else {
  409. completion(nil, nil);
  410. }
  411. }];
  412. return YES;
  413. } else {
  414. [self dynamicLinkFromUniversalLinkURL:universalLinkURL completion:completion];
  415. BOOL canHandleUniversalLink =
  416. [self canParseUniversalLinkURL:universalLinkURL] && universalLinkURL.query.length > 0 &&
  417. FIRDLDictionaryFromQuery(universalLinkURL.query)[kFIRDLParameterLink];
  418. return canHandleUniversalLink;
  419. }
  420. }
  421. - (void)resolveShortLink:(NSURL *)url completion:(FIRDynamicLinkResolverHandler)completion {
  422. [self.dynamicLinkNetworking resolveShortLink:url
  423. FDLSDKVersion:FIRFirebaseVersion()
  424. completion:completion];
  425. }
  426. - (BOOL)matchesShortLinkFormat:(NSURL *)url {
  427. return FIRDLMatchesShortLinkFormat(url);
  428. }
  429. #pragma mark - Private interface
  430. + (BOOL)isAutomaticRetrievalEnabled {
  431. id retrievalEnabledValue =
  432. [[NSBundle mainBundle] infoDictionary][@"FirebaseDeepLinkAutomaticRetrievalEnabled"];
  433. if ([retrievalEnabledValue respondsToSelector:@selector(boolValue)]) {
  434. return [retrievalEnabledValue boolValue];
  435. }
  436. return YES;
  437. }
  438. #pragma mark - Internal methods
  439. - (FIRDynamicLinkNetworking *)dynamicLinkNetworking {
  440. if (!_dynamicLinkNetworking) {
  441. _dynamicLinkNetworking = [[FIRDynamicLinkNetworking alloc] initWithAPIKey:_APIKey
  442. URLScheme:_URLScheme];
  443. }
  444. return _dynamicLinkNetworking;
  445. }
  446. - (BOOL)canParseCustomSchemeURL:(nullable NSURL *)url {
  447. if (url.scheme.length) {
  448. NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
  449. if ([url.scheme.lowercaseString isEqualToString:_URLScheme.lowercaseString] ||
  450. [url.scheme.lowercaseString isEqualToString:bundleIdentifier.lowercaseString]) {
  451. return YES;
  452. }
  453. }
  454. return NO;
  455. }
  456. - (BOOL)canParseUniversalLinkURL:(nullable NSURL *)url {
  457. return FIRDLCanParseUniversalLinkURL(url);
  458. }
  459. - (BOOL)handleIncomingCustomSchemeDeepLink:(NSURL *)url {
  460. return [self canParseCustomSchemeURL:url];
  461. }
  462. - (void)passRetrievedDynamicLinkToApplication:(NSURL *)url {
  463. id<UIApplicationDelegate> applicationDelegate = [UIApplication sharedApplication].delegate;
  464. if ([self isOpenUrlMethodPresentInAppDelegate:applicationDelegate]) {
  465. // pass url directly to application delegate to avoid hop into
  466. // iOS handling of the universal links
  467. [applicationDelegate application:[UIApplication sharedApplication] openURL:url options:@{}];
  468. return;
  469. }
  470. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  471. }
  472. - (BOOL)isOpenUrlMethodPresentInAppDelegate:(id<UIApplicationDelegate>)applicationDelegate {
  473. return applicationDelegate &&
  474. [applicationDelegate respondsToSelector:@selector(application:openURL:options:)];
  475. }
  476. - (void)handlePendingDynamicLinkRetrievalFailureWithErrorCode:(NSInteger)errorCode
  477. errorDescription:(NSString *)errorDescription
  478. underlyingError:(nullable NSError *)underlyingError {
  479. self.retrievingPendingDynamicLink = NO;
  480. }
  481. #pragma mark - FIRDLRetrievalProcessDelegate
  482. - (void)retrievalProcess:(id<FIRDLRetrievalProcessProtocol>)retrievalProcess
  483. completedWithResult:(FIRDLRetrievalProcessResult *)result {
  484. self.retrievingPendingDynamicLink = NO;
  485. _retrievalProcess = nil;
  486. if (![_userDefaults boolForKey:kFIRDLOpenURLKey]) {
  487. // Once we complete the Pending dynamic link retrieval, regardless of whether the retrieval is
  488. // success or failure, we don't want to do the retrieval again on next app start.
  489. // If we try to redo the retrieval again because of some error, the user will experience
  490. // unwanted deeplinking when they restart the app next time.
  491. [_userDefaults setBool:YES forKey:kFIRDLOpenURLKey];
  492. }
  493. NSURL *linkToPassToApp = [result URLWithCustomURLScheme:_URLScheme];
  494. [self passRetrievedDynamicLinkToApplication:linkToPassToApp];
  495. }
  496. #pragma mark - Diagnostics methods
  497. static NSString *kSelfDiagnoseOutputHeader =
  498. @"---- Firebase Dynamic Links diagnostic output start ----\n";
  499. static NSString *kSelfDiagnoseOutputFooter =
  500. @"---- Firebase Dynamic Links diagnostic output end ----\n";
  501. + (NSString *)genericDiagnosticInformation {
  502. NSMutableString *genericDiagnosticInfo = [[NSMutableString alloc] init];
  503. [genericDiagnosticInfo
  504. appendFormat:@"Firebase Dynamic Links framework version %@\n", FIRFirebaseVersion()];
  505. [genericDiagnosticInfo appendFormat:@"System information: OS %@, OS version %@, model %@\n",
  506. [UIDevice currentDevice].systemName,
  507. [UIDevice currentDevice].systemVersion,
  508. [UIDevice currentDevice].model];
  509. [genericDiagnosticInfo appendFormat:@"Current date %@\n", [NSDate date]];
  510. // TODO: bring this diagnostic info back when we shipped non-automatic retrieval
  511. // [genericDiagnosticInfo appendFormat:@"AutomaticRetrievalEnabled: %@\n",
  512. // [self isAutomaticRetrievalEnabled] ? @"YES" : @"NO"];
  513. // Disable deprecated warning for internal methods.
  514. #pragma clang diagnostic push
  515. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  516. [genericDiagnosticInfo appendFormat:@"Device locale %@ (raw %@), timezone %@\n",
  517. FIRDLDeviceLocale(), FIRDLDeviceLocaleRaw(),
  518. FIRDLDeviceTimezone()];
  519. #pragma clang pop
  520. return genericDiagnosticInfo;
  521. }
  522. + (NSString *)diagnosticAnalyzeEntitlements {
  523. NSString *embeddedMobileprovisionFilePath = [[[NSBundle mainBundle] bundlePath]
  524. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  525. NSError *error;
  526. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:embeddedMobileprovisionFilePath
  527. options:0
  528. error:&error];
  529. if (!profileData.length || error) {
  530. return @"\tSKIPPED: Not able to read entitlements (embedded.mobileprovision).\n";
  531. }
  532. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  533. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  534. // ASCII. Replace any 0s or invalid characters in the input.
  535. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  536. for (int i = 0; i < profileData.length; i++) {
  537. uint8_t currentByte = profileBytes[i];
  538. if (!currentByte || currentByte > 127) {
  539. profileBytes[i] = '.';
  540. }
  541. }
  542. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  543. length:profileData.length
  544. encoding:NSASCIIStringEncoding
  545. freeWhenDone:NO];
  546. if (error || !embeddedProfile.length) {
  547. return @"\tSKIPPED: Not able to read entitlements (embedded.mobileprovision).\n";
  548. }
  549. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  550. NSString *plistContents;
  551. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  552. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  553. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  554. }
  555. }
  556. if (!plistContents.length) {
  557. return @"\tWARNING: Not able to read plist entitlements (embedded.mobileprovision).\n";
  558. }
  559. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  560. if (!data.length) {
  561. return @"\tWARNING: Not able to parse entitlements (embedded.mobileprovision).\n";
  562. }
  563. NSError *plistMapError;
  564. id plistData = [NSPropertyListSerialization propertyListWithData:data
  565. options:NSPropertyListImmutable
  566. format:nil
  567. error:&plistMapError];
  568. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  569. return @"\tWARNING: Not able to deserialize entitlements (embedded.mobileprovision).\n";
  570. }
  571. NSDictionary *plistMap = (NSDictionary *)plistData;
  572. // analyze entitlements and print diagnostic information
  573. // we can't detect erorrs, information p[rinted here may hint developer or will help support
  574. // to identify the issue
  575. NSMutableString *outputString = [[NSMutableString alloc] init];
  576. NSArray *appIdentifierPrefixes = plistMap[@"ApplicationIdentifierPrefix"];
  577. NSString *teamID = plistMap[@"Entitlements"][@"com.apple.developer.team-identifier"];
  578. if (appIdentifierPrefixes.count > 1) {
  579. // is this possible? anyway, we can handle it
  580. [outputString
  581. appendFormat:@"\tAppID Prefixes: %@, Team ID: %@, AppId Prefixes contains to Team ID: %@\n",
  582. appIdentifierPrefixes, teamID,
  583. ([appIdentifierPrefixes containsObject:teamID] ? @"YES" : @"NO")];
  584. } else {
  585. [outputString
  586. appendFormat:@"\tAppID Prefix: %@, Team ID: %@, AppId Prefix equal to Team ID: %@\n",
  587. appIdentifierPrefixes[0], teamID,
  588. ([appIdentifierPrefixes[0] isEqualToString:teamID] ? @"YES" : @"NO")];
  589. }
  590. return outputString;
  591. }
  592. + (NSString *)performDiagnosticsIncludingHeaderFooter:(BOOL)includingHeaderFooter
  593. detectedErrors:(nullable NSInteger *)detectedErrors {
  594. NSMutableString *diagnosticString = [[NSMutableString alloc] init];
  595. if (includingHeaderFooter) {
  596. [diagnosticString appendString:@"\n"];
  597. [diagnosticString appendString:kSelfDiagnoseOutputHeader];
  598. }
  599. NSInteger detectedErrorsCnt = 0;
  600. [diagnosticString appendString:[self genericDiagnosticInformation]];
  601. #if TARGET_IPHONE_SIMULATOR
  602. // check is Simulator and print WARNING that Universal Links is not supported on Simulator
  603. [diagnosticString
  604. appendString:@"WARNING: iOS Simulator does not support Universal Links. Firebase "
  605. @"Dynamic Links SDK functionality will be limited. Some FDL "
  606. @"features may be missing or will not work correctly.\n"];
  607. #endif // TARGET_IPHONE_SIMULATOR
  608. id<UIApplicationDelegate> applicationDelegate = [UIApplication sharedApplication].delegate;
  609. if (![applicationDelegate respondsToSelector:@selector(application:openURL:options:)]) {
  610. detectedErrorsCnt++;
  611. [diagnosticString appendFormat:@"ERROR: UIApplication delegate %@ does not implements selector "
  612. @"%@. FDL depends on this implementation to retrieve pending "
  613. @"dynamic link.\n",
  614. applicationDelegate,
  615. NSStringFromSelector(@selector(application:openURL:options:))];
  616. }
  617. // check that Info.plist has custom URL scheme and the scheme is the same as bundleID or
  618. // as customURLScheme passed to FDL iOS SDK
  619. NSString *URLScheme = [FIRDynamicLinks dynamicLinks].URLScheme;
  620. BOOL URLSchemeFoundInPlist = NO;
  621. NSArray *URLSchemesFromInfoPlist = [[NSBundle mainBundle] infoDictionary][@"CFBundleURLTypes"];
  622. for (NSDictionary *schemeDetails in URLSchemesFromInfoPlist) {
  623. NSArray *arrayOfSchemes = schemeDetails[@"CFBundleURLSchemes"];
  624. for (NSString *scheme in arrayOfSchemes) {
  625. if ([scheme isEqualToString:URLScheme]) {
  626. URLSchemeFoundInPlist = YES;
  627. break;
  628. }
  629. }
  630. if (URLSchemeFoundInPlist) {
  631. break;
  632. }
  633. }
  634. if (!URLSchemeFoundInPlist) {
  635. detectedErrorsCnt++;
  636. [diagnosticString appendFormat:@"ERROR: Specified custom URL scheme is %@ but Info.plist do "
  637. @"not contain such scheme in "
  638. "CFBundleURLTypes key.\n",
  639. URLScheme];
  640. } else {
  641. [diagnosticString appendFormat:@"\tSpecified custom URL scheme is %@ and Info.plist contains "
  642. @"such scheme in CFBundleURLTypes key.\n",
  643. URLScheme];
  644. }
  645. #if !TARGET_IPHONE_SIMULATOR
  646. // analyse information in entitlements file
  647. NSString *entitlementsAnalysis = [self diagnosticAnalyzeEntitlements];
  648. if (entitlementsAnalysis.length) {
  649. [diagnosticString appendString:entitlementsAnalysis];
  650. }
  651. #endif // TARGET_IPHONE_SIMULATOR
  652. if (includingHeaderFooter) {
  653. if (detectedErrorsCnt == 0) {
  654. [diagnosticString
  655. appendString:@"performDiagnostic completed successfully! No errors found.\n"];
  656. } else {
  657. [diagnosticString
  658. appendFormat:@"performDiagnostic detected %ld ERRORS.\n", (long)detectedErrorsCnt];
  659. }
  660. [diagnosticString appendString:kSelfDiagnoseOutputFooter];
  661. }
  662. if (detectedErrors) {
  663. *detectedErrors = detectedErrorsCnt;
  664. }
  665. return [diagnosticString copy];
  666. }
  667. + (void)performDiagnosticsWithCompletion:(void (^_Nullable)(NSString *diagnosticOutput,
  668. BOOL hasErrors))completionHandler;
  669. {
  670. NSInteger detectedErrorsCnt = 0;
  671. NSString *diagnosticString = [self performDiagnosticsIncludingHeaderFooter:YES
  672. detectedErrors:&detectedErrorsCnt];
  673. if (completionHandler) {
  674. completionHandler(diagnosticString, detectedErrorsCnt > 0);
  675. } else {
  676. NSLog(@"%@", diagnosticString);
  677. }
  678. }
  679. @end
  680. NS_ASSUME_NONNULL_END
  681. #endif // TARGET_OS_IOS