LoginSignup
11
10

More than 5 years have passed since last update.

[Swift]NSTextCheckingTypeを使って正しいリンク形式かどうかを判断する

Last updated at Posted at 2016-02-01

SNSなどのアプリでプロフィールにWebリンクを追加したい場合があると思いますが、サーバーに文字列などの情報を実際に送る前にクライアント側で有効なURLかどうかを判断したい場合の実装です。

【実装後のイメージ】
IMG_2971.PNG.jpeg

NSTextCheckingTypeNSDataDetectorを使った方法です。
とりあえず実装例。


protocol Validator {
    func validateURL(urlString: String) -> Bool
}

extension Validator {
    func validateURL(urlString: String) -> Bool {
        var result = false
        let types: NSTextCheckingType = .Link
        let detector = try? NSDataDetector(types: types.rawValue)
        guard let detect = detector else {
            return result
        }
        let matches = detect.matchesInString(urlString, options: .ReportCompletion, range: NSMakeRange(0, urlString.characters.count))
        for match in matches {
            if let url = match.URL {
                print("url \(url)")
                result = true
            }
        }
        return result
    }
}

色々なValidationメソッドを今後も追加したいのでprotocol extensionを採用しました。

NSRegularExpressionを使って、


try! NSRegularExpression(pattern: "https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?", options: NSRegularExpressionOptions(rawValue: 0))

のようなパターンを作ってmatchをチェックする方法もあると思いますが、自前で正規表現を用意しなくても基本的な機能なら上の二つのクラスを使ってまかなえそうです。

NSRegularExpressionはハッシュタグの検索とか

try! NSRegularExpression(pattern: "#(\\w+)", options: NSRegularExpressionOptions(rawValue: 0))

NSTextCheckingTypeが用意していないケースのマッチを探す場合だけでいいかなと思いました。
NSTextCheckingTypeは現在

・Orthography
・Spelling
・Grammar
・Date
・Address
・Link
・Quote
・Dash
・Replacement
・Correction
・RegularExpression
・PhoneNumber
・TransitInformation

があるので用途に応じて使っていこうと思います。

11
10
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
11
10