Detect Hash Tags #, Mention Tags @, in iOS Like in Twitter App

Detect hash tags #, mention tags @, in iOS like in Twitter App

-(NSMutableAttributedString*)decorateTags:(NSString *)stringWithTags{

NSError *error = nil;

//For "Vijay #Apple Dev"
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];

//For "Vijay @Apple Dev"
//NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"@(\\w+)" options:0 error:&error];

NSArray *matches = [regex matchesInString:stringWithTags options:0 range:NSMakeRange(0, stringWithTags.length)];
NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:stringWithTags];

NSInteger stringLength=[stringWithTags length];

for (NSTextCheckingResult *match in matches) {

NSRange wordRange = [match rangeAtIndex:1];

NSString* word = [stringWithTags substringWithRange:wordRange];

//Set Font
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, stringLength)];

//Set Background Color
UIColor *backgroundColor=[UIColor orangeColor];
[attString addAttribute:NSBackgroundColorAttributeName value:backgroundColor range:wordRange];

//Set Foreground Color
UIColor *foregroundColor=[UIColor blueColor];
[attString addAttribute:NSForegroundColorAttributeName value:foregroundColor range:wordRange];

NSLog(@"Found tag %@", word);

}

// Set up your text field or label to show up the result

// yourTextField.attributedText = attString;
//
// yourLabel.attributedText = attString;

return attString;
}

Sample Image

How to make UITextView detect hashtags?

This should work for you

  1. Create a new swift file with any name(UITextViewHashtagExtension.swift)
  2. Insert this code below:

    import UIKit

    extension UITextView {

    func resolveHashTags(){

    // turn string in to NSString
    let nsText:NSString = self.text

    // this needs to be an array of NSString. String does not work.
    let words:[NSString] = nsText.componentsSeparatedByString(" ")

    // you can't set the font size in the storyboard anymore, since it gets overridden here.
    let attrs = [
    NSFontAttributeName : UIFont.systemFontOfSize(17.0)
    ]

    // you can staple URLs onto attributed strings
    let attrString = NSMutableAttributedString(string: nsText as String, attributes:attrs)

    // tag each word if it has a hashtag
    for word in words {

    // found a word that is prepended by a hashtag!
    // homework for you: implement @mentions here too.
    if word.hasPrefix("#") {

    // a range is the character position, followed by how many characters are in the word.
    // we need this because we staple the "href" to this range.
    let matchRange:NSRange = nsText.rangeOfString(word as String)

    // convert the word from NSString to String
    // this allows us to call "dropFirst" to remove the hashtag
    var stringifiedWord:String = word as String

    // drop the hashtag
    stringifiedWord = String(stringifiedWord.characters.dropFirst())

    // check to see if the hashtag has numbers.
    // ribl is "#1" shouldn't be considered a hashtag.
    let digits = NSCharacterSet.decimalDigitCharacterSet()

    if let numbersExist = stringifiedWord.rangeOfCharacterFromSet(digits) {
    // hashtag contains a number, like "#1"
    // so don't make it clickable
    } else {
    // set a link for when the user clicks on this word.
    // it's not enough to use the word "hash", but you need the url scheme syntax "hash://"
    // note: since it's a URL now, the color is set to the project's tint color
    attrString.addAttribute(NSLinkAttributeName, value: "hash:\(stringifiedWord)", range: matchRange)
    }

    }
    }

    // we're used to textView.text
    // but here we use textView.attributedText
    // again, this will also wipe out any fonts and colors from the storyboard,
    // so remember to re-add them in the attrs dictionary above
    self.attributedText = attrString
    }

    }

To use this you can do something like this:

self.textView.text = "This is an #example test"
self.textView.resolveHashTags()

Updated for Swift 4.0:

extension UITextView {

func resolveHashTags() {

// turn string in to NSString
let nsText = NSString(string: self.text)

// this needs to be an array of NSString. String does not work.
let words = nsText.components(separatedBy: CharacterSet(charactersIn: "#ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_").inverted)

// you can staple URLs onto attributed strings
let attrString = NSMutableAttributedString()
attrString.setAttributedString(self.attributedText)

// tag each word if it has a hashtag
for word in words {
if word.count < 3 {
continue
}

// found a word that is prepended by a hashtag!
// homework for you: implement @mentions here too.
if word.hasPrefix("#") {

// a range is the character position, followed by how many characters are in the word.
// we need this because we staple the "href" to this range.
let matchRange:NSRange = nsText.range(of: word as String)

// drop the hashtag
let stringifiedWord = word.dropFirst()
if let firstChar = stringifiedWord.unicodeScalars.first, NSCharacterSet.decimalDigits.contains(firstChar) {
// hashtag contains a number, like "#1"
// so don't make it clickable
} else {
// set a link for when the user clicks on this word.
// it's not enough to use the word "hash", but you need the url scheme syntax "hash://"
// note: since it's a URL now, the color is set to the project's tint color
attrString.addAttribute(NSAttributedStringKey.link, value: "hash:\(stringifiedWord)", range: matchRange)
}

}
}

// we're used to textView.text
// but here we use textView.attributedText
// again, this will also wipe out any fonts and colors from the storyboard,
// so remember to re-add them in the attrs dictionary above
self.attributedText = attrString
}
}

Check if string contains a hashtag and then change hashtag color

NSString *tweet = @"This is a tweet #MYTWEET";

NSArray *words = [tweet componentsSeparatedByString:@" "];

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:tweet];

for (NSString *word in words) {

if ([word hasPrefix:@"#"]) {

// Colour your 'word' here
NSRange matchRange = [tweet rangeOfString:word];

[attrString addAttribute:kCTForegroundColorAttributeName
value:[UIColor redColor]
range:matchRange];
// Remember to import CoreText framework (the constant is defined there)

}
}

//Display your attributed string ...

Note: If you're wondering how to display the string, here is one nice open source project : https://github.com/AliSoftware/OHAttributedLabel

How do you detect words that start with “@” or “#” within an NSString?

You can use NSRegularExpression class with a pattern like #\w+ (\w stands for word characters).

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
for (NSTextCheckingResult *match in matches) {
NSRange wordRange = [match rangeAtIndex:1];
NSString* word = [string substringWithRange:wordRange];
NSLog(@"Found tag %@", word);
}

How to only view tweets that have a specific hashtag

Is there a way to run a query for hashtags in STTwitter?

Yes! Use the following method on STTwitterAPI:

[_twitter postStatusesFilterKeyword:@"#Apple"
tweetBlock:^(NSDictionary *tweet) {
//
} errorBlock:^(NSError *error) {
//
}];

Also, the OS X demo project provides a GUI to test that:

Sample Image



Related Topics



Leave a reply



Submit