我们使用该代码下载维基百科html数据并保存。
NSString *urlString = @"http://en.wikipedia.org/wiki/Adele";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error)
{
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[[NSUserDefaults standardUserDefaults] setObject:html forKey:urlString];
NSLog(@"Downloaded.");
}
else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
}
else if (error != nil){
NSLog(@"Error happened = %@ /n %@", error, urlString);
[NSThread detachNewThreadSelector:@selector(updateTextFaild) toTarget:self withObject:nil];
}
}];
然后我们将设备或模拟器脱机并使用UIWebView打开下载html数据。但是,下载维基百科数据缺少(图像)。 我们使用代码打开数据:(" _urlString"" @" http://en.wikipedia.org/wiki/Adele"")
if ([[NSUserDefaults standardUserDefaults] objectForKey:_urlString])
{
[_webview loadHTMLString:[[NSUserDefaults standardUserDefaults] objectForKey:_urlString] baseURL:[NSURL URLWithString:_urlString]];
return;
}
太奇怪了。