FIRDynamicLinks.m 30 KB

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