Search code examples
cordovahybrid-mobile-app

UIWebView on iOS 10 beta: not loading any svg images


We are developing a cordova ios application and we recently installed xcode 8-beta to see how our app would run under ios 10. So far we've noticed only one issue: svg images are not loading. These images are set as background using css for various elements, and they all work fine under 9.3.2 and below.


Solution

  • If your cordova app uses a plugin that implements URLProtocol, such as the phonegap contentsync plugin, you could be seeing a bug with the SVG's response header's MIME Type.

    Prior to iOS 10, the MIME Type was being set automatically, possibly as a feature of the API (yet to confirm), but that no longer seems to be the case. You can work around the problem by explicitly setting the MIME Type (Content-Type) of the response during [URLProtocol startloading]:

    (Adapted from phonegap contentsync and this MIME Check)

    - (void)startLoading {
        NSData *data = [NSData dataWithContentsOfFile:self.request.URL.path];
    
        NSString *fileExtension = self.request.URL.pathExtension;
        NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL);
        NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
    
        // add the MIME Type to the existing header.
        NSMutableDictionary *headers = [NSMutableDictionary dictionaryWithDictionary:self.request.allHTTPHeaderFields];
        headers[@"Content-Type"] = contentType;
    
        // create a response using the request and our new HEADERs
        NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL
                                                                  statusCode:200
                                                                 HTTPVersion:@"1.1"
                                                                headerFields:headers];
    
        [self.client URLProtocol:self didReceiveResponse:response
              cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly];
        [self.client URLProtocol:self didLoadData:data];
        [self.client URLProtocolDidFinishLoading:self];
    }