我有一个用Swift编写的iOS应用,我在UIWebView
中加载了一个网页。我添加了一个Javascript接口,该接口公开了Swift中的某些功能,这些功能在网页上通过Javascript桥调用。我希望公开一个新功能,该功能允许我打开UIImagePickerController
,允许用户从图库中选择图像。当我从选择器收到回调中的图像后,我希望将图像传输到网页。因此,我尝试获取图像的文件路径(使用从选择器委托方法获得的图像信息中使用键UIImagePickerControllerImageURL
),并将其传递给Javascript上下文,该上下文在html中更新了一个img标记,指向该图像src到文件路径。文件路径读为
file:///private/var/mobile/Containers/Data/Application/D28F50B5-4BC2-4D6C-9107-2831384542FE/tmp/290042B5-9302-417E-840C-1B410F3B824B.jpeg
但是图像资产无法在Web视图中呈现。我实现的另一种解决方案是将UIImage
数据转换为易于传递的base64字符串,但是这种方法在这里处理大图像是一个问题。是否可以获取可以由webview加载的所选图像资产的文件路径?还有其他替代方法吗?
import UIKit
导入照片
ViewController类:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
private var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
webView = UIWebView()
self.view.addSubview(webView)
}
public func openGalleryAndPickImage(){
presentImagePicker(presentingViewController: self, pickerSourceType: .photoLibrary)
}
public func takeImageWithCamera(){
presentImagePicker(presentingViewController: self, pickerSourceType: .camera)
}
private func presentImagePicker(presentingViewController: UIViewController, pickerSourceType: UIImagePickerController.SourceType){
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = pickerSourceType
picker.allowsEditing = false
presentingViewController.present(picker, animated: true, completion: nil)
}
public func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
picker.dismiss(animated: true, completion: nil)
convertImageToBase64AndCallJS(image: info[UIImagePickerControllerOriginalImage] as! UIImage)
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
picker.dismiss(animated: true, completion: nil)
}
private func convertImageToBase64AndCallJS(image: UIImage) {
let base64String = base64EncodedStringWith(image: image)
callJSFunctionFromSwift(img: base64String)
}
private func base64EncodedStringWith(image: UIImage)->String{
let imageData = UIImagePNGRepresentation(image)
return imageData?.base64EncodedString() ?? ""
}
private func callJSFunctionFromSwift(img: String) {
webView?.stringByEvaluatingJavaScript(from: "processImage('\(img)')")
}
}