保存Webview数据脱机模式

时间:2015-12-05 22:58:35

标签: ios objective-c caching uiwebview

当有连接时我直接从url加载数据,如果没有Internet我从缓存中获取数据(离线模式)我写了这段代码

 NSURL *url = [NSURL URLWithString:_url];
NSURLRequest * reqyest = [NSURLRequest requestWithURL:url];
if ([[NSUserDefaults standardUserDefaults]objectForKey:@"data"]) {
    NSData * yourData  = [[NSUserDefaults standardUserDefaults]objectForKey:@"data"];

    NSString *html = [[NSString alloc] initWithData:yourData encoding:NSUTF8StringEncoding];
    [_webview loadHTMLString:html baseURL:nil];
    NSLog(@"iam here");
}
 else
 { [_webview loadRequest:reqyest];
   NSCachedURLResponse* response = [[NSURLCache sharedURLCache]
                                    cachedResponseForRequest:reqyest];
   NSData* data = [response data];NSLog(@"%@",data);


   [[NSUserDefaults standardUserDefaults]setObject:data forKey:@"data"];
   [[NSUserDefaults standardUserDefaults]synchronize];
   NSLog(@"herer erege");

}

0 个答案:

没有答案