ぬけてるエンジニアの備忘録

イケてない情報の掃き溜め。。。

【Swift】Parseを使ってデータ取得してみた

parse.com
Parseを使ってサーバーからデータ取得、表示するまでをやってみた。



環境 Xcode7.0 Swift

今回の手順として

  • ParseSDKをプロジェクトに導入
  • Parseサイトの登録・初期設定まで済ましておく
  • Parseサイトで設定したApplication IDと、Client Keyをアプリに設定
  • storyboardでTableView等を設置した画面を作成
  • データを取得してViewに表示する

ざっくり言うとこんな感じ。

まずはcocoapodsでParseSDKを導入する


Podfile

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'Parse'


pod install

これで導入完了。


Parse

f:id:Yuchang:20150929115420p:plain
こんな感じでParseサイトであらかじめアプリで取得したいデータをセットしておく。



AppDelegate.swift

import Parse
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
     Parse.setApplicationId("アプリケーションID", clientKey:"クライアントキー")
        
     return true
}

didFinishLaunchingWithOptionsでApplication IDとClient Keyを設定する。



storyboard

f:id:Yuchang:20150929144307p:plain UIViewControllerUITableViewを設置する。この時にdatasourcedelegateも設定しておく。


ViewController.swift

import UIKit
import Parse

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    var tableData:Array<AnyObject> = Array<AnyObject>()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        
        self.loadData()
    }
    
    func loadData() {
        let query: PFQuery = PFQuery(className: "sample_data")
        query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
            
            if (error != nil){
                // エラー処理
                return
            }
            
            for row:PFObject in objects! {
                self.tableData.append(row)
            }
            
            self.tableView.reloadData()
        }
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableData.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        let imageFile: PFFile? = self.tableData[indexPath.row].objectForKey("thumbnail") as! PFFile?
        imageFile?.getDataInBackgroundWithBlock({ (imageData, error) -> Void in
            if(error == nil) {
                cell.imageView!.image = UIImage(data: imageData!)!
                cell.textLabel!.text = self.tableData[indexPath.row].objectForKey("title") as? String
            }
        })
        return cell
    }
    
}

実装はここまで。

実行してみると


本当に簡単にWebサーバーからデータ取得、表示までを実装する事ができました。サーバーサイドの知識or実装が無くてもParseをうまく使えばそれなりのアプリが作れてしまいますね。
今回はおそらくもっとも簡単な使い方?を試しただけですので今後もParseを使って色々とやってみようと思います。