FIRDynamicLinks.m 30 KB

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