LoginSignup
13
14

More than 5 years have passed since last update.

[Swift]ParseでCRUD(データ作成、読み出し、更新、削除)

Last updated at Posted at 2016-01-23

開発環境

Xcode 7.1.1
Parse 1.10.0
Cocoapods

Parseとは

https://parse.com/
mBaaS(mobile Backend as a Server)の代表格。
Push通知などさまざまな機能が使える。

参考
http://qiita.com/osamu1203/items/d7d2206cc079092d07c4

CRUD

CRUDとは、Create, Read, Update, Deleteの略。
これがデータベースとの連携の基礎である。

CRUDの前にParseを設定する

まずプロジェクトにParseをCocoapodsを使ってプロジェクトに入れる。
https://cocoapods.org/
CocoapodsがMacに入っていないひとは以下のコマンドをターミナルで打ってください。

$ sudo gem install cocoapods

$ pod setup

次に、ターミナルでParseを入れたいプロジェクトまでディレクトリ移動
例えば、デスクトップ上にSampleというフォルダの中にプロジェクトがあるなら

cd Desktop/Sample

次に、プロジェクトにPodfileというのを設定する
そのために次のコマンドを打つ

pod init

これで生成されるPodfileを編集する


# Uncomment this line to define a global platform for your project
# platform :ios, '6.0'

target 'sample' do

pod 'Parse'

end

target 'sampleTests' do

end

target 'sampleUITests' do

end



これでParseが常に最新の状態に保たれます

Cocoapodsについて知りたい方はこちら
http://qiita.com/satoken0417/items/479bcdf91cff2634ffb1

次に、Parse側でデータベースの準備をします。
以下にアクセスして、アカウントを持ってない人はまずは登録してください。
https://parse.com/

アカウントの作り方はこちら(記事が古いかもしれません)
http://dev.classmethod.jp/smartphone/android/parse-getting-started/

アカウントをお持ちの方は、以下のURLにアクセスの上、まずはCreate appでそのアプリのデータベースを作成する
https://parse.com/apps

続いて、ParseをiPhoneアプリに設定する
以下のURLから自分が今作成したAppの右上から"Keys"を選択する
https://parse.com/apps
Home___Parse.png

次に以下のような画面がでてきますので、ここからApplication IDとClient Keyを使います。
Edit_Your_App___Parse.png

AppDelegate.swift

import UIKit
import Parse

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        Parse.setApplicationId("ここにApplication ID", clientKey: "ここにClient Key")

        return true
    }


これでParseを使う準備が整いました

Create データ作成

func create() {
  let myObject: PFObject = PFObject(className: "Table名")
  myObject.setObject("ここに送りたいものを登録", forKey: "カラム名")
  myObject.saveInBackground() //Parseへの送信
}

MyObject___Parse_1.png

  1. Table名(今回は"MyObject")
  2. カラム名(今回は"message")
  3. 保存するデータ (今回は"こんばんは")

Read データ読み出し

今回はfindで該当するデータをすべて読み込み、arrayに要素として追加していき、UITableViewに表示するコードです
Datesというのはカスタムクラスをつくっています。

ViewController.swift
func read() {
   let query = PFQuery(className: "クラス名")
        //キャッシュに溜める
        query.cachePolicy = PFCachePolicy.NetworkElseCache
        query.orderByDescending("createdAt")
        query.whereKey("user", equalTo: user!)
        query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
            if error == nil {
                if let dateObject = objects as? [PFObject]? {
                    for object in objects! {
                        let dateObject = object as! Dates
                        self.array.append(dateObject["カラム名"] as! String)
                        self.dates.append(dateObject)
                    }
                }
                self.tableView.reloadData()
            } else {
                //エラーあり
                print("\(error?.localizedDescription)")

            }
        }
}

Update データ更新

ViewController.swift
let query = PFQuery(className: "クラス名")
//objectIdを指定して、getする
        query.getObjectInBackgroundWithId(objectArray[self.selectedIndexPath.row].objectId!) { object, error in
            if error == nil {
                //"text"というカラムにいれる値を決める
                object!["text"] = alertView.textFieldAtIndex(0)!.text
//データを送信する
                object!.saveInBackgroundWithBlock { (success, error) -> Void in
                    if success {
                        AlertManager.showAlert(.Success, message: "保存成功")
                    }else {
                        AlertManager.showAlert(.Error, message: "保存失敗")
                    }
                }
            }else {
               print(error)
            }
        }

Delete データ削除

ViewController.swift
let query: PFQuery = PFQuery(className: "Basic")
        query.orderByDescending("createdAt")
        print(self.selectedIndexPath)
        query.getObjectInBackgroundWithId(objectArray[self.selectedIndexPath.row].objectId!) { object, error in
            if error == nil {
                object!.deleteInBackgroundWithBlock { success, error in
                    if error == nil {
                        AlertManager.showAlert(.Success, message: "削除しました")
                    }else {
                        AlertManager.showAlert(.Error, message: "削除に失敗しました")
                    }
                }
            }else {
                AlertManager.showAlert(.Error, message: "削除に失敗しました")
            }
        }

参考ウェブサイト

SwiftとParseでの簡単にCRUD(生成、読み込み、更新、削除)。(Swift, Xcode6 beta5, Parse, UITableView, prepareForSegue)
Parse - iOSガイド

参考コード

Parse-Sample-Swift2.0(by masuhara)

13
14
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
13
14