Marcare URLs, hashtag și mention în IOS

Am de identificat într-un tweet URLs, hashtag-uri și mention tag-uri. Dacă # și @ le identific prin regular expression, pentru URLs folosesc o clasă foarte tare din IOS numită NSDataDetector, instanța uitându-se doar după ce-i specific eu: URLs.


NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:stringWithTags];
//identifica URLs in tweet.
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
NSArray *matchesOfURLS = [detector matchesInString:stringWithTags
options:0
range:NSMakeRange(0, [stringWithTags length])];
for (NSTextCheckingResult *match in matchesOfURLS) {
NSRange wordRange = [match range];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:wordRange];
}

//identifica # si @ in tweet.
NSArray *matches = [self.regex matchesInString:stringWithTags options:0 range:NSMakeRange(0, stringWithTags.length)];
for (NSTextCheckingResult *match in matches) {
// wordRange -> length= lungime cuvant si location=poz in string
NSRange wordRange = [match rangeAtIndex:1];
NSString* word = [stringWithTags substringWithRange:wordRange];

if ([self sirul:word contineCaracter:’@’]){
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:wordRange];
}
else
{
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:wordRange];

}

}

Share Button

Stefan

Leave a Reply

Your email address will not be published. Required fields are marked *