1

我需要在我的 WebView 中从 iCloud 文档存储中加载图像我已经通过我自己的 NSURLProtocol 实现解决了这个问题。我的问题是,下载速度非常慢,用户在网页中看不到任何指示正在下载图像的指示符。

我想显示一个占位符图像,直到完成真实图像的下载:

public class EDAMResourceURLProtocol : NSURLProtocol
{

    public override func startLoading() {

       let url = self.request.URL!
       let hash = url.host!

       // I want to show this image before the real content gets downloaded
       let image = UIImage(named: "DownloadPlaceholder")

       // this function is very slow ....
       historyStorage.fetchResourceWithBody(hash, success: {
        edamResource in

        let response = NSURLResponse(URL: self.request.URL!, MIMEType: edamResource!.mime, expectedContentLength: edamResource!.data!.body!.length, textEncodingName: nil)
        self.client!.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: NSURLCacheStoragePolicy.NotAllowed)
        self.client!.URLProtocol(self, didLoadData: edamResource!.data!.body)
        self.client!.URLProtocolDidFinishLoading(self)
        }

在真实内容可用之前,您有什么想法可以显示占位符吗?

4

2 回答 2

1

我认为EDAMResourceURLProtocol类/对象不应该负责显示占位符图像,因此您可以尝试编写一些 JS 代码将占位符放在页面上的某个位置,直到出现所需的内容。

或者,将 UIImage 转换为 NSData 并将其传递给客户端委托两次(一次在请求之后,第二次在成功块中,就像您现在所做的那样)。

于 2015-12-27T11:19:13.710 回答
0

我想到了。解决方案是,我在 style.css 中设置了一个带有占位符图像的背景图像:

  img {
       max-width: 100%;
       min-width: 64px;
       min-height: 64px;
       height: auto;
       margin: 32px auto;
       display:block;
       background: url('edam://placeholder') no-repeat;
    }

我使用自己的 edam:// 协议在我的 NSURLProtocol 类中加载占位符图像。

   public class EDAMResourceURLProtocol : NSURLProtocol
   {
       public override func startLoading()
       { 
           let url = self.request.URL!
           let hash = url.host!

            if hash == "placeholder" {
               let bundle = NSBundle(forClass: object_getClass(self))
               let path = bundle.pathForResource("Fading lines", ofType: "gif")!
               let data = NSData(contentsOfFile: path)
               sendResponse("image/gif", data: data!)
               return
           }

           // here starts the slow download
           historyStorage.fetchResourceWithBody(hash, success: {
            edamResource in

           sendResponse ... 
于 2015-12-28T08:23:57.730 回答