首页 > 解决方案 > 为什么这个 Instagram oEmbed html 不适合 Swift WKWebView?

问题描述

我无法让整个 Instagram 嵌入 html 在这个 WKWebView 中呈现。以下 url 用于查询 api:

/instagram_oembed?url=https://www.instagram.com/p/B4x4RtagRoH/?igshid=rmiahm71silp&maxwidth=658

maxWidth 在 Instagram 文档中进行了描述:Instagram oEmbed Docs

注意:我使用的 WKWebView 的框架宽度为 394(转换为像素为 1182;这就是我使用 API 的最大可能宽度值为 658 的原因)。此外,WKWebView 被添加到容器 UIView 并被限制在其边缘。

该调用返回一个带有 html 键的 json 对象,该键由帖子组成。它以 a 开头,<blockquote>并且无法正确呈现,因此我将其包装在 a<HTML><HEAD>标签中,如下所示:

func embed(html: String, baseURL: URL? = nil) {
    let htmlStart = "<HTML><HEAD><meta name=\"viewport\" content=\"width=658, shrink-to-fit=yes\"></HEAD><BODY>"
    let htmlEnd = "</BODY></HTML>"
    let htmlString = "\(htmlStart)\(html)\(htmlEnd)"

    let script = """
                            var script = document.createElement('script');
                            script.src = 'https://platform.instagram.com/en_US/embeds.js';
                            document.head.appendChild(script);
                         """
            
    let userScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
            
    configuration.userContentController.addUserScript(userScript)
            
    debugPrint("htmlString: \(htmlString)")
    loadHTMLString(htmlString, baseURL: baseURL)
    
}

这是它当前的渲染方式:

在此处输入图像描述

为什么 html 的内容没有正确调整高度?

我该怎么做才能尝试将整个 html 放入 WKWebView 中?

标签: htmlswiftinstagramwkwebviewoembed

解决方案


推荐阅读