FIRDynamicLinks.m 30 KB

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