FIRDynamicLinks.m 31 KB

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