FIRDynamicLinks.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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. // 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(
  376. nil, [[NSError alloc] initWithDomain:@"com.firebase.dynamicLinks"
  377. code:1
  378. userInfo:@{
  379. NSLocalizedFailureReasonErrorKey :
  380. @"Universal link URL could not be parsed by Dynamic Links."
  381. }]);
  382. return nil;
  383. }
  384. - (nullable FIRDynamicLink *)dynamicLinkFromUniversalLinkURL:(NSURL *)url {
  385. return [self dynamicLinkInternalFromUniversalLinkURL:url completion:nil];
  386. }
  387. - (void)dynamicLinkFromUniversalLinkURL:(NSURL *)url
  388. completion:(FIRDynamicLinkUniversalLinkHandler)completion {
  389. [self dynamicLinkInternalFromUniversalLinkURL:url completion:completion];
  390. }
  391. - (BOOL)handleUniversalLink:(NSURL *)universalLinkURL
  392. completion:(FIRDynamicLinkUniversalLinkHandler)completion {
  393. if ([self matchesShortLinkFormat:universalLinkURL]) {
  394. __weak __typeof__(self) weakSelf = self;
  395. [self resolveShortLink:universalLinkURL
  396. completion:^(NSURL *url, NSError *error) {
  397. __typeof__(self) strongSelf = weakSelf;
  398. if (strongSelf) {
  399. FIRDynamicLink *dynamicLink = [strongSelf dynamicLinkFromCustomSchemeURL:url];
  400. dispatch_async(dispatch_get_main_queue(), ^{
  401. completion(dynamicLink, error);
  402. });
  403. } else {
  404. completion(nil, nil);
  405. }
  406. }];
  407. return YES;
  408. } else {
  409. [self dynamicLinkFromUniversalLinkURL:universalLinkURL completion:completion];
  410. BOOL canHandleUniversalLink =
  411. [self canParseUniversalLinkURL:universalLinkURL] && universalLinkURL.query.length > 0 &&
  412. FIRDLDictionaryFromQuery(universalLinkURL.query)[kFIRDLParameterLink];
  413. return canHandleUniversalLink;
  414. }
  415. }
  416. - (void)resolveShortLink:(NSURL *)url completion:(FIRDynamicLinkResolverHandler)completion {
  417. [self.dynamicLinkNetworking resolveShortLink:url
  418. FDLSDKVersion:FIRFirebaseVersion()
  419. completion:completion];
  420. }
  421. - (BOOL)matchesShortLinkFormat:(NSURL *)url {
  422. return FIRDLMatchesShortLinkFormat(url);
  423. }
  424. #pragma mark - Private interface
  425. + (BOOL)isAutomaticRetrievalEnabled {
  426. id retrievalEnabledValue =
  427. [[NSBundle mainBundle] infoDictionary][@"FirebaseDeepLinkAutomaticRetrievalEnabled"];
  428. if ([retrievalEnabledValue respondsToSelector:@selector(boolValue)]) {
  429. return [retrievalEnabledValue boolValue];
  430. }
  431. return YES;
  432. }
  433. #pragma mark - Internal methods
  434. - (FIRDynamicLinkNetworking *)dynamicLinkNetworking {
  435. if (!_dynamicLinkNetworking) {
  436. _dynamicLinkNetworking = [[FIRDynamicLinkNetworking alloc] initWithAPIKey:_APIKey
  437. URLScheme:_URLScheme];
  438. }
  439. return _dynamicLinkNetworking;
  440. }
  441. - (BOOL)canParseCustomSchemeURL:(nullable NSURL *)url {
  442. if (url.scheme.length) {
  443. NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
  444. if ([url.scheme.lowercaseString isEqualToString:_URLScheme.lowercaseString] ||
  445. [url.scheme.lowercaseString isEqualToString:bundleIdentifier.lowercaseString]) {
  446. return YES;
  447. }
  448. }
  449. return NO;
  450. }
  451. - (BOOL)canParseUniversalLinkURL:(nullable NSURL *)url {
  452. return FIRDLCanParseUniversalLinkURL(url);
  453. }
  454. - (BOOL)handleIncomingCustomSchemeDeepLink:(NSURL *)url {
  455. return [self canParseCustomSchemeURL:url];
  456. }
  457. - (void)passRetrievedDynamicLinkToApplication:(NSURL *)url {
  458. id<UIApplicationDelegate> applicationDelegate = [UIApplication sharedApplication].delegate;
  459. if ([self isOpenUrlMethodPresentInAppDelegate:applicationDelegate]) {
  460. // pass url directly to application delegate to avoid hop into
  461. // iOS handling of the universal links
  462. [applicationDelegate application:[UIApplication sharedApplication] openURL:url options:@{}];
  463. return;
  464. }
  465. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  466. }
  467. - (BOOL)isOpenUrlMethodPresentInAppDelegate:(id<UIApplicationDelegate>)applicationDelegate {
  468. return applicationDelegate &&
  469. [applicationDelegate respondsToSelector:@selector(application:openURL:options:)];
  470. }
  471. - (void)handlePendingDynamicLinkRetrievalFailureWithErrorCode:(NSInteger)errorCode
  472. errorDescription:(NSString *)errorDescription
  473. underlyingError:(nullable NSError *)underlyingError {
  474. self.retrievingPendingDynamicLink = NO;
  475. // TODO (b/38035270) inform caller why we failed, for App developer it is hard to debug
  476. // stuff like this without having source code access
  477. }
  478. #pragma mark - FIRDLRetrievalProcessDelegate
  479. - (void)retrievalProcess:(id<FIRDLRetrievalProcessProtocol>)retrievalProcess
  480. completedWithResult:(FIRDLRetrievalProcessResult *)result {
  481. self.retrievingPendingDynamicLink = NO;
  482. _retrievalProcess = nil;
  483. if (![_userDefaults boolForKey:kFIRDLOpenURLKey]) {
  484. // Once we complete the Pending dynamic link retrieval, regardless of whether the retrieval is
  485. // success or failure, we don't want to do the retrieval again on next app start.
  486. // If we try to redo the retrieval again because of some error, the user will experience
  487. // unwanted deeplinking when they restart the app next time.
  488. [_userDefaults setBool:YES forKey:kFIRDLOpenURLKey];
  489. }
  490. NSURL *linkToPassToApp = [result URLWithCustomURLScheme:_URLScheme];
  491. [self passRetrievedDynamicLinkToApplication:linkToPassToApp];
  492. }
  493. #pragma mark - Diagnostics methods
  494. static NSString *kSelfDiagnoseOutputHeader =
  495. @"---- Firebase Dynamic Links diagnostic output start ----\n";
  496. // TODO (b/38397557) Add link to the "Debug FDL" documentation when docs is published
  497. static NSString *kSelfDiagnoseOutputFooter =
  498. @"---- Firebase Dynamic Links diagnostic output end ----\n";
  499. + (NSString *)genericDiagnosticInformation {
  500. NSMutableString *genericDiagnosticInfo = [[NSMutableString alloc] init];
  501. [genericDiagnosticInfo
  502. appendFormat:@"Firebase Dynamic Links framework version %@\n", FIRFirebaseVersion()];
  503. [genericDiagnosticInfo appendFormat:@"System information: OS %@, OS version %@, model %@\n",
  504. [UIDevice currentDevice].systemName,
  505. [UIDevice currentDevice].systemVersion,
  506. [UIDevice currentDevice].model];
  507. [genericDiagnosticInfo appendFormat:@"Current date %@\n", [NSDate date]];
  508. // TODO: bring this diagnostic info back when we shipped non-automatic retrieval
  509. // [genericDiagnosticInfo appendFormat:@"AutomaticRetrievalEnabled: %@\n",
  510. // [self isAutomaticRetrievalEnabled] ? @"YES" : @"NO"];
  511. // Disable deprecated warning for internal methods.
  512. #pragma clang diagnostic push
  513. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  514. [genericDiagnosticInfo appendFormat:@"Device locale %@ (raw %@), timezone %@\n",
  515. FIRDLDeviceLocale(), FIRDLDeviceLocaleRaw(),
  516. FIRDLDeviceTimezone()];
  517. #pragma clang pop
  518. return genericDiagnosticInfo;
  519. }
  520. + (NSString *)diagnosticAnalyzeEntitlements {
  521. NSString *embeddedMobileprovisionFilePath = [[[NSBundle mainBundle] bundlePath]
  522. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  523. NSError *error;
  524. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:embeddedMobileprovisionFilePath
  525. options:0
  526. error:&error];
  527. if (!profileData.length || error) {
  528. return @"\tSKIPPED: Not able to read entitlements (embedded.mobileprovision).\n";
  529. }
  530. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  531. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  532. // ASCII. Replace any 0s or invalid characters in the input.
  533. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  534. for (int i = 0; i < profileData.length; i++) {
  535. uint8_t currentByte = profileBytes[i];
  536. if (!currentByte || currentByte > 127) {
  537. profileBytes[i] = '.';
  538. }
  539. }
  540. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  541. length:profileData.length
  542. encoding:NSASCIIStringEncoding
  543. freeWhenDone:NO];
  544. if (error || !embeddedProfile.length) {
  545. return @"\tSKIPPED: Not able to read entitlements (embedded.mobileprovision).\n";
  546. }
  547. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  548. NSString *plistContents;
  549. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  550. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  551. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  552. }
  553. }
  554. if (!plistContents.length) {
  555. return @"\tWARNING: Not able to read plist entitlements (embedded.mobileprovision).\n";
  556. }
  557. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  558. if (!data.length) {
  559. return @"\tWARNING: Not able to parse entitlements (embedded.mobileprovision).\n";
  560. }
  561. NSError *plistMapError;
  562. id plistData = [NSPropertyListSerialization propertyListWithData:data
  563. options:NSPropertyListImmutable
  564. format:nil
  565. error:&plistMapError];
  566. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  567. return @"\tWARNING: Not able to deserialize entitlements (embedded.mobileprovision).\n";
  568. }
  569. NSDictionary *plistMap = (NSDictionary *)plistData;
  570. // analyze entitlements and print diagnostic information
  571. // we can't detect erorrs, information p[rinted here may hint developer or will help support
  572. // to identify the issue
  573. NSMutableString *outputString = [[NSMutableString alloc] init];
  574. NSArray *appIdentifierPrefixes = plistMap[@"ApplicationIdentifierPrefix"];
  575. NSString *teamID = plistMap[@"Entitlements"][@"com.apple.developer.team-identifier"];
  576. if (appIdentifierPrefixes.count > 1) {
  577. // is this possible? anyway, we can handle it
  578. [outputString
  579. appendFormat:@"\tAppID Prefixes: %@, Team ID: %@, AppId Prefixes contains to Team ID: %@\n",
  580. appIdentifierPrefixes, teamID,
  581. ([appIdentifierPrefixes containsObject:teamID] ? @"YES" : @"NO")];
  582. } else {
  583. [outputString
  584. appendFormat:@"\tAppID Prefix: %@, Team ID: %@, AppId Prefix equal to Team ID: %@\n",
  585. appIdentifierPrefixes[0], teamID,
  586. ([appIdentifierPrefixes[0] isEqualToString:teamID] ? @"YES" : @"NO")];
  587. }
  588. return outputString;
  589. }
  590. + (NSString *)performDiagnosticsIncludingHeaderFooter:(BOOL)includingHeaderFooter
  591. detectedErrors:(nullable NSInteger *)detectedErrors {
  592. NSMutableString *diagnosticString = [[NSMutableString alloc] init];
  593. if (includingHeaderFooter) {
  594. [diagnosticString appendString:@"\n"];
  595. [diagnosticString appendString:kSelfDiagnoseOutputHeader];
  596. }
  597. NSInteger detectedErrorsCnt = 0;
  598. [diagnosticString appendString:[self genericDiagnosticInformation]];
  599. #if TARGET_IPHONE_SIMULATOR
  600. // check is Simulator and print WARNING that Universal Links is not supported on Simulator
  601. [diagnosticString
  602. appendString:@"WARNING: iOS Simulator does not support Universal Links. Firebase "
  603. @"Dynamic Links SDK functionality will be limited. Some FDL "
  604. @"features may be missing or will not work correctly.\n"];
  605. #endif // TARGET_IPHONE_SIMULATOR
  606. id<UIApplicationDelegate> applicationDelegate = [UIApplication sharedApplication].delegate;
  607. if (![applicationDelegate respondsToSelector:@selector(application:openURL:options:)]) {
  608. detectedErrorsCnt++;
  609. [diagnosticString appendFormat:@"ERROR: UIApplication delegate %@ does not implements selector "
  610. @"%@. FDL depends on this implementation to retrieve pending "
  611. @"dynamic link.\n",
  612. applicationDelegate,
  613. NSStringFromSelector(@selector(application:openURL:options:))];
  614. }
  615. // check that Info.plist has custom URL scheme and the scheme is the same as bundleID or
  616. // as customURLScheme passed to FDL iOS SDK
  617. NSString *URLScheme = [FIRDynamicLinks dynamicLinks].URLScheme;
  618. BOOL URLSchemeFoundInPlist = NO;
  619. NSArray *URLSchemesFromInfoPlist = [[NSBundle mainBundle] infoDictionary][@"CFBundleURLTypes"];
  620. for (NSDictionary *schemeDetails in URLSchemesFromInfoPlist) {
  621. NSArray *arrayOfSchemes = schemeDetails[@"CFBundleURLSchemes"];
  622. for (NSString *scheme in arrayOfSchemes) {
  623. if ([scheme isEqualToString:URLScheme]) {
  624. URLSchemeFoundInPlist = YES;
  625. break;
  626. }
  627. }
  628. if (URLSchemeFoundInPlist) {
  629. break;
  630. }
  631. }
  632. if (!URLSchemeFoundInPlist) {
  633. detectedErrorsCnt++;
  634. [diagnosticString appendFormat:@"ERROR: Specified custom URL scheme is %@ but Info.plist do "
  635. @"not contain such scheme in "
  636. "CFBundleURLTypes key.\n",
  637. URLScheme];
  638. } else {
  639. [diagnosticString appendFormat:@"\tSpecified custom URL scheme is %@ and Info.plist contains "
  640. @"such scheme in CFBundleURLTypes key.\n",
  641. URLScheme];
  642. }
  643. #if !TARGET_IPHONE_SIMULATOR
  644. // analyse information in entitlements file
  645. NSString *entitlementsAnalysis = [self diagnosticAnalyzeEntitlements];
  646. if (entitlementsAnalysis.length) {
  647. [diagnosticString appendString:entitlementsAnalysis];
  648. }
  649. #endif // TARGET_IPHONE_SIMULATOR
  650. if (includingHeaderFooter) {
  651. if (detectedErrorsCnt == 0) {
  652. [diagnosticString
  653. appendString:@"performDiagnostic completed successfully! No errors found.\n"];
  654. } else {
  655. [diagnosticString
  656. appendFormat:@"performDiagnostic detected %ld ERRORS.\n", (long)detectedErrorsCnt];
  657. }
  658. [diagnosticString appendString:kSelfDiagnoseOutputFooter];
  659. }
  660. if (detectedErrors) {
  661. *detectedErrors = detectedErrorsCnt;
  662. }
  663. return [diagnosticString copy];
  664. }
  665. + (void)performDiagnosticsWithCompletion:(void (^_Nullable)(NSString *diagnosticOutput,
  666. BOOL hasErrors))completionHandler;
  667. {
  668. NSInteger detectedErrorsCnt = 0;
  669. NSString *diagnosticString = [self performDiagnosticsIncludingHeaderFooter:YES
  670. detectedErrors:&detectedErrorsCnt];
  671. if (completionHandler) {
  672. completionHandler(diagnosticString, detectedErrorsCnt > 0);
  673. } else {
  674. NSLog(@"%@", diagnosticString);
  675. }
  676. }
  677. @end
  678. NS_ASSUME_NONNULL_END
  679. #endif // TARGET_OS_IOS