Google Directions API 返回包含 HTML 標籤(<b>, <div>, <p>, 實體 )的導航指引字串,需在原生 UI 中顯示為富文本。
NSString *htmlString = @"Head southwest toward GH Rd...";
NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:data
options:options
documentAttributes:nil
error:nil];
// 設置到 UILabel / UITextView
textView.attributedText = attributedString;
// 或 UILabel (需 numberOfLines = 0)
label.attributedText = attributedString;
label.numberOfLines = 0;
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
NSString *html = [NSString stringWithFormat:@"%@", htmlString];
[webView loadHTMLString:html baseURL:nil];
[self.view addSubview:webView];
NSString *plainText = [htmlString stringByReplacingOccurrencesOfString:@"<[^>]+>"
withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, htmlString.length)];
// 再處理實體
plainText = [plainText stringByReplacingOccurrencesOfString:@" " withString:@" "];
plainText = [plainText stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
// ...
| 需求 | 推薦方案 |
|---|---|
| 輕量富文本(粗體、顏色、段落),性能敏感 | NSAttributedString + UILabel/TextView |
| 複雜排版(表格、浮動、CSS 動畫)、需交互 | WKWebView |
| 僅需純文本、無格式要求 | 正則移除標籤 + 實體解碼 |
NSAttributedString 解析 HTML 在**主線程**且**較慢**,大量文本建議後台線程預解析緩存:
DispatchQueue.global(qos: .userInitiated).async {
let attributed = try? NSAttributedString(data: data, options: options, documentAttributes: nil)
DispatchQueue.main.async { self.textView.attributedText = attributed }
}
AttributedString (Swift) 支援 Markdown 解析,若後端可改輸出 Markdown 更高效。原生 App 顯示 HTML 導航文本,**NSAttributedString 是首選**(輕量、原生、支援基本富文本)。複雜排版用 WKWebView。純文本需求用正則清洗。避免在主線程大量解析 HTML 導致卡頓。