【Objective-C】WordPressからiPhoneにJSON REST APIで連携する
はじめに
iPhoneとWordPressを連携する方法です。 最近はSwiftの話題で盛り上がっていますが、Objective-Cで行きますよ。
下準備
- WorePressがインストールされたサーバを用意
- X-Codeで新しいプロジェクトをSingleViewApplicationで用意します。 そして、Storyboard上でUITableViewを設置し、ヘッダーファイルと紐付けておきます。
WordPress側の設定
WorePressがインストールされたサーバの管理画面にアクセスしてください。
設定と言っても、プラグインをインストールだけ。
「JSON REST API」をインストールし、有効化しましょう。

なお、パーマリンクも設定しておいて下さい。

あと、取得する記事も、テキトーに入れておいてね。今回はテキトーに3つほど。

Objective-C側の実装
// ViewController.h //UITableViewを使用するときは、UITableViewDelegate, UITableViewDataSourceの2つをプロトコルにしてくださいね @interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> //テーブルの一覧にセットする配列 @property NSArray* items; //StoryBoardと紐付けたUITableView @property (weak, nonatomic) IBOutlet UITableView *tableView; @end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.delegate = self;
self.tableView.dataSource = self;
// 空の配列を用意
self.items = [NSArray array];
[self getJSON];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getJSON
{
NSURL *url = [NSURL URLWithString:@"http://chie-lab.main.jp/wp/wp-json/posts"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// アプリデータの配列をプロパティに保持
//NSArray * values = [jsonDictionary allValues];
self.items = jsonDictionary;
// TableView をリロード
[self.tableView reloadData];
}];
}
// セルの数を設定
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.items count];
}
// テーブルセルの内容を設定
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSDictionary *item = [self.items objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:@"title"];
return cell;
}
@end
以上です、実に素晴らしい。簡単ですね。 今日はここまで。
なお、WordPress側からデータの取得するURLはいろいろあるので、 以下のリンクを参考に試してみてください。 https://github.com/WP-API/WP-API ※Getting Startedが分かり易い https://github.com/WP-API/WP-API/blob/master/docs/guides/getting-started.md