(非推奨)kintone iOS SDK

目次

caution
警告

このツールは、現在推奨されていません。

はじめに

2019年2月にリリースされた、「kintone iOS SDK」について紹介します。
今回リリースされた「kintone iOS SDK」により、SwiftやObjective-Cでより簡単にkintone REST APIを実行できます。

また、「kintone iOS SDK」は以前リリースした「kintone Node.js SDK」や同時期にリリースされている「 kintone Java SDK」と同じ設計思想で設計、実装されています。
そのため、言語による違いは存在しますが、認証やコネクション、クラス、メソッドなど各所で同様に宣言できます。

GitHub

https://github.com/kintone-labs/kintone-ios-sdk/ (External link)

ドキュメント

kintone iOS SDK (External link)

今回は、kintone iOS SDKの導入方法と実行を、サンプルを用いて説明します。
開発はXcodeで行います。
実行できる環境でお試しください。

Xcode

https://developer.apple.com/jp/xcode/ (External link)

注意事項

ソースコードの変更および再配布、商用利用等はライセンスにしたがってご利用可能です。

導入方法

swiftのライブラリ導入方法はパッケージマネージャーか、自身でソースコードをビルドする方法があります。
今回はXcodeの「Single View App」プロジェクトで、パッケージマネージャーを使用して導入方法を紹介します。
「sample_project」という名前でプロジェクトを作成してください。

Xcode > Preferences > Locationsでコマンドラインツールを下図のように設定します。

インストール

Cocoapods

主要なパッケージマネージャーの1つです。
Cocoapods自体のインストールは公式サイトを参考にご自身で設定してください。
Cocoapods (External link)

プロジェクトが保存されているディレクトリーで以下のコマンドを実行しPodfieを作成してください。

1
pod init

以下のサンプルを参考に、Podfileを修正してください。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Uncomment the next line to define a global platform for your project
platform :ios, '11.4'

target 'sample_project' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for sample_project
  pod 'kintone-ios-sdk', '~> 0.1.0'
  pod 'PromisesSwift', '~> 1.2.4'

  target 'sample_projectTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'sample_projectUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end

下記コマンドを実行することでXcodeプロジェクト内にSDKがインストール可能です。

1
pod install

コマンド実行後、ディレクトリー内に拡張子が「sample_project.xcworkspace」のファイルが生成されます。
このファイルをXcodeで開き、一度ビルドするとワークスペース内でSDKが使用可能になります。

Carthage

CarthageはHomebrewからインストール可能です。
GitHubのドキュメントを参考にご自身でインストールしてください。

https://github.com/Carthage/Carthage (External link)

プロジェクトが保存されているディレクトリーにCartfileを作成してください。

1
touch Cartfile

Cartfileに以下のように記述してください。

1
2
github "google/promises"
github "kintone/kintone-ios-sdk"

Cartfileの編集が完了したら次のコマンドを実行しライブラリをダウンロードします。

1
carthage update

ダウンロードが完了すると「Sample_project/Carthage/Build/iOS」フォルダー内に以下の3つのframeworkが作成されます。

  • FBLPromises.framework
  • Promises.framework
  • kintone-ios-sdk.framework

作成されたframeworkファイルをプロジェクトにインポートする必要があります。
下図を参考にインポートしてください。

サンプル

ドキュメントのQuickstartにも掲載されている簡単なサンプルコードを用いて、実行方法とレスポンスについて説明していきます。
サンプルコードでは、kintoneアプリからレコードを1件取得する機能を実装しています。
準備として、kintoneアプリを作成し、下表をもとにフィールドを追加し、閲覧権限を付与したAPIトークンを作成してください。

フィールドタイプ フィールドコード
文字列 (1行) text

サンプルコード(ファイル名:ViewController.swift

次のサンプルコードをコピーし、「sample_project」内の「ViewController.swift」を書き換えてください。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* kintone iOS SDK Sample Program
* Copyright (c) 2019 Cybozu
*
* Licensed under the MIT License
* https://opensource.org/license/mit/
*/

import UIKit
import FBLPromises
import kintone_ios_sdk

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        testGetRecord()
    }
    //Get Record Data
    func testGetRecord() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
        print("test start")

        let apitoken = "xxxxxx"
        let domain = "sample.cybozu.com"

        // Init authenticationAuth
        let kintoneAuth = Auth()
        kintoneAuth.setApiToken(apitoken)

        // Init Connection without "guest space ID"
        let kintoneConnection = Connection(domain, kintoneAuth)

        // Init Record Module
        let kintoneRecord = Record(kintoneConnection)

        // execute get record API
        let appID = xx
        let recordID = x
        kintoneRecord.getRecord(appID, recordID).then { response in
            let resultData = response.getRecord()!
            print(resultData["$id"]?.getValue())
            print(resultData["text"]?.getValue())
        }.catch { error in
            if error is KintoneAPIException {
                print((error as! KintoneAPIException).toString()!)
            }
        }
    }
}

以下の情報は、ご自身の環境に合わせて書き換えてください。

  • APIトークン
  • 認証情報
  • サブドメイン
  • アプリID

実行例

