LoginSignup
6
5

More than 5 years have passed since last update.

Swiftでリンク検出(標準APIで検出する場合とカスタムクラスの2パターン)

Posted at

Swiftでリンク検出(標準APIで検出する場合とカスタムクラスの2パターン)

実現方法

①正規表現書かなくていい場合
NSDataDetectorでリンク検出

let msg:NSString = "http://hoge.com"
let dataDetector =  NSDataDetector(types:NSTextCheckingType.Link.rawValue, error: nil)

let resultArray:NSArray = dataDetector?.matchesInString(msg as String!, options: nil, range: NSMakeRange(0, msg.length)) as NSArray!

for result in resultArray {
    if result.resultType == NSTextCheckingType.Link {
        var url:NSURL! = result.URL!
        linkExist = true
    }
}

②自前で用意する場合


class Regex {
    let internalExpression: NSRegularExpression
    let pattern: String

    init(_ pattern: String) {
        self.pattern = pattern
        var error: NSError?
        self.internalExpression = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)!
    }

    func test(input: String) -> Bool {
        let matches = self.internalExpression.matchesInString(input, options: nil, range:NSMakeRange(0, count(input)))
        return matches.count > 0
    }
}

if Regex("^https?://.*").test("http://hoge.com") {  
    // linkExist
}

参考

NSDataDetector Class Reference
https://developer.apple.com/library/prerelease/ios/documentation/Foundation/Reference/NSDataDetector_Class/index.html

Regex in Swift
http://benscheirman.com/2014/06/regex-in-swift/

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5