iOS:webview使用(一)--https链接

本文详细介绍了如何解决在iOS中使用UIWebView加载HTTPS站点时遇到的NSURLErrorDomaincode=-1202错误,通过重写特定的方法允许使用自签名证书,从而成功加载网页。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        当使用UIWebview加载https的站点时webview总是会报NSURLErrorDomain code=-1202,导致网页加载失败。自己打印错误和网上搜索是因为证书失效,https使用超文本安全传 输协议,即超文本传输协议(HTTP)和SSL/TLS的组合,用以提供加密通讯及对网络服务器身份的鉴定。当我们的服务器使用自我签名证书时,而UIWebView不允许使用自签名证书,所以导致加载失败。

        解决办法: you're using a self-signed certificate, it's necessary to add some additional code.Because by default iOS will reject all untrusted https connections。重写下面俩个方法:

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
#import "ClassCon.h"
//  For now, I've hard coded the IP address of my trusted server.
#define TRUSTED_HOST @"192.168.1.2"

@implementation ClassCon {
    NSMutableData *contentData;
    NSURLConnection *conn;
}
-(void) loadContent {
    contentData = [NSMutableData data];
    NSString *contentURL = @"our url";
    conn = [[NSURLConnection alloc] initWithRequest:
            [NSURLRequest requestWithURL:[NSURL URLWithString:contentURL]] delegate:self];

}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [contentData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Bad: %@", [error description]);
    ContentResponse *response = [[ContentResponse alloc]initWithRc:-999 andDescr:@"error" andAction:0];
    conn = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        NSString *loadedContent = [[NSString alloc] initWithData:
                                     contentData encoding:NSUTF8StringEncoding];
        NSLog(@"Loaded content: %@",loadedContent);

    }

