SWIFT: 如何远程加载本地图片HTML

SWIFT: How to load local images remote HTML

目前我正在为 Android 和 iOS 开发应用程序。这是一个调用远程 URL.

的简单 webView

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

在 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://whosebug.com"
func loadAddressURL(){
   let requesturl = NSURL(string: urlpath!)
   let request = NSURLRequest(URL: requesturl)
   webView.loadRequest(request) }

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

任何人都可以指出如何实现上述结果的正确方向吗?

非常感谢。

您可以使用 NSURLProtocol 执行此操作,这是一个简单的示例:

  1. 子class 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 class:

    NSURLProtocol.registerClass(Interceptor)
    

如果您想阅读有关 NSURLProtocol 的更多信息,还有一篇关于 NSHipster 的好文章。