How to download a web page with it's inner resoures like images,css in iOS?

谁都会走 提交于 2019-12-04 20:27:54

I ran in the same problem once, and I solved it using ASIWebPageRequest . It was old by the time, but still works.

I wrote a method (based on sample method) for download a webpage in a folder. You need to modify this to get it work.

- (IBAction)loadURL:(NSURL *)url inFolder:(NSString*)folderPath
{
    // Assume request is a property of our controller
    // First, we'll cancel any in-progress page load
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [[self request] setDelegate:nil];
    [[self request] cancel];

    [self setRequest:[ASIWebPageRequest requestWithURL:url]];
    [[self request] setDelegate:self];
    [[self request] setDidFailSelector:@selector(webPageFetchFailed:)];
    [[self request] setDidFinishSelector:@selector(webPageFetchSucceeded:)];

    // Tell the request to embed external resources directly in the page
    [[self request] setUrlReplacementMode:ASIReplaceExternalResourcesWithData];

    self.theCache.storagePath = folderPath;


    // It is strongly recommended you use a download cache with ASIWebPageRequest
    // When using a cache, external resources are automatically stored in the cache
    // and can be pulled from the cache on subsequent page loads
    self.request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy;
   [[self request] setDownloadCache:self.theCache];

   // Ask the download cache for a place to store the cached data
   // This is the most efficient way for an ASIWebPageRequest to store a web page
   //[[self request] setDownloadDestinationPath:
   //[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:[self request]]];
   [[self request] setDownloadDestinationPath:[self.theCache pathToStoreCachedResponseDataForRequest:[self request]]];

   [[self request] startAsynchronous];

}

I used ASIDownloadCache too.

...
    ASIDownloadCache *localCache = [[ASIDownloadCache alloc] init];
    self.theCache = localCache;
...

You could implement a custum NSUrlCache and save everything. Everything that is downloaded using a NSUrlRequest will use the NSUrlCache. Everything a UIWebView does uses the NSUrlRequest. If you need a sample, then have a look at https://github.com/evermeer/EVURLCache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!