FIRDynamicLinks.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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 =
  135. [NSString stringWithFormat:
  136. @"Firebase Dynamic Links has stopped your project "
  137. @"because there are incorrect values provided in Firebase's configuration "
  138. @"options that may prevent your app from behaving as expected:\n\n"
  139. @"Error: %@\n\n"
  140. @"Please fix these issues to ensure that Firebase is correctly configured in "
  141. @"your project.",
  142. error.localizedFailureReason];
  143. [NSException raise:kFirebaseDurableDeepLinkErrorDomain format:@"%@", message];
  144. }
  145. [self checkForCustomDomainEntriesInInfoPlist];
  146. }
  147. - (instancetype)initWithAnalytics:(nullable id<FIRAnalyticsInterop>)analytics {
  148. self = [super init];
  149. if (self) {
  150. _analytics = analytics;
  151. }
  152. return self;
  153. }
  154. + (instancetype)dynamicLinks {
  155. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  156. id<FIRDynamicLinksInstanceProvider> instance =
  157. FIR_COMPONENT(FIRDynamicLinksInstanceProvider, defaultApp.container);
  158. return (FIRDynamicLinks *)instance;
  159. }
  160. #else
  161. + (instancetype)dynamicLinks {
  162. static FIRDynamicLinks *dynamicLinks;
  163. static dispatch_once_t onceToken;
  164. dispatch_once(&onceToken, ^{
  165. dynamicLinks = [[self alloc] init];
  166. });
  167. return dynamicLinks;
  168. }
  169. #endif
  170. #pragma mark - Custom domains
  171. - (instancetype)init {
  172. self = [super init];
  173. if (self) {
  174. [self checkForCustomDomainEntriesInInfoPlist];
  175. }
  176. return self;
  177. }
  178. // Check for custom domains entry in PLIST file.
  179. - (void)checkForCustomDomainEntriesInInfoPlist {
  180. // Check to see if FirebaseDynamicLinksCustomDomains array is present.
  181. NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary;
  182. NSArray *customDomains = infoDictionary[kInfoPlistCustomDomainsKey];
  183. if (customDomains) {
  184. FIRDLAddToAllowListForCustomDomainsArray(customDomains);
  185. }
  186. }
  187. #pragma mark - First party interface
  188. - (BOOL)setUpWithLaunchOptions:(nullable NSDictionary *)launchOptions
  189. apiKey:(NSString *)apiKey
  190. urlScheme:(nullable NSString *)urlScheme
  191. userDefaults:(nullable NSUserDefaults *)userDefaults {
  192. if (apiKey == nil) {
  193. FDLLog(FDLLogLevelError, FDLLogIdentifierSetupNilAPIKey, @"API Key must not be nil.");
  194. return NO;
  195. }
  196. _APIKey = [apiKey copy];
  197. _URLScheme = urlScheme.length ? [urlScheme copy] : [NSBundle mainBundle].bundleIdentifier;
  198. if (!userDefaults) {
  199. _userDefaults = [NSUserDefaults standardUserDefaults];
  200. } else {
  201. _userDefaults = userDefaults;
  202. }
  203. NSURL *url = launchOptions[UIApplicationLaunchOptionsURLKey];
  204. if (url) {
  205. if ([self canParseCustomSchemeURL:url] || [self canParseUniversalLinkURL:url]) {
  206. // Make sure we don't call |checkForPendingDynamicLink| again if
  207. // a strong deep link is found.
  208. [_userDefaults setBool:YES forKey:kFIRDLReadDeepLinkAfterInstallKey];
  209. }
  210. }
  211. return YES;
  212. }
  213. - (void)checkForPendingDynamicLinkUsingExperimentalRetrievalProcess {
  214. [self checkForPendingDynamicLink];
  215. }
  216. - (void)checkForPendingDynamicLink {
  217. // Make sure this method is called only once after the application was installed.
  218. // kFIRDLOpenURLKey marks checkForPendingDynamic link had been called already so no need to do it
  219. // again. kFIRDLReadDeepLinkAfterInstallKey marks we have already read a deeplink after the
  220. // install and so no need to do check for pending dynamic link.
  221. BOOL appInviteDeepLinkRead = [_userDefaults boolForKey:kFIRDLOpenURLKey] ||
  222. [_userDefaults boolForKey:kFIRDLReadDeepLinkAfterInstallKey];
  223. if (appInviteDeepLinkRead || self.retrievingPendingDynamicLink) {
  224. NSString *errorDescription =
  225. appInviteDeepLinkRead ? NSLocalizedString(@"Link was already retrieved", @"Error message")
  226. : NSLocalizedString(@"Already retrieving link", @"Error message");
  227. [self handlePendingDynamicLinkRetrievalFailureWithErrorCode:-1
  228. errorDescription:errorDescription
  229. underlyingError:nil];
  230. return;
  231. }
  232. self.retrievingPendingDynamicLink = YES;
  233. FIRDLRetrievalProcessFactory *factory =
  234. [[FIRDLRetrievalProcessFactory alloc] initWithNetworkingService:self.dynamicLinkNetworking
  235. URLScheme:_URLScheme
  236. APIKey:_APIKey
  237. FDLSDKVersion:FIRFirebaseVersion()
  238. delegate:self];
  239. _retrievalProcess = [factory automaticRetrievalProcess];
  240. [_retrievalProcess retrievePendingDynamicLink];
  241. }
  242. // Disable deprecated warning for internal methods.
  243. #pragma clang diagnostic push
  244. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  245. + (instancetype)sharedInstance {
  246. return [self dynamicLinks];
  247. }
  248. - (BOOL)setUpWithLaunchOptions:(nullable NSDictionary *)launchOptions
  249. apiKey:(NSString *)apiKey
  250. clientID:(NSString *)clientID
  251. urlScheme:(nullable NSString *)urlScheme
  252. userDefaults:(nullable NSUserDefaults *)userDefaults {
  253. return [self setUpWithLaunchOptions:launchOptions
  254. apiKey:apiKey
  255. urlScheme:urlScheme
  256. userDefaults:userDefaults];
  257. }
  258. - (void)checkForPendingDeepLink {
  259. [self checkForPendingDynamicLink];
  260. }
  261. - (nullable FIRDynamicLink *)deepLinkFromCustomSchemeURL:(NSURL *)url {
  262. return [self dynamicLinkFromCustomSchemeURL:url];
  263. }
  264. - (nullable FIRDynamicLink *)deepLinkFromUniversalLinkURL:(NSURL *)url {
  265. return [self dynamicLinkFromUniversalLinkURL:url];
  266. }
  267. - (BOOL)shouldHandleDeepLinkFromCustomSchemeURL:(NSURL *)url {
  268. return [self shouldHandleDynamicLinkFromCustomSchemeURL:url];
  269. }
  270. #pragma clang pop
  271. #pragma mark - Public interface
  272. - (BOOL)shouldHandleDynamicLinkFromCustomSchemeURL:(NSURL *)url {
  273. // Return NO if the URL scheme does not match.
  274. if (![self canParseCustomSchemeURL:url]) {
  275. return NO;
  276. }
  277. // We can handle "/link" and "/link/dismiss". The latter will return a nil deep link.
  278. return ([url.path hasPrefix:@"/link"] && [url.host isEqualToString:@"google"]);
  279. }
  280. - (nullable FIRDynamicLink *)dynamicLinkFromCustomSchemeURL:(NSURL *)url {
  281. // Return nil if the URL scheme does not match.
  282. if (![self canParseCustomSchemeURL:url]) {
  283. return nil;
  284. }
  285. if ([url.path isEqualToString:@"/link"] && [url.host isEqualToString:@"google"]) {
  286. // This URL is a callback url from a device heuristics based match
  287. // Extract information from query.
  288. NSString *query = url.query;
  289. NSDictionary *parameters = FIRDLDictionaryFromQuery(query);
  290. // As long as the deepLink has some parameter, return it.
  291. if (parameters.count > 0) {
  292. FIRDynamicLink *dynamicLink =
  293. [[FIRDynamicLink alloc] initWithParametersDictionary:parameters];
  294. #ifdef GIN_SCION_LOGGING
  295. if (dynamicLink.url) {
  296. BOOL isFirstOpen = ![_userDefaults boolForKey:kFIRDLReadDeepLinkAfterInstallKey];
  297. FIRDLLogEvent event = isFirstOpen ? FIRDLLogEventFirstOpen : FIRDLLogEventAppOpen;
  298. FIRDLLogEventToScion(event, parameters[kFIRDLParameterSource],
  299. parameters[kFIRDLParameterMedium], parameters[kFIRDLParameterCampaign],
  300. _analytics);
  301. }
  302. #endif
  303. // Make sure we don't call |checkForPendingDynamicLink| again if we did this already.
  304. if ([_userDefaults boolForKey:kFIRDLOpenURLKey]) {
  305. [_userDefaults setBool:YES forKey:kFIRDLReadDeepLinkAfterInstallKey];
  306. }
  307. return dynamicLink;
  308. }
  309. }
  310. return nil;
  311. }
  312. - (nullable FIRDynamicLink *)
  313. dynamicLinkInternalFromUniversalLinkURL:(NSURL *)url
  314. completion:
  315. (nullable FIRDynamicLinkUniversalLinkHandler)completion {
  316. // Make sure the completion is always called on the main queue.
  317. FIRDynamicLinkUniversalLinkHandler mainQueueCompletion =
  318. ^(FIRDynamicLink *_Nullable dynamicLink, NSError *_Nullable error) {
  319. if (completion) {
  320. dispatch_async(dispatch_get_main_queue(), ^{
  321. completion(dynamicLink, error);
  322. });
  323. }
  324. };
  325. if ([self canParseUniversalLinkURL:url]) {
  326. if (url.query.length > 0) {
  327. NSDictionary<NSString *, NSString *> *parameters = FIRDLDictionaryFromQuery(url.query);
  328. if (parameters[kFIRDLParameterLink]) {
  329. NSString *urlString = parameters[kFIRDLParameterLink];
  330. NSURL *deepLinkURL = [NSURL URLWithString:urlString];
  331. if (deepLinkURL) {
  332. NSMutableDictionary *paramsDictionary = [[NSMutableDictionary alloc]
  333. initWithDictionary:@{kFIRDLParameterDeepLinkIdentifier : urlString}];
  334. if (parameters[kFIRDLParameterSource] != nil) {
  335. [paramsDictionary setValue:parameters[kFIRDLParameterSource]
  336. forKey:kFIRDLParameterSource];
  337. }
  338. if (parameters[kFIRDLParameterMedium] != nil) {
  339. [paramsDictionary setValue:parameters[kFIRDLParameterMedium]
  340. forKey:kFIRDLParameterMedium];
  341. }
  342. if (parameters[kFIRDLParameterTerm] != nil) {
  343. [paramsDictionary setValue:parameters[kFIRDLParameterTerm] forKey:kFIRDLParameterTerm];
  344. }
  345. if (parameters[kFIRDLParameterCampaign] != nil) {
  346. [paramsDictionary setValue:parameters[kFIRDLParameterCampaign]
  347. forKey:(kFIRDLParameterCampaign)];
  348. }
  349. if (parameters[kFIRDLParameterContent] != nil) {
  350. [paramsDictionary setValue:parameters[kFIRDLParameterContent]
  351. forKey:kFIRDLParameterContent];
  352. }
  353. FIRDynamicLink *dynamicLink =
  354. [[FIRDynamicLink alloc] initWithParametersDictionary:paramsDictionary];
  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. }
  476. #pragma mark - FIRDLRetrievalProcessDelegate
  477. - (void)retrievalProcess:(id<FIRDLRetrievalProcessProtocol>)retrievalProcess
  478. completedWithResult:(FIRDLRetrievalProcessResult *)result {
  479. self.retrievingPendingDynamicLink = NO;
  480. _retrievalProcess = nil;
  481. if (![_userDefaults boolForKey:kFIRDLOpenURLKey]) {
  482. // Once we complete the Pending dynamic link retrieval, regardless of whether the retrieval is
  483. // success or failure, we don't want to do the retrieval again on next app start.
  484. // If we try to redo the retrieval again because of some error, the user will experience
  485. // unwanted deeplinking when they restart the app next time.
  486. [_userDefaults setBool:YES forKey:kFIRDLOpenURLKey];
  487. }
  488. NSURL *linkToPassToApp = [result URLWithCustomURLScheme:_URLScheme];
  489. [self passRetrievedDynamicLinkToApplication:linkToPassToApp];
  490. }
  491. #pragma mark - Diagnostics methods
  492. static NSString *kSelfDiagnoseOutputHeader =
  493. @"---- Firebase Dynamic Links diagnostic output start ----\n";
  494. static NSString *kSelfDiagnoseOutputFooter =
  495. @"---- Firebase Dynamic Links diagnostic output end ----\n";
  496. + (NSString *)genericDiagnosticInformation {
  497. NSMutableString *genericDiagnosticInfo = [[NSMutableString alloc] init];
  498. [genericDiagnosticInfo
  499. appendFormat:@"Firebase Dynamic Links framework version %@\n", FIRFirebaseVersion()];
  500. [genericDiagnosticInfo appendFormat:@"System information: OS %@, OS version %@, model %@\n",
  501. [UIDevice currentDevice].systemName,
  502. [UIDevice currentDevice].systemVersion,
  503. [UIDevice currentDevice].model];
  504. [genericDiagnosticInfo appendFormat:@"Current date %@\n", [NSDate date]];
  505. // TODO: bring this diagnostic info back when we shipped non-automatic retrieval
  506. // [genericDiagnosticInfo appendFormat:@"AutomaticRetrievalEnabled: %@\n",
  507. // [self isAutomaticRetrievalEnabled] ? @"YES" : @"NO"];
  508. // Disable deprecated warning for internal methods.
  509. #pragma clang diagnostic push
  510. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  511. [genericDiagnosticInfo appendFormat:@"Device locale %@ (raw %@), timezone %@\n",
  512. FIRDLDeviceLocale(), FIRDLDeviceLocaleRaw(),
  513. FIRDLDeviceTimezone()];
  514. #pragma clang pop
  515. return genericDiagnosticInfo;
  516. }
  517. + (NSString *)diagnosticAnalyzeEntitlements {
  518. NSString *embeddedMobileprovisionFilePath = [[[NSBundle mainBundle] bundlePath]
  519. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  520. NSError *error;
  521. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:embeddedMobileprovisionFilePath
  522. options:0
  523. error:&error];
  524. if (!profileData.length || error) {
  525. return @"\tSKIPPED: Not able to read entitlements (embedded.mobileprovision).\n";
  526. }
  527. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  528. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  529. // ASCII. Replace any 0s or invalid characters in the input.
  530. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  531. for (int i = 0; i < profileData.length; i++) {
  532. uint8_t currentByte = profileBytes[i];
  533. if (!currentByte || currentByte > 127) {
  534. profileBytes[i] = '.';
  535. }
  536. }
  537. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  538. length:profileData.length
  539. encoding:NSASCIIStringEncoding
  540. freeWhenDone:NO];
  541. if (error || !embeddedProfile.length) {
  542. return @"\tSKIPPED: Not able to read entitlements (embedded.mobileprovision).\n";
  543. }
  544. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  545. NSString *plistContents;
  546. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  547. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  548. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  549. }
  550. }
  551. if (!plistContents.length) {
  552. return @"\tWARNING: Not able to read plist entitlements (embedded.mobileprovision).\n";
  553. }
  554. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  555. if (!data.length) {
  556. return @"\tWARNING: Not able to parse entitlements (embedded.mobileprovision).\n";
  557. }
  558. NSError *plistMapError;
  559. id plistData = [NSPropertyListSerialization propertyListWithData:data
  560. options:NSPropertyListImmutable
  561. format:nil
  562. error:&plistMapError];
  563. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  564. return @"\tWARNING: Not able to deserialize entitlements (embedded.mobileprovision).\n";
  565. }
  566. NSDictionary *plistMap = (NSDictionary *)plistData;
  567. // analyze entitlements and print diagnostic information
  568. // we can't detect errors, information p[rinted here may hint developer or will help support
  569. // to identify the issue
  570. NSMutableString *outputString = [[NSMutableString alloc] init];
  571. NSArray *appIdentifierPrefixes = plistMap[@"ApplicationIdentifierPrefix"];
  572. NSString *teamID = plistMap[@"Entitlements"][@"com.apple.developer.team-identifier"];
  573. if (appIdentifierPrefixes.count > 1) {
  574. // is this possible? anyway, we can handle it
  575. [outputString
  576. appendFormat:@"\tAppID Prefixes: %@, Team ID: %@, AppId Prefixes contains to Team ID: %@\n",
  577. appIdentifierPrefixes, teamID,
  578. ([appIdentifierPrefixes containsObject:teamID] ? @"YES" : @"NO")];
  579. } else {
  580. [outputString
  581. appendFormat:@"\tAppID Prefix: %@, Team ID: %@, AppId Prefix equal to Team ID: %@\n",
  582. appIdentifierPrefixes[0], teamID,
  583. ([appIdentifierPrefixes[0] isEqualToString:teamID] ? @"YES" : @"NO")];
  584. }
  585. return outputString;
  586. }
  587. + (NSString *)performDiagnosticsIncludingHeaderFooter:(BOOL)includingHeaderFooter
  588. detectedErrors:(nullable NSInteger *)detectedErrors {
  589. NSMutableString *diagnosticString = [[NSMutableString alloc] init];
  590. if (includingHeaderFooter) {
  591. [diagnosticString appendString:@"\n"];
  592. [diagnosticString appendString:kSelfDiagnoseOutputHeader];
  593. }
  594. NSInteger detectedErrorsCnt = 0;
  595. [diagnosticString appendString:[self genericDiagnosticInformation]];
  596. #if TARGET_IPHONE_SIMULATOR
  597. // check is Simulator and print WARNING that Universal Links is not supported on Simulator
  598. [diagnosticString
  599. appendString:@"WARNING: iOS Simulator does not support Universal Links. Firebase "
  600. @"Dynamic Links SDK functionality will be limited. Some FDL "
  601. @"features may be missing or will not work correctly.\n"];
  602. #endif // TARGET_IPHONE_SIMULATOR
  603. id<UIApplicationDelegate> applicationDelegate = [UIApplication sharedApplication].delegate;
  604. if (![applicationDelegate respondsToSelector:@selector(application:openURL:options:)]) {
  605. detectedErrorsCnt++;
  606. [diagnosticString appendFormat:@"ERROR: UIApplication delegate %@ does not implements selector "
  607. @"%@. FDL depends on this implementation to retrieve pending "
  608. @"dynamic link.\n",
  609. applicationDelegate,
  610. NSStringFromSelector(@selector(application:openURL:options:))];
  611. }
  612. // check that Info.plist has custom URL scheme and the scheme is the same as bundleID or
  613. // as customURLScheme passed to FDL iOS SDK
  614. NSString *URLScheme = [FIRDynamicLinks dynamicLinks].URLScheme;
  615. BOOL URLSchemeFoundInPlist = NO;
  616. NSArray *URLSchemesFromInfoPlist = [[NSBundle mainBundle] infoDictionary][@"CFBundleURLTypes"];
  617. for (NSDictionary *schemeDetails in URLSchemesFromInfoPlist) {
  618. NSArray *arrayOfSchemes = schemeDetails[@"CFBundleURLSchemes"];
  619. for (NSString *scheme in arrayOfSchemes) {
  620. if ([scheme isEqualToString:URLScheme]) {
  621. URLSchemeFoundInPlist = YES;
  622. break;
  623. }
  624. }
  625. if (URLSchemeFoundInPlist) {
  626. break;
  627. }
  628. }
  629. if (!URLSchemeFoundInPlist) {
  630. detectedErrorsCnt++;
  631. [diagnosticString appendFormat:@"ERROR: Specified custom URL scheme is %@ but Info.plist do "
  632. @"not contain such scheme in "
  633. "CFBundleURLTypes key.\n",
  634. URLScheme];
  635. } else {
  636. [diagnosticString appendFormat:@"\tSpecified custom URL scheme is %@ and Info.plist contains "
  637. @"such scheme in CFBundleURLTypes key.\n",
  638. URLScheme];
  639. }
  640. #if !TARGET_IPHONE_SIMULATOR
  641. // analyse information in entitlements file
  642. NSString *entitlementsAnalysis = [self diagnosticAnalyzeEntitlements];
  643. if (entitlementsAnalysis.length) {
  644. [diagnosticString appendString:entitlementsAnalysis];
  645. }
  646. #endif // TARGET_IPHONE_SIMULATOR
  647. if (includingHeaderFooter) {
  648. if (detectedErrorsCnt == 0) {
  649. [diagnosticString
  650. appendString:@"performDiagnostic completed successfully! No errors found.\n"];
  651. } else {
  652. [diagnosticString
  653. appendFormat:@"performDiagnostic detected %ld ERRORS.\n", (long)detectedErrorsCnt];
  654. }
  655. [diagnosticString appendString:kSelfDiagnoseOutputFooter];
  656. }
  657. if (detectedErrors) {
  658. *detectedErrors = detectedErrorsCnt;
  659. }
  660. return [diagnosticString copy];
  661. }
  662. + (void)performDiagnosticsWithCompletion:(void (^_Nullable)(NSString *diagnosticOutput,
  663. BOOL hasErrors))completionHandler;
  664. {
  665. NSInteger detectedErrorsCnt = 0;
  666. NSString *diagnosticString = [self performDiagnosticsIncludingHeaderFooter:YES
  667. detectedErrors:&detectedErrorsCnt];
  668. if (completionHandler) {
  669. completionHandler(diagnosticString, detectedErrorsCnt > 0);
  670. } else {
  671. NSLog(@"%@", diagnosticString);
  672. }
  673. }
  674. @end
  675. NS_ASSUME_NONNULL_END
  676. #endif // TARGET_OS_IOS