2012-11-16 59 views
1

我想從一串文本中提取圖片的網址。它可能來自不同的網站,可能是任何形式的圖像(jpg,png,gif等)。掃描字符串,找到任何匹配的圖片擴展名並從中獲取圖形是一種好方法?從字符串中提取圖片的網址

字符串可以是這樣的:

Hello, I hope you like my picture located at http://www.website.com/picture1.png. However, if you don't, I know you'll like this one http://www.website2.org/picture2.jpg.Please refer all comments to http://www.website5.com/ 

我希望能夠掃描字符串圖像文件的ONLY網址,並作出新的字符串任何的第一張圖像URL是。因此,在這個字符串,我可以創建一個新的字符串,只有http://www.website.com/picture1.png

+0

呵呵,這有點寬泛,你不覺得嗎? – 2012-11-16 21:09:45

+0

@ H2CO3請參閱編輯瞭解更多信息。 – user717452

回答

5

我領匯Objective-C - Finding a URL within a string

無需使用RegexKitLite此得到的,因爲iOS 4的蘋果提供NSDataDetector(的NSRegularExpression一個子類)。

你可以使用它只是像這樣(來源就是你的字符串):

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil]; 
NSArray* matches = [detector matchesInString:source options:0 range:NSMakeRange(0, [source length])]; 
+0

好的,所以使用這個,我會得到一個包含在字符串中的所有URL的數組,對嗎?我如何從那裏將其縮小到只包含有效圖像的1(如果存在)? – user717452

+0

之後,爲包含** URL **的數組放置一個'for循環',並使用@ dmason82代碼實現該任務。 – 2012-11-16 21:44:08

0

好了,讓你可以使用NSString的方法pathExtension擴展,這將導致一個字符串,只是擴展,所以你就會知道,如果它是JPG,GIF,PNG等

NSString* path = @"http://location.com/pictures/image.jpg"; 
NSString* extension = [path pathExtension]; 

爲圖形可以使用的UIImage imageWithData方法,並把它傳遞從NSData的dataWithContentsOfUrl方法的輸出,使用這些方法的聯合,將你你可以創建一個UIImage在UIImageView中顯示。

UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:path]]; 

希望這會有幫助。

1
Use below code after later finish with @Anup Kumar 

    for (NSTextCheckingResult *match in matches) { 
     NSRange matchRange = [match range]; 
     if ([match resultType] == NSTextCheckingTypeLink) { 
      NSURL *url = [match URL]; 
     } else if ([match resultType] == NSTextCheckingTypePhoneNumber) { 
      NSString *phoneNumber = [match phoneNumber]; 
     } 
    }