Search code examples
iosnsdatansurlloaddatauiweb

NSData not loaded properly in UIWebView lodadata method


i want that UIWebView working offline. When i first visit the url than i have done the below code to save data in document directory in webViewDidFinishLoad method.

NSCachedURLResponse* response = [[NSURLCache sharedURLCache]                                     cachedResponseForRequest:[webview request]];
NSData * data = [response data];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *filePath = [NSString stringWithFormat:@“%@temp”, basePath];
if (response)
{
    BOOL isSaveFile = [NSKeyedArchiver archiveRootObject:data toFile:filePath];
}

When i open the webview second time i will check that file exist or not. I get the file exist i have done the below code to open file from local.

NSData * sData = (NSData *)[NSData dataWithContentsOfFile:filePath];
if (sData.length)
{
[webview loadData: sData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];
}

Above code is not working properly and i am getting the below output.

enter image description here

Please guide me. what i am doing wrong ??


Solution

  • You should set proper MIMEType, because UIWebView have no idea how to render the raw data.

    NSCachedURLResponse* response = [[NSURLCache sharedURLCache] cachedResponseForRequest:[webview request]];
    NSString *MIMEType = response.response.MIMEType;
    NSData * data = [response data];
    

    then load

    [webview loadData: sData MIMEType:MIMEType textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];