2013-01-31 64 views
0

我有包含链接的文本(这些是图像链接) 我需要解析文本以便构建它,并且当链接被环绕时,图像被抓取。阅读文本,解析链接

因此,例如:

“我曾经有过一个狐狸http://mysite.com/images/fox.jpg 我也拥有了一只小狗http://mysite.com/images/dog.jpg

因此,它对子级是这样的:

我曾经有一个狐狸

---------------------------------- 
|        | 
|Fox Image From     | 
|http://mysite.com/images/fox.jpg| 
|        | 
|        | 
---------------------------------- 

我也拥有了一只小狗和一只公鸡

---------------------------------- 
|        | 
|dog Image From     | 
|http://mysite.com/images/dog.jpg| 
|        | 
|        | 
---------------------------------- 
-------------------------------------- 
|         | 
|rooster Image From     | 
|http://mysite.com/images/rooster.jpg| 
|         | 
|         | 
-------------------------------------- 

我能使用来实现这一目标?

我已经设置了视图,但现在它只显示我的文本。 如何将图像添加到该视图? 我如何解析它们? 什么是最好的方法?

回答

1

您可以使用UIWebView显示您的文本,并在找到有效图像链接的任何地方将其包装在<img>标记中。

要解析这些链接,您可以使用RegEx。您可能需要根据自己的确切规格调整正则表达式,但粗糙的jist应该是http(?:s)?://.+\.(?:jpg|jpeg|png|gif|bmp)。那会选择一个以http或https开头的web链接,并以.jpg,.png等结尾。(的方式未经)

在代码中,你可以把它作为

NSString *regExpString = @"http(?:s)?://.+\\.(?:jpg|jpeg|png|gif|bmp)"; 
NSString *storyStr = @"...";  

NSRegularExpression *storyRegex = [[NSRegularExpression alloc] initWithPattern:regExpString 
                     options:NSRegularExpressionCaseInsensitive 
                     error:nil]; 

NSString* webViewStr = [storyRegex stringByReplacingMatchesInString:storyStr options:0 range:NSMakeRange(0, storyStr.length) withTemplate:@"<br\><img src=\"$0\"></img><br\>"]; 

然后,内UIWebView

UIWebView* webView = ...; 
[webView loadHTMLString:webViewStr baseURL:nil]; 
0

无论何时检测到图像链接(通过最可能使用stringByReplacingOccurencesOfString: withString:),您都可以通过将图像链接包装在img src=标记中,首先将其转换为HTML。

所以你转换所有链接来自:

http://mysite.com/images/rooster.jpg 

<img src="http://mysite.com/images/rooster.jpg"> 

一旦你的HTML,您可以将其加载到UIWebView

希望这会有所帮助。

0
使用 webViewStr

我们可以写HTML代码,并显示在TextView中

NSString *regExpString = @"http(?:s)?://.+\\.(?:jpg|jpeg|png|gif|bmp)"; 
NSString *yourStr = @"Test Article with Image and LinksTest Article with Image and Links http://image.gif"; 
NSRegularExpression *storyRegex = [[NSRegularExpression alloc] initWithPattern:regExpString options:NSRegularExpressionCaseInsensitive error:nil]; 

NSString* tempStr = [storyRegex stringByReplacingMatchesInString:yourStr options:0 range:NSMakeRange(0, storyStr.length) withTemplate:@"<br\><img src=\"$0\"></img><br\>"]; 
NSString *htmlStr = [NSString stringWithFormat:@"<html> %@ </html>",tempStr]; 
[self.txtView setValue:htmlStr forKey:@"contentToHTMLString"];