ios - SWIFT:如何加载本地镜像远程 HTML

标签 ios swift

目前我正在开发适用于 Android 和 iOS 的应用程序。这是一个调用远程 URL 的简单 webView。

这工作得很好 - 但现在我在弄清楚如何拦截图像加载时遇到了问题。 我正在努力实现以下目标: * 加载远程地址 *拦截加载并检查图像 * 如果图片存在于应用程序中(在某个文件夹中)加载本 map 片,否则从服务器加载远程图片

在 Android 上这很简单:

public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        try {
            if( url.endsWith("png") ) {
                return new WebResourceResponse("image/png", "ISO-8859-1", ctx.getAssets().open(url.substring(basepath.length())));
            }
            if( url.endsWith("jpg") ) {
                return new WebResourceResponse("image/jpg", "ISO-8859-1", ctx.getAssets().open(url.substring(basepath.length())));
            }
        } catch (IOException e) {
        }

        return super.shouldInterceptRequest(view, url);
    }

在 iOS - 尤其是 SWIFT 上,我还没有找到解决方案。到目前为止,这就是我的 webView:

@IBOutlet var webView: UIWebView!
var urlpath = "http://stackoverflow.com"
func loadAddressURL(){
   let requesturl = NSURL(string: urlpath!)
   let request = NSURLRequest(URL: requesturl)
   webView.loadRequest(request) }

override func viewDidLoad() {
   super.viewDidLoad()
   loadAddressURL() }

谁能指出我如何实现上述结果的正确方向?

非常感谢。

最佳答案

您可以使用 NSURLProtocol 来做到这一点,这是一个简单的例子:

  1. 子类 NSURLProtocol

    class Interceptor: NSURLProtocol {
        override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
            return request
        }
    
        override class func canInitWithRequest(request: NSURLRequest) -> Bool {
            // returns true for the requests we want to intercept (*.png)
            return request.URL.pathExtension == "png"
        }
    
        override func startLoading() {
            // a request for a png file starts loading
            // custom response
            let response = NSURLResponse(URL: request.URL, MIMEType: "image/png", expectedContentLength: -1, textEncodingName: nil)
    
            if let client = self.client {
                client.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
    
                // reply with data from a local file
                client.URLProtocol(self, didLoadData: NSData(contentsOfFile: "local file path")!)
    
                client.URLProtocolDidFinishLoading(self)
            }
        }
    
        override func stopLoading() {
        }
    }
    
  2. 在代码的某处,注册 Interceptor 类:

    NSURLProtocol.registerClass(Interceptor)
    

关于 NSHipster 也有一篇不错的文章如果你想阅读更多关于 NSURLProtocol 的内容。

关于ios - SWIFT:如何加载本地镜像远程 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28024296/

相关文章:

objective-c - UILocalNotification有时不通知我

swift - "Cannot call value of non-function type ' HTTPURL 响应? '"(Alamofire 4.0) [Swift 3.0]

ios - 没有结果时隐藏海关部分?

ios - 事件工具包权限

swift - swift中的简单下拉框

iOS文本框光标位置错误

iphone - 我什么时候需要同时拥有 iVar 和属性(property)?

ios - SKTexture 返回错误的大小?

ios - iOS中如何检测文件是否被修改?

ios - Swift SVG 填充颜色到 SVG 图像