#include
std::for_each( boost::counting_iterator(0),
boost::counting_iterator(100),
do_something );
Вы можете сохранить HTML-код в каталоге документов и загрузить страницу прямо из каталога документов при запуске.
Чтобы сохранить содержимое веб-просмотра: Чтение содержимого HTML из UIWebView
Для загрузки:
NSString* path = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"html"];
NSURL* url = [NSURL fileURLWithPath:path];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
Если на странице уже есть AJAX, почему бы не сохранить JavaScript / HTML в пакете приложения для запуска, а не загружать его при первом запуске? Затем загрузите страницу с кодом, который Кори дал ниже, и позвольте AJAX обрабатывать сеть для обновленных частей страницы.
Об этом есть множество статей кеш UIWebView работает, и общее ощущение состоит в том, что даже если некоторые механизмы работают нормально под MacOS X, те же подходы могут иметь любопытное поведение под iPhone.
ОДНАКО, я делаю это, играя с глобальным кешем, к которому обращается любое NSURLConnection
, UIWebView
в том числе. А в моем случае работает;).
Что вам нужно понять, так это глобальный поток:
loadRequest
в UIWebView
NSURLCache
, чтобы спросить, «есть ли что-то закешировано для этого запроса? ": - (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
Отсюда, вот что я делаю для обработки кеша на диске со своей стороны, чтобы ускорить загрузку UIWebView:
NSURLCache
и переопределить управление получением над - (NSCachedURLResponse *) cachedResponseForRequest: (NSURLRequest *) запросом
селектором Теперь код:
@interface MyCache : NSURLCache {
}
@end
@implementation MyCache
-(NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"CACHE REQUEST S%@", request);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray* tokens = [request.URL.relativePath componentsSeparatedByString:@"/"];
if (tokens==nil) {
NSLog(@"ignoring cache for %@", request);
return nil;
}
NSString* pathWithoutRessourceName=@"";
for (int i=0; i<[tokens count]-1; i++) {
pathWithoutRessourceName = [pathWithoutRessourceName stringByAppendingString:[NSString stringWithFormat:@"%@%@", [tokens objectAtIndex:i], @"/"]];
}
NSString* absolutePath = [NSString stringWithFormat:@"%@%@", documentsDirectory, pathWithoutRessourceName];
NSString* absolutePathWithRessourceName = [NSString stringWithFormat:@"%@%@", documentsDirectory, request.URL.relativePath];
NSString* ressourceName = [absolutePathWithRessourceName stringByReplacingOccurrencesOfString:absolutePath withString:@""];
NSCachedURLResponse* cacheResponse = nil;
//we're only caching .png, .js, .cgz, .jgz
if (
[ressourceName rangeOfString:@".png"].location!=NSNotFound ||
[ressourceName rangeOfString:@".js"].location!=NSNotFound ||
[ressourceName rangeOfString:@".cgz"].location!=NSNotFound ||
[ressourceName rangeOfString:@".jgz"].location!=NSNotFound) {
NSString* storagePath = [NSString stringWithFormat:@"%@/myCache%@", documentsDirectory, request.URL.relativePath];
//this ressource is candidate for cache.
NSData* content;
NSError* error = nil;
//is it already cached ?
if ([[NSFileManager defaultManager] fileExistsAtPath:storagePath]) {
//NSLog(@"CACHE FOUND for %@", request.URL.relativePath);
content = [[NSData dataWithContentsOfFile:storagePath] retain];
NSURLResponse* response = [[NSURLResponse alloc] initWithURL:request.URL MIMEType:@"" expectedContentLength:[content length] textEncodingName:nil];
cacheResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:content];
} else {
//trick here : if no cache, populate it asynchronously and return nil
[NSThread detachNewThreadSelector:@selector(populateCacheFor:) toTarget:self withObject:request];
}
} else {
NSLog(@"ignoring cache for %@", request);
}
return cacheResponse;
}
-(void)populateCacheFor:(NSURLRequest*)request {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSLog(@"PATH S%@", paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray* tokens = [request.URL.relativePath componentsSeparatedByString:@"/"];
NSString* pathWithoutRessourceName=@"";
for (int i=0; i<[tokens count]-1; i++) {
pathWithoutRessourceName = [pathWithoutRessourceName stringByAppendingString:[NSString stringWithFormat:@"%@%@", [tokens objectAtIndex:i], @"/"]];
}
NSString* absolutePath = [NSString stringWithFormat:@"%@/myCache%@", documentsDirectory, pathWithoutRessourceName];
//NSString* absolutePathWithRessourceName = [NSString stringWithFormat:@"%@%@", documentsDirectory, request.URL.relativePath];
//NSString* ressourceName = [absolutePathWithRessourceName stringByReplacingOccurrencesOfString:absolutePath withString:@""];
NSString* storagePath = [NSString stringWithFormat:@"%@/myCache%@", documentsDirectory, request.URL.relativePath];
NSData* content;
NSError* error = nil;
NSCachedURLResponse* cacheResponse = nil;
NSLog(@"NO CACHE FOUND for %@", request.URL);
//NSLog(@"retrieving content (timeout=%f) for %@ ...", [request timeoutInterval], request.URL);
content = [NSData dataWithContentsOfURL:request.URL options:1 error:&error];
//NSLog(@"content retrieved for %@ / error:%@", request.URL, error);
if (error!=nil) {
NSLog(@"ERROR %@ info:%@", error, error.userInfo);
NSLog(@"Cache not populated for %@", request.URL);
} else {
NSURLResponse* response = [[NSURLResponse alloc] initWithURL:request.URL MIMEType:@"" expectedContentLength:[content length] textEncodingName:nil];
cacheResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:content];
//the store is invoked automatically.
[[NSFileManager defaultManager] createDirectoryAtPath:absolutePath withIntermediateDirectories:YES attributes:nil error:&error];
BOOL ok;// = [[NSFileManager defaultManager] createDirectoryAtPath:absolutePath withIntermediateDirectories:YES attributes:nil error:&error];
ok = [content writeToFile:storagePath atomically:YES];
NSLog(@"Caching %@ : %@", storagePath , ok?@"OK":@"KO");
}
[pool release];
}
@end
И его использование в вашем приложении:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* diskCachePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"myCache"];
NSError* error;
[[NSFileManager defaultManager] createDirectoryAtPath:diskCachePath withIntermediateDirectories:YES attributes:nil error:&error];
MyCache* cacheMngr = [[MyCache alloc] initWithMemoryCapacity:10000 diskCapacity:100000000 diskPath:diskCachePath];
[NSURLCache setSharedURLCache:cacheMngr];
Этот код заслуживает серьезной доработки ... но самое главное должно быть там. У меня было много проблем, чтобы заставить это работать, надеюсь, это поможет.
Недавно я нашел этот проект на гитхабе: http://github.com/rs/SDURLCache Подход полностью совпадает с моим предыдущим ответом, описанным здесь Как сохранить контент в UIWebView для более быстрой загрузки при следующем запуске? , но код выглядит более отточенным, поэтому, возможно, имеет смысл попробовать.