FIRDynamicLinks.m 29 KB

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