如果服务器是持有自签名证书,React-Native fetch访问会报错
解决方法:
找到RCTNetwork.xcodeproj中的RCTHTTPRequestHandler.m文件,
在#pragma mark - NSURLSession delegate下面增加以下代码:
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}
关于react-native-webview加载自签名的https证书
解决办法:
在plist文件中设置Allow Arbitrary Loads in Web Content 置为 YES,并
在RNCWebView.m文件中找到以下方法
- (void) webView:(WKWebView*)webView
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void(^)(NSURLSessionAuthChallengeDispositiondisposition,NSURLCredential*_Nullable))completionHandler
增加以下代码即可:
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,card);
return;
}
如下图所示: