FIRDynamicLinks.m 30 KB

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