WKWebView:将UIImage插入网页 [英] WKWebView: insert UIImage into web page

查看:72
本文介绍了WKWebView:将UIImage插入网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS中,给定加载在 WKWebView 内的网页,如何在HTML内显示自己的 UIImage ?

In iOS, given a web page loaded inside a WKWebView, how can I show my own UIImage inside the HTML?

谢谢

推荐答案

一种方法是使用Base64编码.下面的示例应该是一个完整的示例,假设您连接了 UIWebView 并具有正确名称的图像:

One way to do it is using Base64 encoding. The following should be a completely working example, assuming you wire up a UIWebView and have an image of the correct name:

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if let image = UIImage(named: "Castle"),
            let data = UIImagePNGRepresentation(image) {
            let base64 = data.base64EncodedString(options: [])
            let url = "data:application/png;base64," + base64
            let html = "<html><head></head><body><h1>Hello World!</h1><img src='\(url)'></body></html>"
            webView.loadHTMLString(html, baseURL: URL(fileURLWithPath: ""))
        }

    }

}

我尝试在Playground中执行此操作,但是无法显示webView,因此这是一个最小的应用程序...

I tried to do this in Playground, but couldn't get the webView to display, so it's a minimal app...

输出:

这篇关于WKWebView:将UIImage插入网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