Ei kuvausta

RNCWebView.m 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RNCWebView.h"
  8. #import <React/RCTConvert.h>
  9. #import <React/RCTAutoInsetsProtocol.h>
  10. #import "RNCWKProcessPoolManager.h"
  11. #import <UIKit/UIKit.h>
  12. #import "objc/runtime.h"
  13. static NSTimer *keyboardTimer;
  14. static NSString *const MessageHandlerName = @"ReactNativeWebView";
  15. static NSURLCredential* clientAuthenticationCredential;
  16. static NSDictionary* customCertificatesForHost;
  17. // runtime trick to remove WKWebView keyboard default toolbar
  18. // see: http://stackoverflow.com/questions/19033292/ios-7-uiwebview-keyboard-issue/19042279#19042279
  19. @interface _SwizzleHelperWK : UIView
  20. @property (nonatomic, copy) WKWebView *webView;
  21. @end
  22. @implementation _SwizzleHelperWK
  23. -(id)inputAccessoryView
  24. {
  25. if (_webView == nil) {
  26. return nil;
  27. }
  28. if ([_webView respondsToSelector:@selector(inputAssistantItem)]) {
  29. UITextInputAssistantItem *inputAssistantItem = [_webView inputAssistantItem];
  30. inputAssistantItem.leadingBarButtonGroups = @[];
  31. inputAssistantItem.trailingBarButtonGroups = @[];
  32. }
  33. return nil;
  34. }
  35. @end
  36. @interface RNCWebView () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, UIScrollViewDelegate, RCTAutoInsetsProtocol>
  37. @property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
  38. @property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
  39. @property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
  40. @property (nonatomic, copy) RCTDirectEventBlock onLoadingProgress;
  41. @property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
  42. @property (nonatomic, copy) RCTDirectEventBlock onHttpError;
  43. @property (nonatomic, copy) RCTDirectEventBlock onMessage;
  44. @property (nonatomic, copy) RCTDirectEventBlock onScroll;
  45. @property (nonatomic, copy) RCTDirectEventBlock onContentProcessDidTerminate;
  46. @property (nonatomic, copy) WKWebView *webView;
  47. @end
  48. @implementation RNCWebView
  49. {
  50. UIColor * _savedBackgroundColor;
  51. BOOL _savedHideKeyboardAccessoryView;
  52. BOOL _savedKeyboardDisplayRequiresUserAction;
  53. // Workaround for StatusBar appearance bug for iOS 12
  54. // https://github.com/react-native-community/react-native-webview/issues/62
  55. BOOL _isFullScreenVideoOpen;
  56. UIStatusBarStyle _savedStatusBarStyle;
  57. BOOL _savedStatusBarHidden;
  58. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  59. UIScrollViewContentInsetAdjustmentBehavior _savedContentInsetAdjustmentBehavior;
  60. #endif
  61. }
  62. - (instancetype)initWithFrame:(CGRect)frame
  63. {
  64. if ((self = [super initWithFrame:frame])) {
  65. super.backgroundColor = [UIColor clearColor];
  66. _bounces = YES;
  67. _scrollEnabled = YES;
  68. _showsHorizontalScrollIndicator = YES;
  69. _showsVerticalScrollIndicator = YES;
  70. _directionalLockEnabled = YES;
  71. _automaticallyAdjustContentInsets = YES;
  72. _contentInset = UIEdgeInsetsZero;
  73. _savedKeyboardDisplayRequiresUserAction = YES;
  74. _savedStatusBarStyle = RCTSharedApplication().statusBarStyle;
  75. _savedStatusBarHidden = RCTSharedApplication().statusBarHidden;
  76. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  77. _savedContentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  78. #endif
  79. }
  80. if (@available(iOS 12.0, *)) {
  81. // Workaround for a keyboard dismissal bug present in iOS 12
  82. // https://openradar.appspot.com/radar?id=5018321736957952
  83. [[NSNotificationCenter defaultCenter]
  84. addObserver:self
  85. selector:@selector(keyboardWillHide)
  86. name:UIKeyboardWillHideNotification object:nil];
  87. [[NSNotificationCenter defaultCenter]
  88. addObserver:self
  89. selector:@selector(keyboardWillShow)
  90. name:UIKeyboardWillShowNotification object:nil];
  91. // Workaround for StatusBar appearance bug for iOS 12
  92. // https://github.com/react-native-community/react-native-webview/issues/62
  93. [[NSNotificationCenter defaultCenter] addObserver:self
  94. selector:@selector(showFullScreenVideoStatusBars)
  95. name:UIWindowDidBecomeVisibleNotification
  96. object:nil];
  97. [[NSNotificationCenter defaultCenter] addObserver:self
  98. selector:@selector(hideFullScreenVideoStatusBars)
  99. name:UIWindowDidBecomeHiddenNotification
  100. object:nil];
  101. }
  102. return self;
  103. }
  104. - (void)dealloc
  105. {
  106. [[NSNotificationCenter defaultCenter] removeObserver:self];
  107. }
  108. /**
  109. * See https://stackoverflow.com/questions/25713069/why-is-wkwebview-not-opening-links-with-target-blank/25853806#25853806 for details.
  110. */
  111. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
  112. {
  113. if (!navigationAction.targetFrame.isMainFrame) {
  114. [webView loadRequest:navigationAction.request];
  115. }
  116. return nil;
  117. }
  118. - (void)didMoveToWindow
  119. {
  120. if (self.window != nil && _webView == nil) {
  121. WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
  122. WKPreferences *prefs = [[WKPreferences alloc]init];
  123. if (!_javaScriptEnabled) {
  124. prefs.javaScriptEnabled = NO;
  125. wkWebViewConfig.preferences = prefs;
  126. }
  127. if (_incognito) {
  128. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
  129. } else if (_cacheEnabled) {
  130. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  131. }
  132. if(self.useSharedProcessPool) {
  133. wkWebViewConfig.processPool = [[RNCWKProcessPoolManager sharedManager] sharedProcessPool];
  134. }
  135. wkWebViewConfig.userContentController = [WKUserContentController new];
  136. if (_messagingEnabled) {
  137. [wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName];
  138. NSString *source = [NSString stringWithFormat:
  139. @"window.%@ = {"
  140. " postMessage: function (data) {"
  141. " window.webkit.messageHandlers.%@.postMessage(String(data));"
  142. " }"
  143. "};", MessageHandlerName, MessageHandlerName
  144. ];
  145. WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  146. [wkWebViewConfig.userContentController addUserScript:script];
  147. if (_injectedJavaScriptBeforeContentLoaded) {
  148. // If user has provided an injectedJavascript prop, execute it at the start of the document
  149. WKUserScript *injectedScript = [[WKUserScript alloc] initWithSource:_injectedJavaScriptBeforeContentLoaded injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  150. [wkWebViewConfig.userContentController addUserScript:injectedScript];
  151. }
  152. }
  153. wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
  154. #if WEBKIT_IOS_10_APIS_AVAILABLE
  155. wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
  156. ? WKAudiovisualMediaTypeAll
  157. : WKAudiovisualMediaTypeNone;
  158. wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
  159. #else
  160. wkWebViewConfig.mediaPlaybackRequiresUserAction = _mediaPlaybackRequiresUserAction;
  161. #endif
  162. if (_applicationNameForUserAgent) {
  163. wkWebViewConfig.applicationNameForUserAgent = [NSString stringWithFormat:@"%@ %@", wkWebViewConfig.applicationNameForUserAgent, _applicationNameForUserAgent];
  164. }
  165. if(_sharedCookiesEnabled) {
  166. // More info to sending cookies with WKWebView
  167. // https://stackoverflow.com/questions/26573137/can-i-set-the-cookies-to-be-used-by-a-wkwebview/26577303#26577303
  168. if (@available(iOS 11.0, *)) {
  169. // Set Cookies in iOS 11 and above, initialize websiteDataStore before setting cookies
  170. // See also https://forums.developer.apple.com/thread/97194
  171. // check if websiteDataStore has not been initialized before
  172. if(!_incognito && !_cacheEnabled) {
  173. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
  174. }
  175. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
  176. [wkWebViewConfig.websiteDataStore.httpCookieStore setCookie:cookie completionHandler:nil];
  177. }
  178. } else {
  179. NSMutableString *script = [NSMutableString string];
  180. // Clear all existing cookies in a direct called function. This ensures that no
  181. // javascript error will break the web content javascript.
  182. // We keep this code here, if someone requires that Cookies are also removed within the
  183. // the WebView and want to extends the current sharedCookiesEnabled option with an
  184. // additional property.
  185. // Generates JS: document.cookie = "key=; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"
  186. // for each cookie which is already available in the WebView context.
  187. /*
  188. [script appendString:@"(function () {\n"];
  189. [script appendString:@" var cookies = document.cookie.split('; ');\n"];
  190. [script appendString:@" for (var i = 0; i < cookies.length; i++) {\n"];
  191. [script appendString:@" if (cookies[i].indexOf('=') !== -1) {\n"];
  192. [script appendString:@" document.cookie = cookies[i].split('=')[0] + '=; Expires=Thu, 01 Jan 1970 00:00:01 GMT';\n"];
  193. [script appendString:@" }\n"];
  194. [script appendString:@" }\n"];
  195. [script appendString:@"})();\n\n"];
  196. */
  197. // Set cookies in a direct called function. This ensures that no
  198. // javascript error will break the web content javascript.
  199. // Generates JS: document.cookie = "key=value; Path=/; Expires=Thu, 01 Jan 20xx 00:00:01 GMT;"
  200. // for each cookie which is available in the application context.
  201. [script appendString:@"(function () {\n"];
  202. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
  203. [script appendFormat:@"document.cookie = %@ + '=' + %@",
  204. RCTJSONStringify(cookie.name, NULL),
  205. RCTJSONStringify(cookie.value, NULL)];
  206. if (cookie.path) {
  207. [script appendFormat:@" + '; Path=' + %@", RCTJSONStringify(cookie.path, NULL)];
  208. }
  209. if (cookie.expiresDate) {
  210. [script appendFormat:@" + '; Expires=' + new Date(%f).toUTCString()",
  211. cookie.expiresDate.timeIntervalSince1970 * 1000
  212. ];
  213. }
  214. [script appendString:@";\n"];
  215. }
  216. [script appendString:@"})();\n"];
  217. WKUserScript* cookieInScript = [[WKUserScript alloc] initWithSource:script
  218. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  219. forMainFrameOnly:YES];
  220. [wkWebViewConfig.userContentController addUserScript:cookieInScript];
  221. }
  222. }
  223. _webView = [[WKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
  224. [self setBackgroundColor: _savedBackgroundColor];
  225. _webView.scrollView.delegate = self;
  226. _webView.UIDelegate = self;
  227. _webView.navigationDelegate = self;
  228. _webView.scrollView.scrollEnabled = _scrollEnabled;
  229. _webView.scrollView.pagingEnabled = _pagingEnabled;
  230. _webView.scrollView.bounces = _bounces;
  231. _webView.scrollView.showsHorizontalScrollIndicator = _showsHorizontalScrollIndicator;
  232. _webView.scrollView.showsVerticalScrollIndicator = _showsVerticalScrollIndicator;
  233. _webView.scrollView.directionalLockEnabled = _directionalLockEnabled;
  234. _webView.allowsLinkPreview = _allowsLinkPreview;
  235. [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
  236. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  237. if (_userAgent) {
  238. _webView.customUserAgent = _userAgent;
  239. }
  240. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  241. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  242. _webView.scrollView.contentInsetAdjustmentBehavior = _savedContentInsetAdjustmentBehavior;
  243. }
  244. #endif
  245. [self addSubview:_webView];
  246. [self setHideKeyboardAccessoryView: _savedHideKeyboardAccessoryView];
  247. [self setKeyboardDisplayRequiresUserAction: _savedKeyboardDisplayRequiresUserAction];
  248. [self visitSource];
  249. }
  250. }
  251. // Update webview property when the component prop changes.
  252. - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures {
  253. _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
  254. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  255. }
  256. - (void)removeFromSuperview
  257. {
  258. if (_webView) {
  259. [_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHandlerName];
  260. [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
  261. [_webView removeFromSuperview];
  262. _webView.scrollView.delegate = nil;
  263. _webView = nil;
  264. }
  265. [super removeFromSuperview];
  266. }
  267. -(void)showFullScreenVideoStatusBars
  268. {
  269. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  270. _isFullScreenVideoOpen = YES;
  271. RCTUnsafeExecuteOnMainQueueSync(^{
  272. [RCTSharedApplication() setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
  273. });
  274. #pragma clang diagnostic pop
  275. }
  276. -(void)hideFullScreenVideoStatusBars
  277. {
  278. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  279. _isFullScreenVideoOpen = NO;
  280. RCTUnsafeExecuteOnMainQueueSync(^{
  281. [RCTSharedApplication() setStatusBarHidden:self->_savedStatusBarHidden animated:YES];
  282. [RCTSharedApplication() setStatusBarStyle:self->_savedStatusBarStyle animated:YES];
  283. });
  284. #pragma clang diagnostic pop
  285. }
  286. -(void)keyboardWillHide
  287. {
  288. keyboardTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(keyboardDisplacementFix) userInfo:nil repeats:false];
  289. [[NSRunLoop mainRunLoop] addTimer:keyboardTimer forMode:NSRunLoopCommonModes];
  290. }
  291. -(void)keyboardWillShow
  292. {
  293. if (keyboardTimer != nil) {
  294. [keyboardTimer invalidate];
  295. }
  296. }
  297. -(void)keyboardDisplacementFix
  298. {
  299. // Additional viewport checks to prevent unintentional scrolls
  300. UIScrollView *scrollView = self.webView.scrollView;
  301. double maxContentOffset = scrollView.contentSize.height - scrollView.frame.size.height;
  302. if (maxContentOffset < 0) {
  303. maxContentOffset = 0;
  304. }
  305. if (scrollView.contentOffset.y > maxContentOffset) {
  306. // https://stackoverflow.com/a/9637807/824966
  307. [UIView animateWithDuration:.25 animations:^{
  308. scrollView.contentOffset = CGPointMake(0, maxContentOffset);
  309. }];
  310. }
  311. }
  312. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  313. if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
  314. if(_onLoadingProgress){
  315. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  316. [event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
  317. _onLoadingProgress(event);
  318. }
  319. }else{
  320. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  321. }
  322. }
  323. - (void)setBackgroundColor:(UIColor *)backgroundColor
  324. {
  325. _savedBackgroundColor = backgroundColor;
  326. if (_webView == nil) {
  327. return;
  328. }
  329. CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  330. self.opaque = _webView.opaque = (alpha == 1.0);
  331. _webView.scrollView.backgroundColor = backgroundColor;
  332. _webView.backgroundColor = backgroundColor;
  333. }
  334. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  335. - (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)behavior
  336. {
  337. _savedContentInsetAdjustmentBehavior = behavior;
  338. if (_webView == nil) {
  339. return;
  340. }
  341. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  342. CGPoint contentOffset = _webView.scrollView.contentOffset;
  343. _webView.scrollView.contentInsetAdjustmentBehavior = behavior;
  344. _webView.scrollView.contentOffset = contentOffset;
  345. }
  346. }
  347. #endif
  348. /**
  349. * This method is called whenever JavaScript running within the web view calls:
  350. * - window.webkit.messageHandlers[MessageHandlerName].postMessage
  351. */
  352. - (void)userContentController:(WKUserContentController *)userContentController
  353. didReceiveScriptMessage:(WKScriptMessage *)message
  354. {
  355. if (_onMessage != nil) {
  356. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  357. [event addEntriesFromDictionary: @{@"data": message.body}];
  358. _onMessage(event);
  359. }
  360. }
  361. - (void)setSource:(NSDictionary *)source
  362. {
  363. if (![_source isEqualToDictionary:source]) {
  364. _source = [source copy];
  365. if (_webView != nil) {
  366. [self visitSource];
  367. }
  368. }
  369. }
  370. - (void)setAllowingReadAccessToURL:(NSString *)allowingReadAccessToURL
  371. {
  372. if (![_allowingReadAccessToURL isEqualToString:allowingReadAccessToURL]) {
  373. _allowingReadAccessToURL = [allowingReadAccessToURL copy];
  374. if (_webView != nil) {
  375. [self visitSource];
  376. }
  377. }
  378. }
  379. - (void)setContentInset:(UIEdgeInsets)contentInset
  380. {
  381. _contentInset = contentInset;
  382. [RCTView autoAdjustInsetsForView:self
  383. withScrollView:_webView.scrollView
  384. updateOffset:NO];
  385. }
  386. - (void)refreshContentInset
  387. {
  388. [RCTView autoAdjustInsetsForView:self
  389. withScrollView:_webView.scrollView
  390. updateOffset:YES];
  391. }
  392. - (void)visitSource
  393. {
  394. // Check for a static html source first
  395. NSString *html = [RCTConvert NSString:_source[@"html"]];
  396. if (html) {
  397. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  398. if (!baseURL) {
  399. baseURL = [NSURL URLWithString:@"about:blank"];
  400. }
  401. [_webView loadHTMLString:html baseURL:baseURL];
  402. return;
  403. }
  404. NSURLRequest *request = [self requestForSource:_source];
  405. // Because of the way React works, as pages redirect, we actually end up
  406. // passing the redirect urls back here, so we ignore them if trying to load
  407. // the same url. We'll expose a call to 'reload' to allow a user to load
  408. // the existing page.
  409. if ([request.URL isEqual:_webView.URL]) {
  410. return;
  411. }
  412. if (!request.URL) {
  413. // Clear the webview
  414. [_webView loadHTMLString:@"" baseURL:nil];
  415. return;
  416. }
  417. if (request.URL.host) {
  418. [_webView loadRequest:request];
  419. }
  420. else {
  421. NSURL* readAccessUrl = _allowingReadAccessToURL ? [RCTConvert NSURL:_allowingReadAccessToURL] : request.URL;
  422. [_webView loadFileURL:request.URL allowingReadAccessToURL:readAccessUrl];
  423. }
  424. }
  425. -(void)setKeyboardDisplayRequiresUserAction:(BOOL)keyboardDisplayRequiresUserAction
  426. {
  427. if (_webView == nil) {
  428. _savedKeyboardDisplayRequiresUserAction = keyboardDisplayRequiresUserAction;
  429. return;
  430. }
  431. if (_savedKeyboardDisplayRequiresUserAction == true) {
  432. return;
  433. }
  434. UIView* subview;
  435. for (UIView* view in _webView.scrollView.subviews) {
  436. if([[view.class description] hasPrefix:@"WK"])
  437. subview = view;
  438. }
  439. if(subview == nil) return;
  440. Class class = subview.class;
  441. NSOperatingSystemVersion iOS_11_3_0 = (NSOperatingSystemVersion){11, 3, 0};
  442. NSOperatingSystemVersion iOS_12_2_0 = (NSOperatingSystemVersion){12, 2, 0};
  443. NSOperatingSystemVersion iOS_13_0_0 = (NSOperatingSystemVersion){13, 0, 0};
  444. Method method;
  445. IMP override;
  446. if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_13_0_0]) {
  447. // iOS 13.0.0 - Future
  448. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:");
  449. method = class_getInstanceMethod(class, selector);
  450. IMP original = method_getImplementation(method);
  451. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  452. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  453. });
  454. }
  455. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_12_2_0]) {
  456. // iOS 12.2.0 - iOS 13.0.0
  457. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  458. method = class_getInstanceMethod(class, selector);
  459. IMP original = method_getImplementation(method);
  460. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  461. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  462. });
  463. }
  464. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_11_3_0]) {
  465. // iOS 11.3.0 - 12.2.0
  466. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  467. method = class_getInstanceMethod(class, selector);
  468. IMP original = method_getImplementation(method);
  469. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  470. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  471. });
  472. } else {
  473. // iOS 9.0 - 11.3.0
  474. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:");
  475. method = class_getInstanceMethod(class, selector);
  476. IMP original = method_getImplementation(method);
  477. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, id arg3) {
  478. ((void (*)(id, SEL, void*, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3);
  479. });
  480. }
  481. method_setImplementation(method, override);
  482. }
  483. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  484. {
  485. if (_webView == nil) {
  486. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  487. return;
  488. }
  489. if (_savedHideKeyboardAccessoryView == false) {
  490. return;
  491. }
  492. UIView* subview;
  493. for (UIView* view in _webView.scrollView.subviews) {
  494. if([[view.class description] hasPrefix:@"WK"])
  495. subview = view;
  496. }
  497. if(subview == nil) return;
  498. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  499. Class newClass = NSClassFromString(name);
  500. if(newClass == nil)
  501. {
  502. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  503. if(!newClass) return;
  504. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  505. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  506. objc_registerClassPair(newClass);
  507. }
  508. object_setClass(subview, newClass);
  509. }
  510. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  511. {
  512. scrollView.decelerationRate = _decelerationRate;
  513. }
  514. - (void)setScrollEnabled:(BOOL)scrollEnabled
  515. {
  516. _scrollEnabled = scrollEnabled;
  517. _webView.scrollView.scrollEnabled = scrollEnabled;
  518. }
  519. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  520. {
  521. // Don't allow scrolling the scrollView.
  522. if (!_scrollEnabled) {
  523. scrollView.bounds = _webView.bounds;
  524. }
  525. else if (_onScroll != nil) {
  526. NSDictionary *event = @{
  527. @"contentOffset": @{
  528. @"x": @(scrollView.contentOffset.x),
  529. @"y": @(scrollView.contentOffset.y)
  530. },
  531. @"contentInset": @{
  532. @"top": @(scrollView.contentInset.top),
  533. @"left": @(scrollView.contentInset.left),
  534. @"bottom": @(scrollView.contentInset.bottom),
  535. @"right": @(scrollView.contentInset.right)
  536. },
  537. @"contentSize": @{
  538. @"width": @(scrollView.contentSize.width),
  539. @"height": @(scrollView.contentSize.height)
  540. },
  541. @"layoutMeasurement": @{
  542. @"width": @(scrollView.frame.size.width),
  543. @"height": @(scrollView.frame.size.height)
  544. },
  545. @"zoomScale": @(scrollView.zoomScale ?: 1),
  546. };
  547. _onScroll(event);
  548. }
  549. }
  550. - (void)setDirectionalLockEnabled:(BOOL)directionalLockEnabled
  551. {
  552. _directionalLockEnabled = directionalLockEnabled;
  553. _webView.scrollView.directionalLockEnabled = directionalLockEnabled;
  554. }
  555. - (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator
  556. {
  557. _showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  558. _webView.scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  559. }
  560. - (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator
  561. {
  562. _showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  563. _webView.scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  564. }
  565. - (void)postMessage:(NSString *)message
  566. {
  567. NSDictionary *eventInitDict = @{@"data": message};
  568. NSString *source = [NSString
  569. stringWithFormat:@"window.dispatchEvent(new MessageEvent('message', %@));",
  570. RCTJSONStringify(eventInitDict, NULL)
  571. ];
  572. [self injectJavaScript: source];
  573. }
  574. - (void)layoutSubviews
  575. {
  576. [super layoutSubviews];
  577. // Ensure webview takes the position and dimensions of RNCWebView
  578. _webView.frame = self.bounds;
  579. _webView.scrollView.contentInset = _contentInset;
  580. }
  581. - (NSMutableDictionary<NSString *, id> *)baseEvent
  582. {
  583. NSDictionary *event = @{
  584. @"url": _webView.URL.absoluteString ?: @"",
  585. @"title": _webView.title ?: @"",
  586. @"loading" : @(_webView.loading),
  587. @"canGoBack": @(_webView.canGoBack),
  588. @"canGoForward" : @(_webView.canGoForward)
  589. };
  590. return [[NSMutableDictionary alloc] initWithDictionary: event];
  591. }
  592. + (void)setClientAuthenticationCredential:(nullable NSURLCredential*)credential {
  593. clientAuthenticationCredential = credential;
  594. }
  595. + (void)setCustomCertificatesForHost:(nullable NSDictionary*)certificates {
  596. customCertificatesForHost = certificates;
  597. }
  598. - (void) webView:(WKWebView *)webView
  599. didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  600. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
  601. {
  602. NSString* host = nil;
  603. if (webView.URL != nil) {
  604. host = webView.URL.host;
  605. }
  606. if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
  607. completionHandler(NSURLSessionAuthChallengeUseCredential, clientAuthenticationCredential);
  608. return;
  609. }
  610. if ([[challenge protectionSpace] serverTrust] != nil && customCertificatesForHost != nil && host != nil) {
  611. SecCertificateRef localCertificate = (__bridge SecCertificateRef)([customCertificatesForHost objectForKey:host]);
  612. if (localCertificate != nil) {
  613. NSData *localCertificateData = (NSData*) CFBridgingRelease(SecCertificateCopyData(localCertificate));
  614. SecTrustRef trust = [[challenge protectionSpace] serverTrust];
  615. long count = SecTrustGetCertificateCount(trust);
  616. for (long i = 0; i < count; i++) {
  617. SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(trust, i);
  618. if (serverCertificate == nil) { continue; }
  619. NSData *serverCertificateData = (NSData *) CFBridgingRelease(SecCertificateCopyData(serverCertificate));
  620. if ([serverCertificateData isEqualToData:localCertificateData]) {
  621. NSURLCredential *useCredential = [NSURLCredential credentialForTrust:trust];
  622. if (challenge.sender != nil) {
  623. [challenge.sender useCredential:useCredential forAuthenticationChallenge:challenge];
  624. }
  625. completionHandler(NSURLSessionAuthChallengeUseCredential, useCredential);
  626. return;
  627. }
  628. }
  629. }
  630. }
  631. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  632. }
  633. #pragma mark - WKNavigationDelegate methods
  634. /**
  635. * alert
  636. */
  637. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  638. {
  639. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  640. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  641. completionHandler();
  642. }]];
  643. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  644. }
  645. /**
  646. * confirm
  647. */
  648. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  649. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  650. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  651. completionHandler(YES);
  652. }]];
  653. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  654. completionHandler(NO);
  655. }]];
  656. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  657. }
  658. /**
  659. * prompt
  660. */
  661. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{
  662. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
  663. [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  664. textField.text = defaultText;
  665. }];
  666. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  667. completionHandler([[alert.textFields lastObject] text]);
  668. }];
  669. [alert addAction:okAction];
  670. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  671. completionHandler(nil);
  672. }];
  673. [alert addAction:cancelAction];
  674. alert.preferredAction = okAction;
  675. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  676. }
  677. /**
  678. * topViewController
  679. */
  680. -(UIViewController *)topViewController{
  681. UIViewController *controller = [self topViewControllerWithRootViewController:[self getCurrentWindow].rootViewController];
  682. return controller;
  683. }
  684. /**
  685. * topViewControllerWithRootViewController
  686. */
  687. -(UIViewController *)topViewControllerWithRootViewController:(UIViewController *)viewController{
  688. if (viewController==nil) return nil;
  689. if (viewController.presentedViewController!=nil) {
  690. return [self topViewControllerWithRootViewController:viewController.presentedViewController];
  691. } else if ([viewController isKindOfClass:[UITabBarController class]]){
  692. return [self topViewControllerWithRootViewController:[(UITabBarController *)viewController selectedViewController]];
  693. } else if ([viewController isKindOfClass:[UINavigationController class]]){
  694. return [self topViewControllerWithRootViewController:[(UINavigationController *)viewController visibleViewController]];
  695. } else {
  696. return viewController;
  697. }
  698. }
  699. /**
  700. * getCurrentWindow
  701. */
  702. -(UIWindow *)getCurrentWindow{
  703. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  704. if (window.windowLevel!=UIWindowLevelNormal) {
  705. for (UIWindow *wid in [UIApplication sharedApplication].windows) {
  706. if (window.windowLevel==UIWindowLevelNormal) {
  707. window = wid;
  708. break;
  709. }
  710. }
  711. }
  712. return window;
  713. }
  714. /**
  715. * Decides whether to allow or cancel a navigation.
  716. * @see https://fburl.com/42r9fxob
  717. */
  718. - (void) webView:(WKWebView *)webView
  719. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  720. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  721. {
  722. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  723. static dispatch_once_t onceToken;
  724. dispatch_once(&onceToken, ^{
  725. navigationTypes = @{
  726. @(WKNavigationTypeLinkActivated): @"click",
  727. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  728. @(WKNavigationTypeBackForward): @"backforward",
  729. @(WKNavigationTypeReload): @"reload",
  730. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  731. @(WKNavigationTypeOther): @"other",
  732. };
  733. });
  734. WKNavigationType navigationType = navigationAction.navigationType;
  735. NSURLRequest *request = navigationAction.request;
  736. if (_onShouldStartLoadWithRequest) {
  737. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  738. [event addEntriesFromDictionary: @{
  739. @"url": (request.URL).absoluteString,
  740. @"mainDocumentURL": (request.mainDocumentURL).absoluteString,
  741. @"navigationType": navigationTypes[@(navigationType)]
  742. }];
  743. if (![self.delegate webView:self
  744. shouldStartLoadForRequest:event
  745. withCallback:_onShouldStartLoadWithRequest]) {
  746. decisionHandler(WKNavigationActionPolicyCancel);
  747. return;
  748. }
  749. }
  750. if (_onLoadingStart) {
  751. // We have this check to filter out iframe requests and whatnot
  752. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  753. if (isTopFrame) {
  754. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  755. [event addEntriesFromDictionary: @{
  756. @"url": (request.URL).absoluteString,
  757. @"navigationType": navigationTypes[@(navigationType)]
  758. }];
  759. _onLoadingStart(event);
  760. }
  761. }
  762. // Allow all navigation by default
  763. decisionHandler(WKNavigationActionPolicyAllow);
  764. }
  765. /**
  766. * Called when the web view’s content process is terminated.
  767. * @see https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455639-webviewwebcontentprocessdidtermi?language=objc
  768. */
  769. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
  770. {
  771. RCTLogWarn(@"Webview Process Terminated");
  772. if (_onContentProcessDidTerminate) {
  773. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  774. _onContentProcessDidTerminate(event);
  775. }
  776. }
  777. /**
  778. * Decides whether to allow or cancel a navigation after its response is known.
  779. * @see https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview?language=objc
  780. */
  781. - (void) webView:(WKWebView *)webView
  782. decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
  783. decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
  784. {
  785. if (_onHttpError && navigationResponse.forMainFrame) {
  786. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  787. NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
  788. NSInteger statusCode = response.statusCode;
  789. if (statusCode >= 400) {
  790. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  791. [event addEntriesFromDictionary: @{
  792. @"url": response.URL.absoluteString,
  793. @"statusCode": @(statusCode)
  794. }];
  795. _onHttpError(event);
  796. }
  797. }
  798. }
  799. decisionHandler(WKNavigationResponsePolicyAllow);
  800. }
  801. /**
  802. * Called when an error occurs while the web view is loading content.
  803. * @see https://fburl.com/km6vqenw
  804. */
  805. - (void) webView:(WKWebView *)webView
  806. didFailProvisionalNavigation:(WKNavigation *)navigation
  807. withError:(NSError *)error
  808. {
  809. if (_onLoadingError) {
  810. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  811. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  812. // a new URL in the WebView before the previous one came back. We can just
  813. // ignore these since they aren't real errors.
  814. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  815. return;
  816. }
  817. if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102) {
  818. // Error code 102 "Frame load interrupted" is raised by the WKWebView
  819. // when the URL is from an http redirect. This is a common pattern when
  820. // implementing OAuth with a WebView.
  821. return;
  822. }
  823. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  824. [event addEntriesFromDictionary:@{
  825. @"didFailProvisionalNavigation": @YES,
  826. @"domain": error.domain,
  827. @"code": @(error.code),
  828. @"description": error.localizedDescription,
  829. }];
  830. _onLoadingError(event);
  831. }
  832. }
  833. - (void)evaluateJS:(NSString *)js
  834. thenCall: (void (^)(NSString*)) callback
  835. {
  836. [self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
  837. if (callback != nil) {
  838. callback([NSString stringWithFormat:@"%@", result]);
  839. }
  840. if (error != nil) {
  841. RCTLogWarn(@"%@", [NSString stringWithFormat:@"Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string. %@", error]);
  842. }
  843. }];
  844. }
  845. /**
  846. * Called when the navigation is complete.
  847. * @see https://fburl.com/rtys6jlb
  848. */
  849. - (void)webView:(WKWebView *)webView
  850. didFinishNavigation:(WKNavigation *)navigation
  851. {
  852. if (_injectedJavaScript) {
  853. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  854. NSMutableDictionary *event = [self baseEvent];
  855. event[@"jsEvaluationValue"] = jsEvaluationValue;
  856. if (self.onLoadingFinish) {
  857. self.onLoadingFinish(event);
  858. }
  859. }];
  860. } else if (_onLoadingFinish) {
  861. _onLoadingFinish([self baseEvent]);
  862. }
  863. }
  864. - (void)injectJavaScript:(NSString *)script
  865. {
  866. [self evaluateJS: script thenCall: nil];
  867. }
  868. - (void)goForward
  869. {
  870. [_webView goForward];
  871. }
  872. - (void)goBack
  873. {
  874. [_webView goBack];
  875. }
  876. - (void)reload
  877. {
  878. /**
  879. * When the initial load fails due to network connectivity issues,
  880. * [_webView reload] doesn't reload the webpage. Therefore, we must
  881. * manually call [_webView loadRequest:request].
  882. */
  883. NSURLRequest *request = [self requestForSource:self.source];
  884. if (request.URL && !_webView.URL.absoluteString.length) {
  885. [_webView loadRequest:request];
  886. } else {
  887. [_webView reload];
  888. }
  889. }
  890. - (void)stopLoading
  891. {
  892. [_webView stopLoading];
  893. }
  894. - (void)setBounces:(BOOL)bounces
  895. {
  896. _bounces = bounces;
  897. _webView.scrollView.bounces = bounces;
  898. }
  899. - (NSURLRequest *)requestForSource:(id)json {
  900. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  901. // If sharedCookiesEnabled we automatically add all application cookies to the
  902. // http request. This is automatically done on iOS 11+ in the WebView constructor.
  903. // Se we need to manually add these shared cookies here only for iOS versions < 11.
  904. if (_sharedCookiesEnabled) {
  905. if (@available(iOS 11.0, *)) {
  906. // see WKWebView initialization for added cookies
  907. } else {
  908. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
  909. NSDictionary<NSString *, NSString *> *cookieHeader = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
  910. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  911. [mutableRequest setAllHTTPHeaderFields:cookieHeader];
  912. return mutableRequest;
  913. }
  914. }
  915. return request;
  916. }
  917. @end