目前我正在开发适用于 Android 和 iOS 的应用程序。这是一个简单的 webView,正在调用远程 URL。
这工作得很好 - 但现在我在弄清楚如何拦截图像的加载方面遇到了问题。
我正在努力实现以下目标:
* 加载远程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://stackoverflow.com"
func loadAddressURL(){
let requesturl = NSURL(string: urlpath!)
let request = NSURLRequest(URL: requesturl)
webView.loadRequest(request) }
override func viewDidLoad() {
super.viewDidLoad()
loadAddressURL() }
谁能指出我如何实现上述结果的正确方向?
提前谢谢了。
你可以使用NSURLProtocol https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLProtocol_Class/index.html,这是一个简单的例子:
-
子类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
class:
NSURLProtocol.registerClass(Interceptor)
还有一篇不错的文章NSHipster http://nshipster.com/nsurlprotocol/如果你想了解更多NSURLProtocol
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)