LoginSignup
2
2

More than 3 years have passed since last update.

【Swift5】RSSフィードのURLを見つける

Last updated at Posted at 2020-06-08

RSSリーダーには、https://〇〇〇.comと入力するだけでhttps://〇〇〇.com/feed.xmlのようなフィードのURLを自動で見つけてくれる機能があったりします。

今回は、Auto Discoveryというものを利用して実装してみます。

試しにGizmodo JapanのHTMLを見てみると…

<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="https://www.gizmodo.jp/index.xml">
<link rel="alternate" type="application/atom+xml" title="Atom" href="https://www.gizmodo.jp/atom.xml">

ありました。
このapplication/〇〇〇+xmlがある、すなわちAuto Discoveryに対応しているサイトなら簡単にURLが取得できます。

たったこれだけ

if let doc = try? HTML(url: URL(string: "https://gizmodo.jp")!, encoding: .utf8) {
    for node in doc.xpath("//link[@type='application/rss+xml']") {
        print("rss:\(node["href"]!)")
    }
    for node in doc.xpath("//link[@type='application/atom+xml']") {
        print("atom:\(node["href"]!)")
    }
}

HTMLパーサーはKannaというライブラリを使用しました。
Swift製HTMLパーサ「Kanna」
少し古いですが、こちらの記事が参考になります。importする手順も書かれています。

出力結果

rss:https://www.gizmodo.jp/index.xml
atom:https://www.gizmodo.jp/atom.xml

問題なく取得できました。
今回試したGizmodoはrssとatomの両方に対応していたようです。

2
2
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
2
2