Xcode上で左上の「▶︎」マークをクリックするか、⌘ + Rで実行してください。
リクエストに成功すると、次のようなレスポンスが返ってきます。

サンプルコード解説

Authentication

サンプルコード30〜31行目についての解説です。
この部分では、kintoneに接続するための、認証方法について定義します。

30
31
// Init authenticationAuth
let kintoneAuth = Auth()

Authenticationクラスがあり、パスワード認証、APIトークン認証、Basic認証を設定できます。
認証の優先度は以下のとおりです。
参考: 認証の優先順位

  1. パスワード認証
  2. APIトークン認証

セッション認証はkintone iOS SDKでは実装できません。

パスワード認証
1
2
3
let username = "User Name"
let password = "Password"
kintoneAuth.setPasswordAuth(username, password)
API トークン認証
1
2
let apiTokenString = "API Token";
kintoneAuth.setApiToken(apiTokenString);
Basic 認証
1
2
3
let basicUsername = "Basic username";
let basicPassword = "Basic password";
kintoneAuth.setBasicAuth(basicUsername, basicPassword);

Connection クラス

34行目のConnectionクラスでは、接続について設定できます。
接続先のドメイン情報と、先ほど作成した認証情報を使ってkintone環境に接続します。

通常のスペースの場合
33
34
let domain = "{subdomain}.cybozu.com";
let kintoneConnection = Connection(domain, kintoneAuth);
ゲストスペースの場合
1
2
3
4
// for GuestSpace
let domain = "{subdomain}.cybozu.com";
let guestSpaceID = xx;
let kintoneConnection = Connection(domain, kintoneAuth, guestSpaceID);

Record クラス

最後に、37〜50行目についてです。

37
38
39
40
41
42
43
44
45
46
47
48
49
50
let kintoneRecord = Record(kintoneConnection)

// execute get record API
let appID = xx
let recordID = x
kintoneRecord.getRecord(appID, recordID).then { response in
    let resultData = response.getRecord()!
    print(resultData["$id"]?.getValue())
    print(resultData["text"]?.getValue())
}.catch { error in
    if error is KintoneAPIException {
        print((error as! KintoneAPIException).toString()!)
    }
}

この部分は、実際にkintoneのREST APIを実行する処理です。
サンプルでは、レコードを1件取得するために、RecordクラスのgetRecord関数を使用しています。

getRecord関数には次の引数を指定します。

名称 データタイプ 必須 説明
appID Integer アプリ ID
recordID Integer レコード番号

Recordクラスには、後述のとおり、レコード1件取得以外にも、さまざまな関数が用意されています。

その他の機能について

Record クラス

先ほどのサンプルコードで使用した関数が定義されているクラスです。
アプリのレコードに対し、取得/登録/更新/削除、/ステータスの変更を実施する関数や、コメントの取得/登録/削除を実施する関数が実装されています。
実装されている関数の例として、次の関数が実装されています。

  • getRecord
  • getRecords
  • addRecord
  • addRecords
  • updateRecords
  • deleteRecords
  • updateRecordStatus
  • getComments
  • addComment
  • deleteComment

他にもさまざまな関数が用意されています。
詳細はドキュメントを確認してください。 Record (External link)

BulkRequest クラス

複数のアプリに対して、同時に複数のAPIをリクエストできます。
BulkRequestクラスで使用できる関数は次のドキュメントを確認してください。
BulkRequest (External link)

また、BulkRequestを実行する際は次のことに注意してください。

  • BulkRequestを実行し、レスポンスを取得する際は、 execute (External link) 関数を実行する。
  • 一度に実行できる関数は、excecute関数をのぞいて20個まで。
BulkRequest サンプル
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
var bulkRequest = BulkRequest(kintoneConnection);

bulkRequest = try! bulkRequest.addRecord(appID, addData)
bulkRequest = try! bulkRequest.addRecords(appID, addDataList)
bulkRequest = try! bulkRequest.updateRecordByID(appID, updRecID, updateData, nil)
bulkRequest = try! bulkRequest.deleteRecords(appID, delIdList);

bulkRequest.execute().then{ responses in
    print(responses)
}.catch{ error in
    if error is KintoneAPIException {
        print((error as! KintoneAPIException).toString()!)
    }
    else {
        print(error)
    }
}

App クラス

アプリの情報を取得する関数が定義されているクラスです。
アプリの閲覧権限が必要です。

Appクラスで使用できる関数は次のドキュメントを確認してください。
App (External link)

App サンプル
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let app = App(kintoneConnection)

app.getApp(appID).then{ response in
    print(response.getCreator()?.getName())
}.catch{ error in
    if error is KintoneAPIException {
        print((error as! KintoneAPIException).toString()!)
    } else {
        print(error)
    }
}

型について

kintone iOS SDKでは、各APIのレスポンスに独自の型を利用しています。
それぞれコンストラクタや利用できるメソッドが違うのでドキュメントを確認して利用してください。
AppModel (External link)

おわりに

iOSやmacOSのアプリ開発において、kintone REST APIを実行しやすくなりました。
この機会にkintone iOS SDKをご活用ください。

information

このTipsは、2019年2月版kintoneで動作を確認しています。