5
1

More than 3 years have passed since last update.

【iOS】AWS DynamoDBからテーブル名を取得する方法

Last updated at Posted at 2020-12-31

はじめに

案件でAWSと連携したアプリを開発することになりましたが、意外と参考にする記事が少なくて苦労したので、手順をまとめてみました。
今回はDynamoDBからテーブル名を取得してみます。

開発環境

Cocoapodsの導入

aws-amplify/aws-sdk-iosのREADMEの手順通りに進めていきます。

まずcocoapodsをインストールします。

ターミナル
$ gem install cocoapods
$ pod setup

プロジェクトのディレクトリ直下でpod init

ターミナル
$ pod init

Podfileが作成されているので使用するAWSのサービスを記載します

Podfile
target 'aws-sdk' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  pod 'AWSDynamoDB'
end

podインストールしたら、xed .でXcodeを開きなおします。

ターミナル
$ pod install --repo-uodate
$ xed .

AWSに接続するための設定

AWSに接続するにはAWSの認証を行う必要があります。
私が調べた限りでは下記の2通りがあります。

  1. Coginitoを使用した認証(aws-sdkのREADMEにはこちらが書かれている)
  2. AWSのaccess-keyとsecrete-keyを使用した認証

両方を試しましたが、Cognitoの認証は設定が面倒だったので、2の方法で認証することにしました。
Keyの発行は下記を参考にしてください。

AWS アクセスキーを作成するには、どうすればよいですか?
Qiita AWS アクセスキーを作成する

認証の設定はAppDelegate.swiftで行います。

AppDelegate.swift
import UIKit
import AWSCore

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

     // 下記を追加
        let accessKey = Constans.accessKey
        let secretKey = Constans.secretKey
        let provider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)

        let configuration = AWSServiceConfiguration(
            region: AWSRegionType.APNortheast1,  // regionは適宜変更してください
            credentialsProvider: provider)

        AWSServiceManager.default().defaultServiceConfiguration = configuration

        return true
    }
}

AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey)のaccessKeyとsecretKeyの管理は個々にお任せします。(絶対に公開しないように気をつけてください。)

私の場合は、案件ではcocoapods-keysで管理しましたが、今回は簡易的に定数のクラスを作成しました。
作成したファイルは、pushしないように.gitignoreに設定しています。
orta/cocoapods-keys

Constants.swift
import Foundation

class Constans {
    static let accessKey = "AWSのaccess-key"
    static let secretKey = "AWSのsecret-key"
}

AWSDynamoDBからテーブル名を取得

ViewController.swift
import UIKit
import AWSDynamoDB

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchDynamoDBTableName()
    }

    private func fetchDynamoDBTableName() {
        let dynamoDB = AWSDynamoDB.default()
        let listTableInput = AWSDynamoDBListTablesInput()
        dynamoDB.listTables(listTableInput!).continueWith { (task:AWSTask<AWSDynamoDBListTablesOutput>) -> Any? in
            if let error = task.error as? NSError {
            print("Error occurred: \(error)")
                return nil
            }

            let listTablesOutput = task.result

            for tableName in listTablesOutput!.tableNames! {
                print("\(tableName)")
            }

            return nil
        }
    }
}

これでビルドするとコンソールにDynamoDBに存在するテーブル名が表示されていると思います。
複数のテーブルが存在する場合、複数表示されています。
ViewControllerにメソッドを記載しましたが、ViewControllerがFatになるのでDynamoDM用のクラスを作成するなどしたほうが良いと思います。

今回のリポジトリ

参考までに。
https://github.com/shungo0525/aws-sdk

おわりに

今回はDynamoDBのテーブル名の取得だけですが、DBデータの取得やS3との連携についても投稿したいと思います。

5
1
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
5
1