FIRDynamicLinks.m 32 KB

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