Skip to content

WKWebView 加载 TXT 文件编码问题

轩辕十四
Published date:

今天在做在线预览功能的时候碰到了一个蛋疼的问题,office 格式都可以完美的适配,但是 txt 格式出现了乱码。没办法只能进行一个转码,然后再输出内容。

Table of contents

Open Table of contents

提取 TXT 文件内容并转码 utf8


do {
	var encoding: String.Encoding = .utf8
	let body = try String(contentsOf: url, usedEncoding: &encoding)
	return body
} catch {}

这里我们的 body 就是我们获取的内容,默认的我们用了 utf8 编码格式,如果转码错误,说明文件的编码格式为其他格式。

对应中文编码


由于在 Swift 中,我并没有找到有关 GBKGBK18030 等的转码写法,所以,这里我们使用 NSString 来进行中文简体和繁体的转码。

if let body = try? NSString(contentsOf: url, encoding: SimplifiedChinese.GBK) {
	/// GBK & GB2312
	return body as String
} else if let body = try? NSString(contentsOf: url, encoding: SimplifiedChinese.GBK18030) {
	/// GBK18030
	return body as String
} else if let body = try? NSString(contentsOf: url, encoding: TraditionalChinese.Big5) {
	/// Big5
	return body as String
} else if let body = try? NSString(contentsOf: url, encoding: TraditionalChinese.Big5HKSCS) {
	/// Big5 HKSCS
	return body as String
} else {
	return nil
}

相应编码的 encoding 如下:

/// 中文简体
struct SimplifiedChinese {
    static let GBK: UInt = 0x80000632
    static let GBK18030: UInt = 0x80000631
}

/// 中文繁体
struct TraditionalChinese {
    static let Big5: UInt = 0x80000A03
    static let Big5HKSCS: UInt = 0x80000A06
}

显示 HTML


在显示内容的时候我发现字体格外的小,所以这个需要进行一个对应。

"<html><header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=no'></header><body>\(body)</body></html>"

重要的是 viewport meta 标签,这里可以进行一个缩放。

device-width:设备宽度 initial-scale:初始缩放 maximum-scale:最大缩放 minimum-scale:最小缩放 user-scalable:是否允许使用者缩放

OK,显示完美。

Previous
一键安装最新内核并开启 BBR 脚本
Next
observeOn vs. subscribeOn【译】