2013-01-31 68 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"];