FIRDynamicLinks.m 29 KB

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