2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift】WordPressにAPIリクエストをしてブログ情報を取得する

Posted at

APIリクエストの飛ばし方がやっとわかった

Swiftには便利なライブラリAlamofireというものがあり、それを使用してHTTP接続をするのがセオリーですが、いかんせん最近はAlamofireの書き方が新しくなり、ネットでも調べても全然よくわかりませんでした。
それがやっと解消できたのでここに記します。

WprdPressが提供してくれてるAPI

情報が欲しいブログのURLの後ろに「/wp-json/wp/v2/posts?_embed」をつけてあげて、そのURLにリクエストを飛ばします。
私のブログはkimotii.comなので、

kimotii.com/wp-json/wp/v2/posts?_embed

となります。

ライブラリを入れる

CocoaPodsを使って便利なライブラリを入れましょう。
今回使用するのは
・Alamofire
・SwiftyJson
の2つです。
手順は、

1、ターミナルで以下を打つ

sudo gem install cocoapods

インストールが終わったら

pod setup

2、Xcode開いて今回作りたいアプリのプロジェクトを作る
ホームに作ると楽

3、ターミナルで

cd プロジェクトフォルダの名前

フォルダに移動できたら

pod init

これでpodファイルが生まれる

4、podファイルを開いて、

pod 'Alamofire'
pod 'SwiftyJson'

これらを記入したら

pod install

これでライブラリがインストールされました。

書いてみよう

以下が今回書いたものです。記事のタイトルを全て出してみました。

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // APIリクエストの関数を呼び出す
        getArticles()
    }
    
    func getArticles() {
        // Alamofireを使う
        // URLでリクエストを飛ばし、レスポンスがresponseに入る
        AF.request("https://kimotii.com/wp-json/wp/v2/posts?_embed").responseJSON { response in
        // 確認のためresponseを見てみる
        print("Response JSON: \(response.value)")

        // responseがnilじゃなかったら変数jsonObjectにレスポンスを入れる
        if let jsonObject = response.value {

                // 変数jsonにJSON形式にしたjsonObjectを入れる
                let json = JSON(jsonObject)

                // 配列の数だけ処理を繰り返す
                for i in 0..<json.count {
                    let array = json[i]
                    // "taitle"の"rendered"を指定してあげると記事タイトルが取れる
                    let title = array["title"]["rendered"].stringValue

                    // 取得できたタイトルを表示
                    print(title)
                }
            }
        }
    }
}

タイトル以外にも色んな情報がとれるのでおためしあれ!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?