FIRDynamicLinks.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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. #else
  25. #import "FirebaseCore/Sources/Public/FirebaseCore/FIRVersion.h"
  26. #endif
  27. #ifdef FIRDynamicLinks3P
  28. #import "FirebaseDynamicLinks/Sources/FDLURLComponents/FDLURLComponents+Private.h"
  29. #endif
  30. #import "FirebaseDynamicLinks/Sources/FIRDLRetrievalProcessFactory.h"
  31. #import "FirebaseDynamicLinks/Sources/FIRDLRetrievalProcessProtocols.h"
  32. #import "FirebaseDynamicLinks/Sources/FIRDLRetrievalProcessResult.h"
  33. #import "FirebaseDynamicLinks/Sources/FIRDynamicLink+Private.h"
  34. #import "FirebaseDynamicLinks/Sources/FIRDynamicLinkNetworking.h"
  35. #import "FirebaseDynamicLinks/Sources/FIRDynamicLinks+FirstParty.h"
  36. #import "FirebaseDynamicLinks/Sources/FIRDynamicLinks+Private.h"
  37. #import "FirebaseDynamicLinks/Sources/Logging/FDLLogging.h"
  38. #import "FirebaseDynamicLinks/Sources/Utilities/FDLUtilities.h"
  39. // We should only read the deeplink after install once. We use the following key to store the state
  40. // in the user defaults.
  41. NSString *const kFIRDLReadDeepLinkAfterInstallKey =
  42. @"com.google.appinvite.readDeeplinkAfterInstall";
  43. // We should only open url once. We use the following key to store the state in the user defaults.
  44. static NSString *const kFIRDLOpenURLKey = @"com.google.appinvite.openURL";
  45. // Custom domains to be whitelisted are optionally added as an array to the info.plist.
  46. static NSString *const kInfoPlistCustomDomainsKey = @"FirebaseDynamicLinksCustomDomains";
  47. NS_ASSUME_NONNULL_BEGIN
  48. @interface FIRDynamicLinks () <FIRDLRetrievalProcessDelegate>
  49. // API Key for API access.
  50. @property(nonatomic, copy) NSString *APIKey;
  51. // Custom URL scheme.
  52. @property(nonatomic, copy) NSString *URLScheme;
  53. // Networking object for Dynamic Links
  54. @property(nonatomic, readonly) FIRDynamicLinkNetworking *dynamicLinkNetworking;
  55. @property(atomic, assign) BOOL retrievingPendingDynamicLink;
  56. @end
  57. #ifdef FIRDynamicLinks3P
  58. // Error code from FDL.
  59. static const NSInteger FIRErrorCodeDurableDeepLinkFailed = -119;
  60. @interface FIRDynamicLinks () {
  61. /// Stored Analytics reference, if it exists.
  62. id<FIRAnalyticsInterop> _Nullable _analytics;
  63. }
  64. @end
  65. // DynamicLinks doesn't provide any functionality to other components,
  66. // so it provides a private, empty protocol that it conforms to and use it for registration.
  67. @protocol FIRDynamicLinksInstanceProvider
  68. @end
  69. @interface FIRDynamicLinks () <FIRDynamicLinksInstanceProvider, FIRLibrary>
  70. @end
  71. #endif
  72. @implementation FIRDynamicLinks {
  73. // User defaults passed.
  74. NSUserDefaults *_userDefaults;
  75. FIRDynamicLinkNetworking *_dynamicLinkNetworking;
  76. id<FIRDLRetrievalProcessProtocol> _retrievalProcess;
  77. }
  78. #pragma mark - Object lifecycle
  79. #ifdef FIRDynamicLinks3P
  80. + (void)load {
  81. [FIRApp registerInternalLibrary:self withName:@"fire-dl"];
  82. }
  83. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  84. // Product requirement is enforced by CocoaPod. Not technical requirement for analytics.
  85. FIRDependency *analyticsDep = [FIRDependency dependencyWithProtocol:@protocol(FIRAnalyticsInterop)
  86. isRequired:NO];
  87. FIRComponentCreationBlock creationBlock =
  88. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  89. // Don't return an instance when it's not the default app.
  90. if (!container.app.isDefaultApp) {
  91. // Only configure for the default FIRApp.
  92. FDLLog(FDLLogLevelInfo, FDLLogIdentifierSetupNonDefaultApp,
  93. @"Firebase Dynamic Links only "
  94. "works with the default app.");
  95. return nil;
  96. }
  97. // Ensure it's cached so it returns the same instance every time dynamicLinks is called.
  98. *isCacheable = YES;
  99. id<FIRAnalyticsInterop> analytics = FIR_COMPONENT(FIRAnalyticsInterop, container);
  100. FIRDynamicLinks *dynamicLinks = [[FIRDynamicLinks alloc] initWithAnalytics:analytics];
  101. [dynamicLinks configureDynamicLinks:container.app];
  102. // Check for pending Dynamic Link automatically if enabled, otherwise we expect the developer to
  103. // call strong match FDL API to retrieve a pending link.
  104. if ([FIRDynamicLinks isAutomaticRetrievalEnabled]) {
  105. [dynamicLinks checkForPendingDynamicLink];
  106. }
  107. return dynamicLinks;
  108. };
  109. FIRComponent *dynamicLinksProvider =
  110. [FIRComponent componentWithProtocol:@protocol(FIRDynamicLinksInstanceProvider)
  111. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  112. dependencies:@[ analyticsDep ]
  113. creationBlock:creationBlock];
  114. return @[ dynamicLinksProvider ];
  115. }
  116. - (void)configureDynamicLinks:(FIRApp *)app {
  117. FIROptions *options = app.options;
  118. NSError *error;
  119. NSMutableString *errorDescription;
  120. NSString *urlScheme;
  121. if (options.APIKey.length == 0) {
  122. errorDescription = [@"API key must not be nil or empty." mutableCopy];
  123. }
  124. if (!errorDescription) {
  125. // setup FDL if no error detected
  126. urlScheme = options.deepLinkURLScheme ?: [NSBundle mainBundle].bundleIdentifier;
  127. [self setUpWithLaunchOptions:nil apiKey:options.APIKey urlScheme:urlScheme userDefaults:nil];
  128. } else {
  129. NSString *description =
  130. [NSString stringWithFormat:@"Configuration failed for service DynamicLinks."];
  131. NSDictionary *errorDict = @{
  132. NSLocalizedDescriptionKey : description,
  133. NSLocalizedFailureReasonErrorKey : errorDescription
  134. };
  135. error = [NSError errorWithDomain:kFirebaseDurableDeepLinkErrorDomain
  136. code:FIRErrorCodeDurableDeepLinkFailed
  137. userInfo:errorDict];
  138. }
  139. if (error) {
  140. NSString *message = nil;
  141. if (options.usingOptionsFromDefaultPlist) {
  142. // Configured using plist file
  143. message = [NSString
  144. stringWithFormat:
  145. @"Firebase Dynamic Links has stopped your project "
  146. @"because there are missing or incorrect values provided in %@.%@ that may "
  147. @"prevent your app from behaving as expected:\n\n"
  148. @"Error: %@\n\n"
  149. @"Please fix these issues to ensure that Firebase is correctly configured in "
  150. @"your project.",
  151. kServiceInfoFileName, kServiceInfoFileType, error.localizedFailureReason];
  152. } else {
  153. // Configured manually
  154. message = [NSString
  155. stringWithFormat:
  156. @"Firebase Dynamic Links has stopped your project "
  157. @"because there are incorrect values provided in Firebase's configuration "
  158. @"options that may prevent your app from behaving as expected:\n\n"
  159. @"Error: %@\n\n"
  160. @"Please fix these issues to ensure that Firebase is correctly configured in "
  161. @"your project.",
  162. error.localizedFailureReason];
  163. }
  164. [NSException raise:kFirebaseDurableDeepLinkErrorDomain format:@"%@", message];
  165. }
  166. [self checkForCustomDomainEntriesInInfoPlist];
  167. }
  168. - (instancetype)initWithAnalytics:(nullable id<FIRAnalyticsInterop>)analytics {
  169. self = [super init];
  170. if (self) {
  171. _analytics = analytics;
  172. }
  173. return self;
  174. }
  175. + (instancetype)dynamicLinks {
  176. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  177. id<FIRDynamicLinksInstanceProvider> instance =
  178. FIR_COMPONENT(FIRDynamicLinksInstanceProvider, defaultApp.container);
  179. return (FIRDynamicLinks *)instance;
  180. }
  181. #else
  182. + (instancetype)dynamicLinks {
  183. static FIRDynamicLinks *dynamicLinks;
  184. static dispatch_once_t onceToken;
  185. dispatch_once(&onceToken, ^{
  186. dynamicLinks = [[self alloc] init];
  187. });
  188. return dynamicLinks;
  189. }
  190. #endif
  191. #pragma mark - Custom domains
  192. - (instancetype)init {
  193. self = [super init];
  194. if (self) {
  195. [self checkForCustomDomainEntriesInInfoPlist];
  196. }
  197. return self;
  198. }
  199. // Check for custom domains entry in PLIST file.
  200. - (void)checkForCustomDomainEntriesInInfoPlist {
  201. // Check to see if FirebaseDynamicLinksCustomDomains array is present.
  202. NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary;
  203. NSArray *customDomains = infoDictionary[kInfoPlistCustomDomainsKey];
  204. if (customDomains) {
  205. FIRDLAddToAllowListForCustomDomainsArray(customDomains);
  206. }
  207. }
  208. #pragma mark - First party interface
  209. - (BOOL)setUpWithLaunchOptions:(nullable NSDictionary *)launchOptions
  210. apiKey:(NSString *)apiKey
  211. urlScheme:(nullable NSString *)urlScheme
  212. userDefaults:(nullable NSUserDefaults *)userDefaults {
  213. if (apiKey == nil) {
  214. FDLLog(FDLLogLevelError, FDLLogIdentifierSetupNilAPIKey, @"API Key must not be nil.");
  215. return NO;
  216. }
  217. _APIKey = [apiKey copy];
  218. _URLScheme = urlScheme.length ? [urlScheme copy] : [NSBundle mainBundle].bundleIdentifier;
  219. if (!userDefaults) {
  220. _userDefaults = [NSUserDefaults standardUserDefaults];
  221. } else {
  222. _userDefaults = userDefaults;
  223. }
  224. NSURL *url = launchOptions[UIApplicationLaunchOptionsURLKey];
  225. if (url) {
  226. if ([self canParseCustomSchemeURL:url] || [self canParseUniversalLinkURL:url]) {
  227. // Make sure we don't call |checkForPendingDynamicLink| again if
  228. // a strong deep link is found.
  229. [_userDefaults setBool:YES forKey:kFIRDLReadDeepLinkAfterInstallKey];
  230. }
  231. }
  232. return YES;
  233. }
  234. - (void)checkForPendingDynamicLinkUsingExperimentalRetrievalProcess {
  235. [self checkForPendingDynamicLink];
  236. }
  237. - (void)checkForPendingDynamicLink {
  238. // Make sure this method is called only once after the application was installed.
  239. // kFIRDLOpenURLKey marks checkForPendingDynamic link had been called already so no need to do it
  240. // again. kFIRDLReadDeepLinkAfterInstallKey marks we have already read a deeplink after the
  241. // install and so no need to do check for pending dynamic link.
  242. BOOL appInviteDeepLinkRead = [_userDefaults boolForKey:kFIRDLOpenURLKey] ||
  243. [_userDefaults boolForKey:kFIRDLReadDeepLinkAfterInstallKey];
  244. if (appInviteDeepLinkRead || self.retrievingPendingDynamicLink) {
  245. NSString *errorDescription =
  246. appInviteDeepLinkRead ? NSLocalizedString(@"Link was already retrieved", @"Error message")
  247. : NSLocalizedString(@"Already retrieving link", @"Error message");
  248. [self handlePendingDynamicLinkRetrievalFailureWithErrorCode:-1
  249. errorDescription:errorDescription
  250. underlyingError:nil];
  251. return;
  252. }
  253. self.retrievingPendingDynamicLink = YES;
  254. FIRDLRetrievalProcessFactory *factory =
  255. [[FIRDLRetrievalProcessFactory alloc] initWithNetworkingService:self.dynamicLinkNetworking
  256. URLScheme:_URLScheme
  257. APIKey:_APIKey
  258. FDLSDKVersion:FIRFirebaseVersion()
  259. delegate:self];
  260. _retrievalProcess = [factory automaticRetrievalProcess];
  261. [_retrievalProcess retrievePendingDynamicLink];
  262. }
  263. // Disable deprecated warning for internal methods.
  264. #pragma clang diagnostic push
  265. #pragma clang diagnostic ignored "-Wdeprecated-implementations"
  266. + (instancetype)sharedInstance {
  267. return [self dynamicLinks];
  268. }
  269. - (BOOL)setUpWithLaunchOptions:(nullable NSDictionary *)launchOptions
  270. apiKey:(NSString *)apiKey
  271. clientID:(NSString *)clientID
  272. urlScheme:(nullable NSString *)urlScheme
  273. userDefaults:(nullable NSUserDefaults *)userDefaults {
  274. return [self setUpWithLaunchOptions:launchOptions
  275. apiKey:apiKey
  276. urlScheme:urlScheme
  277. userDefaults:userDefaults];
  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:FIRFirebaseVersion()
  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:FIRFirebaseVersion()
  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. URLScheme:_URLScheme];
  413. }
  414. return _dynamicLinkNetworking;
  415. }
  416. - (BOOL)canParseCustomSchemeURL:(nullable NSURL *)url {
  417. if (url.scheme.length) {
  418. NSString *bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
  419. if ([url.scheme.lowercaseString isEqualToString:_URLScheme.lowercaseString] ||
  420. [url.scheme.lowercaseString isEqualToString:bundleIdentifier.lowercaseString]) {
  421. return YES;
  422. }
  423. }
  424. return NO;
  425. }
  426. - (BOOL)canParseUniversalLinkURL:(nullable NSURL *)url {
  427. return FIRDLCanParseUniversalLinkURL(url);
  428. }
  429. - (BOOL)handleIncomingCustomSchemeDeepLink:(NSURL *)url {
  430. return [self canParseCustomSchemeURL:url];
  431. }
  432. - (void)passRetrievedDynamicLinkToApplication:(NSURL *)url {
  433. id<UIApplicationDelegate> applicationDelegate = [UIApplication sharedApplication].delegate;
  434. if ([self isOpenUrlMethodPresentInAppDelegate:applicationDelegate]) {
  435. // pass url directly to application delegate to avoid hop into
  436. // iOS handling of the universal links
  437. [applicationDelegate application:[UIApplication sharedApplication] openURL:url options:@{}];
  438. return;
  439. }
  440. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  441. }
  442. - (BOOL)isOpenUrlMethodPresentInAppDelegate:(id<UIApplicationDelegate>)applicationDelegate {
  443. return applicationDelegate &&
  444. [applicationDelegate respondsToSelector:@selector(application:openURL:options:)];
  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 (![_userDefaults boolForKey:kFIRDLOpenURLKey]) {
  459. // Once we complete the Pending dynamic link retrieval, regardless of whether the retrieval is
  460. // success or failure, we don't want to do the retrieval again on next app start.
  461. // If we try to redo the retrieval again because of some error, the user will experience
  462. // unwanted deeplinking when they restart the app next time.
  463. [_userDefaults setBool:YES forKey:kFIRDLOpenURLKey];
  464. }
  465. NSURL *linkToPassToApp = [result URLWithCustomURLScheme:_URLScheme];
  466. [self passRetrievedDynamicLinkToApplication:linkToPassToApp];
  467. }
  468. #pragma mark - Diagnostics methods
  469. static NSString *kSelfDiagnoseOutputHeader =
  470. @"---- Firebase Dynamic Links diagnostic output start ----\n";
  471. // TODO (b/38397557) Add link to the "Debug FDL" documentation when docs is published
  472. static NSString *kSelfDiagnoseOutputFooter =
  473. @"---- Firebase Dynamic Links diagnostic output end ----\n";
  474. + (NSString *)genericDiagnosticInformation {
  475. NSMutableString *genericDiagnosticInfo = [[NSMutableString alloc] init];
  476. [genericDiagnosticInfo
  477. appendFormat:@"Firebase Dynamic Links framework version %@\n", FIRFirebaseVersion()];
  478. [genericDiagnosticInfo appendFormat:@"System information: OS %@, OS version %@, model %@\n",
  479. [UIDevice currentDevice].systemName,
  480. [UIDevice currentDevice].systemVersion,
  481. [UIDevice currentDevice].model];
  482. [genericDiagnosticInfo appendFormat:@"Current date %@\n", [NSDate date]];
  483. // TODO: bring this diagnostic info back when we shipped non-automatic retrieval
  484. // [genericDiagnosticInfo appendFormat:@"AutomaticRetrievalEnabled: %@\n",
  485. // [self isAutomaticRetrievalEnabled] ? @"YES" : @"NO"];
  486. // Disable deprecated warning for internal methods.
  487. #pragma clang diagnostic push
  488. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  489. [genericDiagnosticInfo appendFormat:@"Device locale %@ (raw %@), timezone %@\n",
  490. FIRDLDeviceLocale(), FIRDLDeviceLocaleRaw(),
  491. FIRDLDeviceTimezone()];
  492. #pragma clang pop
  493. return genericDiagnosticInfo;
  494. }
  495. + (NSString *)diagnosticAnalyzeEntitlements {
  496. NSString *embeddedMobileprovisionFilePath = [[[NSBundle mainBundle] bundlePath]
  497. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  498. NSError *error;
  499. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:embeddedMobileprovisionFilePath
  500. options:0
  501. error:&error];
  502. if (!profileData.length || error) {
  503. return @"\tSKIPPED: Not able to read entitlements (embedded.mobileprovision).\n";
  504. }
  505. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  506. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  507. // ASCII. Replace any 0s or invalid characters in the input.
  508. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  509. for (int i = 0; i < profileData.length; i++) {
  510. uint8_t currentByte = profileBytes[i];
  511. if (!currentByte || currentByte > 127) {
  512. profileBytes[i] = '.';
  513. }
  514. }
  515. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  516. length:profileData.length
  517. encoding:NSASCIIStringEncoding
  518. freeWhenDone:NO];
  519. if (error || !embeddedProfile.length) {
  520. return @"\tSKIPPED: Not able to read entitlements (embedded.mobileprovision).\n";
  521. }
  522. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  523. NSString *plistContents;
  524. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  525. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  526. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  527. }
  528. }
  529. if (!plistContents.length) {
  530. return @"\tWARNING: Not able to read plist entitlements (embedded.mobileprovision).\n";
  531. }
  532. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  533. if (!data.length) {
  534. return @"\tWARNING: Not able to parse entitlements (embedded.mobileprovision).\n";
  535. }
  536. NSError *plistMapError;
  537. id plistData = [NSPropertyListSerialization propertyListWithData:data
  538. options:NSPropertyListImmutable
  539. format:nil
  540. error:&plistMapError];
  541. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  542. return @"\tWARNING: Not able to deserialize entitlements (embedded.mobileprovision).\n";
  543. }
  544. NSDictionary *plistMap = (NSDictionary *)plistData;
  545. // analyze entitlements and print diagnostic information
  546. // we can't detect erorrs, information p[rinted here may hint developer or will help support
  547. // to identify the issue
  548. NSMutableString *outputString = [[NSMutableString alloc] init];
  549. NSArray *appIdentifierPrefixes = plistMap[@"ApplicationIdentifierPrefix"];
  550. NSString *teamID = plistMap[@"Entitlements"][@"com.apple.developer.team-identifier"];
  551. if (appIdentifierPrefixes.count > 1) {
  552. // is this possible? anyway, we can handle it
  553. [outputString
  554. appendFormat:@"\tAppID Prefixes: %@, Team ID: %@, AppId Prefixes contains to Team ID: %@\n",
  555. appIdentifierPrefixes, teamID,
  556. ([appIdentifierPrefixes containsObject:teamID] ? @"YES" : @"NO")];
  557. } else {
  558. [outputString
  559. appendFormat:@"\tAppID Prefix: %@, Team ID: %@, AppId Prefix equal to Team ID: %@\n",
  560. appIdentifierPrefixes[0], teamID,
  561. ([appIdentifierPrefixes[0] isEqualToString:teamID] ? @"YES" : @"NO")];
  562. }
  563. return outputString;
  564. }
  565. + (NSString *)performDiagnosticsIncludingHeaderFooter:(BOOL)includingHeaderFooter
  566. detectedErrors:(nullable NSInteger *)detectedErrors {
  567. NSMutableString *diagnosticString = [[NSMutableString alloc] init];
  568. if (includingHeaderFooter) {
  569. [diagnosticString appendString:@"\n"];
  570. [diagnosticString appendString:kSelfDiagnoseOutputHeader];
  571. }
  572. NSInteger detectedErrorsCnt = 0;
  573. [diagnosticString appendString:[self genericDiagnosticInformation]];
  574. #if TARGET_IPHONE_SIMULATOR
  575. // check is Simulator and print WARNING that Universal Links is not supported on Simulator
  576. [diagnosticString
  577. appendString:@"WARNING: iOS Simulator does not support Universal Links. Firebase "
  578. @"Dynamic Links SDK functionality will be limited. Some FDL "
  579. @"features may be missing or will not work correctly.\n"];
  580. #endif // TARGET_IPHONE_SIMULATOR
  581. id<UIApplicationDelegate> applicationDelegate = [UIApplication sharedApplication].delegate;
  582. if (![applicationDelegate respondsToSelector:@selector(application:openURL:options:)]) {
  583. detectedErrorsCnt++;
  584. [diagnosticString appendFormat:@"ERROR: UIApplication delegate %@ does not implements selector "
  585. @"%@. FDL depends on this implementation to retrieve pending "
  586. @"dynamic link.\n",
  587. applicationDelegate,
  588. NSStringFromSelector(@selector(application:openURL:options:))];
  589. }
  590. // check that Info.plist has custom URL scheme and the scheme is the same as bundleID or
  591. // as customURLScheme passed to FDL iOS SDK
  592. NSString *URLScheme = [FIRDynamicLinks dynamicLinks].URLScheme;
  593. BOOL URLSchemeFoundInPlist = NO;
  594. NSArray *URLSchemesFromInfoPlist = [[NSBundle mainBundle] infoDictionary][@"CFBundleURLTypes"];
  595. for (NSDictionary *schemeDetails in URLSchemesFromInfoPlist) {
  596. NSArray *arrayOfSchemes = schemeDetails[@"CFBundleURLSchemes"];
  597. for (NSString *scheme in arrayOfSchemes) {
  598. if ([scheme isEqualToString:URLScheme]) {
  599. URLSchemeFoundInPlist = YES;
  600. break;
  601. }
  602. }
  603. if (URLSchemeFoundInPlist) {
  604. break;
  605. }
  606. }
  607. if (!URLSchemeFoundInPlist) {
  608. detectedErrorsCnt++;
  609. [diagnosticString appendFormat:@"ERROR: Specified custom URL scheme is %@ but Info.plist do "
  610. @"not contain such scheme in "
  611. "CFBundleURLTypes key.\n",
  612. URLScheme];
  613. } else {
  614. [diagnosticString appendFormat:@"\tSpecified custom URL scheme is %@ and Info.plist contains "
  615. @"such scheme in CFBundleURLTypes key.\n",
  616. URLScheme];
  617. }
  618. #if !TARGET_IPHONE_SIMULATOR
  619. // analyse information in entitlements file
  620. NSString *entitlementsAnalysis = [self diagnosticAnalyzeEntitlements];
  621. if (entitlementsAnalysis.length) {
  622. [diagnosticString appendString:entitlementsAnalysis];
  623. }
  624. #endif // TARGET_IPHONE_SIMULATOR
  625. if (includingHeaderFooter) {
  626. if (detectedErrorsCnt == 0) {
  627. [diagnosticString
  628. appendString:@"performDiagnostic completed successfully! No errors found.\n"];
  629. } else {
  630. [diagnosticString
  631. appendFormat:@"performDiagnostic detected %ld ERRORS.\n", (long)detectedErrorsCnt];
  632. }
  633. [diagnosticString appendString:kSelfDiagnoseOutputFooter];
  634. }
  635. if (detectedErrors) {
  636. *detectedErrors = detectedErrorsCnt;
  637. }
  638. return [diagnosticString copy];
  639. }
  640. + (void)performDiagnosticsWithCompletion:(void (^_Nullable)(NSString *diagnosticOutput,
  641. BOOL hasErrors))completionHandler;
  642. {
  643. NSInteger detectedErrorsCnt = 0;
  644. NSString *diagnosticString = [self performDiagnosticsIncludingHeaderFooter:YES
  645. detectedErrors:&detectedErrorsCnt];
  646. if (completionHandler) {
  647. completionHandler(diagnosticString, detectedErrorsCnt > 0);
  648. } else {
  649. NSLog(@"%@", diagnosticString);
  650. }
  651. }
  652. @end
  653. NS_ASSUME_NONNULL_END
  654. #endif // TARGET_OS_IOS