react-native-webview.git

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