UIWebView显示乱码问题

今天有人问Swift中UIWebView加载页面出来的是乱码,问知道怎么解决么?

OC我知道肯定不会有乱码问题,Swift就不知道了,因为没有试过.....于是...我自己动手试试啦...

OC和Swift我都写了一遍,代码如下:

loadRequest确实会是乱码显示,使用loadHTMLString就不会.....因为你的html没有对文字进行编码格式转化 要转化成utf-8才可以.若webView是通过loadHTMLString加载的网页,是将网页预加载下来转换为string.

OC代码如下:

#import "ViewController.h"

#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kScreenHeight  [UIScreen mainScreen].bounds.size.height

@interface ViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.webView];
}

- (UIWebView *)webView {
    
    if (!_webView) {
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _webView.delegate  =self;
//        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://139.199.12.84:5858/sxweb/attached/projectStep/1.html"]]];
        NSURL *url = [NSURL URLWithString:@"http://139.199.12.84:5858/sxweb/attached/projectStep/1.html"];
        NSString * strUrl = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        
        [_webView loadHTMLString:strUrl baseURL:url];
    }
    return _webView;
}

Swift代码如下:

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

    var webView: UIWebView?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        webView = UIWebView(frame: CGRect(x: 0, y: 0,  view.frame.size.width, height: view.frame.size.height))
        webView?.delegate  = self
        let url = URL(string: "http://139.199.12.84:5858/sxweb/attached/projectStep/1.html")
//        let request = URLRequest(url: url!)
//        webView?.loadRequest(request)
        let urlString = try? String(contentsOf: url!, encoding: String.Encoding.utf8)
        webView?.loadHTMLString(urlString!, baseURL: url!)
        view.addSubview(webView!)
    }
}

显示没有乱码界面:

原文地址:https://www.cnblogs.com/pengsi/p/6149896.html