// ------------ ByPass ssl starts ----------
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:
(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod
            isEqualToString:NSURLAuthenticationMethodServerTrust];
}

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:
(NSURLAuthenticationChallenge *)challenge {
    if (([challenge.protectionSpace.authenticationMethod
          isEqualToString:NSURLAuthenticationMethodServerTrust])) {
        if ([challenge.protectionSpace.host isEqualToString:TRUSTED_HOST]) {
            NSLog(@"Allowing bypass...");
            NSURLCredential *credential = [NSURLCredential credentialForTrust:
                                           challenge.protectionSpace.serverTrust];
            [challenge.sender useCredential:credential
                 forAuthenticationChallenge:challenge];
        }
    }
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
// -------------------ByPass ssl ends
@end

<template> <view class="webview-container"> <cover-view class="webview-wrapper"> <web-view :src="webviewPath" id="targetWebview" ></web-view> </cover-view> <cover-view class="bottom-action-area"> <cover-view class="capture-btn" @click="generatePdfFromWebview"> <cover-view class="btn-text">生成PDF</cover-view> </cover-view> </cover-view> </view> </template> <script setup lang="ts"> import { onLoad} from '@dcloudio/uni-app'; import { ref } from 'vue'; import jsPDF from 'jspdf'; declare const plus: any; const webviewPath = ref(''); // const ws = ref<any>(null); // const pdfFilePath = ref(''); const showPdfPreview = ref(false); const platform = ref(''); // const htmlContent = ref(''); const pdfViewerUrl = ref(''); onLoad((options: any) => { if (options.url) { webviewPath.value = decodeURIComponent(options.url); pdfViewerUrl.value = `/static/pdfjs/web/viewer.html?file=${encodeURIComponent(webviewPath.value)}`; } // 获取当前平台 const systemInfo = uni.getSystemInfoSync(); platform.value = systemInfo.platform; }); const generatePdfFromWebview = async () => { if (uni.getSystemInfoSync().platform === 'android') { // 安卓使用Intent唤起 plus.runtime.openWeb('https://docs.google.com/viewer?url=' + encodeURI(webviewPath.value)) } else { // iOS可直接用WebView加载 uni.navigateTo({ url: `pages/home/components/Webpreview?url=${encodeURIComponent(webviewPath.value)}` }) } } </script> <style> .webview-container { position: relative; width: 100%; height: 100vh; overflow: hidden; } .webview-wrapper { height: calc(100vh - 120rpx); width: 100%; overflow: hidden; } .bottom-action-area { position: fixed; bottom: 0; left: 0; right: 0; z-index: 100; background-color: #007aff; padding: 30rpx; padding-bottom: constant(safe-area-inset-bottom); padding-bottom: env(safe-area-inset-bottom); display: flex; justify-content: center; align-items: center; } .capture-btn { width: 100%; height: 90rpx; background-color: #007aff; border-radius: 45rpx; box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2); display: flex; align-items: center; justify-content: center; } .btn-text { color: #ffffff; font-size: 32rpx; font-weight: 500; } /* PDF预览组件样式 */ .custom-preview { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 9999; background-color: rgba(0, 0, 0, 0.9); display: flex; flex-direction: column; align-items: center; padding: 0 0 40rpx 0; box-sizing: border-box; } .preview-header { width: 100%; height: 100rpx; background-color: #007aff; color: #ffffff; display: flex; align-items: center; justify-content: center; position: relative; } .title-container { display: flex; align-items: center; justify-content: center; width: 100%; } .preview-title { color: #ffffff; font-size: 34rpx; font-weight: bold; } .close-btn { position: absolute; right: 30rpx; font-size: 40rpx; color: white; } .preview-pdf { width: 100%; height: calc(100% - 100rpx - 120rpx); background-color: white; } .action-buttons { display: flex; width: 100%; justify-content: space-between; padding: 30rpx 5%; margin-top: auto; background-color: #353336; box-sizing: border-box; } .action-btn { flex: 1; height: 90rpx; border-radius: 12rpx; display: flex; align-items: center; justify-content: center; margin: 0 15rpx; color: #ffffff; font-size: 34rpx; font-weight: 500; } .cancel-btn { background-color: #666; } .confirm-btn { background-color: #007aff; } </style> 这是webview页面 <template> <view> <web-view :src="pdfViewerUrl"></web-view> </view> </template> <script> export default { data() { return { pdfViewerUrl: '' // 将在此处构建PDF查看器的URL }; }, onLoad(options) { // 从跳转链接中获取PDF地址 const pdfUrl = decodeURIComponent(options.src); // 构建PDF.js查看器的URL // 注意:这里使用的是本地static目录下的viewer.html // 假设PDF.js放在static/pdfjs/web/viewer.html this.pdfViewerUrl = `/static/pdfjs/web/viewer.html?file=${encodeURIComponent(pdfUrl)}`; } }; </script> 这是webview预览页面 怎样将在跳到预览页的时候直接跳PDF 将webview内容生成pdf格式预览
08-09
<template> <view class="webview-container"> <cover-view class="webview-wrapper"> <web-view :src="webviewPath" id="targetWebview" ></web-view> </cover-view> <cover-view class="bottom-action-area"> <cover-view class="capture-btn" @click="generatePdfFromWebview"> <cover-view class="btn-text">生成PDF</cover-view> </cover-view> </cover-view> </view> </template> <script setup lang="ts"> import { onLoad} from '@dcloudio/uni-app'; import { ref } from 'vue'; import jsPDF from 'jspdf'; declare const plus: any; const webviewPath = ref(''); // const ws = ref<any>(null); // const pdfFilePath = ref(''); const showPdfPreview = ref(false); const platform = ref(''); // const htmlContent = ref(''); const pdfViewerUrl = ref(''); onLoad((options: any) => { if (options.url) { webviewPath.value = decodeURIComponent(options.url); pdfViewerUrl.value = `/static/pdfjs/web/viewer.html?file=${encodeURIComponent(webviewPath.value)}`; } // 获取当前平台 const systemInfo = uni.getSystemInfoSync(); platform.value = systemInfo.platform; }); const generatePdfFromWebview = async () => { const pdfUrl = 'https://example.com/document.pdf'; uni.navigateTo({ url: `/pages/pdf-preview?pdfUrl=${encodeURIComponent(pdfUrl)}` }); } </script> <style> .webview-container { position: relative; width: 100%; height: 100vh; overflow: hidden; } .webview-wrapper { height: calc(100vh - 120rpx); width: 100%; overflow: hidden; } .bottom-action-area { position: fixed; bottom: 0; left: 0; right: 0; z-index: 100; background-color: #007aff; padding: 30rpx; padding-bottom: constant(safe-area-inset-bottom); padding-bottom: env(safe-area-inset-bottom); display: flex; justify-content: center; align-items: center; } .capture-btn { width: 100%; height: 90rpx; background-color: #007aff; border-radius: 45rpx; box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2); display: flex; align-items: center; justify-content: center; } .btn-text { color: #ffffff; font-size: 32rpx; font-weight: 500; } /* PDF预览组件样式 */ .custom-preview { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 9999; background-color: rgba(0, 0, 0, 0.9); display: flex; flex-direction: column; align-items: center; padding: 0 0 40rpx 0; box-sizing: border-box; } .preview-header { width: 100%; height: 100rpx; background-color: #007aff; color: #ffffff; display: flex; align-items: center; justify-content: center; position: relative; } .title-container { display: flex; align-items: center; justify-content: center; width: 100%; } .preview-title { color: #ffffff; font-size: 34rpx; font-weight: bold; } .close-btn { position: absolute; right: 30rpx; font-size: 40rpx; color: white; } .preview-pdf { width: 100%; height: calc(100% - 100rpx - 120rpx); background-color: white; } .action-buttons { display: flex; width: 100%; justify-content: space-between; padding: 30rpx 5%; margin-top: auto; background-color: #353336; box-sizing: border-box; } .action-btn { flex: 1; height: 90rpx; border-radius: 12rpx; display: flex; align-items: center; justify-content: center; margin: 0 15rpx; color: #ffffff; font-size: 34rpx; font-weight: 500; } .cancel-btn { background-color: #666; } .confirm-btn { background-color: #007aff; } </style> 这是webview页面 应该怎样修改
最新发布
08-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值