LoginSignup
17
13

More than 5 years have passed since last update.

Swift 3でStringからURLの配列を抽出する(Extract an array of URLs from a String in Swift 3)

Last updated at Posted at 2016-11-14

はじめに(Introduction)

Swift 3でStringからURLの配列を抽出したい場合、どう書くか。
(How do we write if we want to extract an array of URLs from a String in Swift 3?)

記述例(Implementation)

文字列を渡すと、URLの配列を返します。
(After passing the string, an array of URLs will be returned.)

LinkHelper.swift
class LinkHelper: NSObject {

    class func extractURL(_ string:String)-> [URL]{
        let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
        let links = detector.matches(in: string, range: NSMakeRange(0, string.characters.count))
        return links.flatMap { $0.url }
    }
}

(2016/11/16追記: @woxtuさんのご指摘で、flatMapを使った記述にコードを改善しました。ありがとうございます。)

こうすれば、URLが2つarrayに入ります。
(Two of the URL will be placed in array.)

let string = "プロフィールページ http://qiita.com/hsylife PickerをPopoverで表示するライブラリの紹介 http://qiita.com/hsylife/items/e54ae8bde0838db53ae3"
let array = LinkHelper.extractURL(string)

条件(Required)

init(types checkingTypes: NSTextCheckingTypes) throwsは、iOS8.0+, watchOS 2.0+が必須です。

発展(Development)

typesの.linkを.phoneNumberに変更すると、同じような構造で、電話番号文字列の配列を抽出をさせることができますね。
(If you change the type's .link to .phoneNumber, you can have the same structure for extracting an array of phone number strings.)

その他の種類については一覧表に説明があります。

(Other types are explained in the table.)

関連リンク(Links)

NSDataDetector

余談。英語を併記してみました。Google Translationの結果をほぼ90%くらいそのまま使っています。閲覧者側でページ単位の翻訳をしてもらえると併記不要なのですが、まだ検索結果はオリジナル言語に依存していると思うので、過渡的な措置として英語併記が必要で、省力化のためにGoogle 翻訳が便利だという実感を得ました。おすすめです。

17
13
2

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
17
13