FIRDynamicLinks.m 30 KB

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