[Swift] Parseでデータを読み込む

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Swift で Parse!

今回は、Swiftを使って、Parseサーバからデータを取得・表示するところまでやってみましょう。

以下、順を追ってやり方を説明していきます。

Parseサーバ上にデータを追加

ここでは、

  • すでにParseサイトでのサインアップが完了していること
  • アプリの登録が完了していること
    • を前提に話を進めます。

      Parseサイトのデータ管理画面(Core)に移動し、必要なデータを入力します。

      今回は画像を表示したいので、画像を格納する graphicFile カラム(File)を追加しました。

      また、画像の説明文を格納する title カラム(String)も追加しています。

      スクリーンショット 2014-11-29 21.43.31

      Parse iOS SDKを導入

      CocoaPodsで"Parse"を導入しましょう。

      参考:Parseのpodは 一番公式っぽい “Parse” を使おう

      スクリーンショット 2014-11-29 16.01.08

      Storyboard

      今回はデータ一覧を効率的に表示するため、TableViewControllerを使います。

      スクリーンショット 2014-11-29 21.49.00

      Swiftでコードを書く

      中身を見て行きましょう

      AppDelegate.swift

          func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
              var Id = "xxxxxxxxxxxxxxxxx"
              var Key = "xxxxxxxxxxxxxxxxx"
      
              // MARK: - Parse
              Parse.setApplicationId(Id, clientKey: Key)
              PFUser.enableAutomaticUser()
              var defaultACL = PFACL()
              PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser: true)
              return true
          }

      application:didFinishLaunchingWithOptions:で、Parseサイトで設定したApplication IDと、Client Keyを設定します。

      TableViewController.swift

      loadData()

          func loadData(callback:([PFObject]!, NSError!) -> ())  {
              var query: PFQuery = PFQuery(className: "Picture")
              query.orderByAscending("createdAt")
              query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
                  if (error != nil){
                      // エラー処理
                  }
                  callback(objects as [PFObject], error)
              }
          }

      Parseのサーバからデータを取ってくるところから実装します。

      コールバックで、PFObjectの入った配列を返しています。

      viewDidLoad()

          override func viewDidLoad() {
              super.viewDidLoad()
              self.loadData { (pictures, error) -> () in
                  self.pictures = pictures
                  self.tableView.reloadData()
              }
          }

      あらかじめ定義しておいたself.pictures(PFObjectの入った配列として定義)の中に、loadData()で取得した内容を代入しています。

      その後、変更が画面に反映されるよう、reloadData()を呼んでいます。

      UITableViewDataSourceのプロパティ

          override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
              return 1
          }
      
          override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
              return self.pictures.count
          }
          
          override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as UITableViewCell
          var imageFile: PFFile? = self.pictures[indexPath.row].objectForKey("graphicFile") as PFFile?
          imageFile?.getDataInBackgroundWithBlock({ (imageData, error) -> Void in
              if(error == nil) {
                  cell.imageView.image = UIImage(data: imageData)!
                  cell.textLabel.text = self.pictures[indexPath.row].objectForKey("title") as? String
              }
          })
          return cell
      }

      ここでのポイントは、画像読み込みでPFFileオブジェクトを作成し、getDataInBackgroundWithBlock(block: PFDataResultBlock!)で実際に画像データを取得し、表示処理をしているところです。

      完成

      実行してみましょう。

      iOS Simulator Screen Shot 2014.11.29 23.01.08

      Parseサーバに保存した3件のデータがすべてTableView上に表示されています。

      お疲れ様でした!