简体   繁体   English

从包含HTML的NSString中创建本地NSURL?

[英]Make a local NSURL from an NSString containing HTML?

I have an NSString containing some HTML. 我有一个包含一些HTML的NSString I'm trying to pre-load that HTML, including any external image links inside it. 我正在尝试预加载该HTML,包括其中的所有外部图像链接。 So, to clarify: I have just HTML, and I need to basically load it, grab its images, and cache that data. 因此,请澄清一下:我只有HTML,并且需要基本加载它,获取其图像并缓存该数据。

I can do this with a live website using the following code: 我可以使用以下代码通过实时网站来做到这一点:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], @"index.html"];
NSURL *url = [NSURL URLWithString:@"http://www.google.co.uk"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];

But this won't work without an NSURL . 但是,如果没有NSURL这将无法工作。 I'm wondering if I can make an NSURL somehow from this string of HTML, and substitute it in the URLWithString: method here. 我想知道是否可以通过此HTML字符串制作NSURL ,并将其替换为URLWithString:方法。

So, question: can I take some local HTML inside an NSString and turn that into an NSURL , so that I can feed it into the code above, and save the both the HTML and any images it links to? 所以,问题是:我可以在NSString内放入一些本地HTML并将其转换为NSURL ,以便可以将其输入到上面的代码中,并保存HTML和它链接到的任何图像吗?

The question you are asking makes absolutely no sense. 您所提出的问题完全没有道理。

A URL is a pointer to the location of a resource online. URL是指向在线资源位置的指针。 In this context a html file. 在这种情况下,一个html文件。 You can not make one into the other. 您不能将一个变成另一个。

I suggest you create a UIWebView , load the string into that, have it render and cache the result. 我建议您创建一个UIWebView ,将字符串加载到其中,使其呈现并缓存结果。

[webView loadHTMLString:@"data" baseURL:nil];

I believe it will need to be actually place on the screen for it to render, so make it an invisible 1 X 1 pixel square and it should be fine. 我认为它实际上需要放置在屏幕上才能呈现,因此使其成为不可见的1 X 1像素正方形,应该没问题。 Then when the didFinishLoading fires. 然后在didFinishLoading触发时。 Cache the result 缓存结果

Yes, you can. 是的你可以。 You would have to parse the links out of HTML yourself. 您必须自己解析HTML中的链接。 Real world HTML is not XML compliant, so a quick and dirty way to achieve your goals would be to treat HTML as text and parse links out using a regular expression library. 现实世界中的HTML不符合XML,因此实现目标的一种快速而肮脏的方法是将HTML视为文本并使用正则表达式库解析出链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM