1

I needed to load images from the iCloud Document Storage in my WebView I have solved this problem with my own implementation of the NSURLProtocol. My problem is, that the download is very slow and the User doesn't see any Indicator in the web page that an image is getting downloaded.

I want to show a placeholder image until the download of the real image is accomplished:

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)
        }

Do you have any ideas how I can show a placeholder until the real content is available?

ChaosSpeeder
  • 3,468
  • 5
  • 30
  • 38

2 Answers2

1

I don't think EDAMResourceURLProtocol class/object should be in charge of showing the placeholder image, so you can try writing some JS code to put the placeholder somewhere on the page until the desired content takes place.

Or, convert UIImage to NSData and pass it to clients delegate twice (once right after the request, the second one in the success block, as you're doing it now).

Dmitry Kurilo
  • 404
  • 4
  • 11
0

I figured it out. The solution is, that I set a background image with a placeholder image in my 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;
    }

I use my own edam:// protocol to load a placeholder image in my NSURLProtocol class.

   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 ... 
ChaosSpeeder
  • 3,468
  • 5
  • 30
  • 38