目前我正在开发适用于 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
来做到这一点,这是一个简单的例子:
子类
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() { } }
在代码的某处,注册
Interceptor
类:NSURLProtocol.registerClass(Interceptor)
关于 NSHipster
也有一篇不错的文章如果你想阅读更多关于 NSURLProtocol
的内容。
关于ios - SWIFT:如何加载本地镜像远程 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28024296/