LoginSignup
140
139

More than 5 years have passed since last update.

SwiftでWebAPIアプリを作った時の要点

Last updated at Posted at 2014-06-05

全文はこちらで。要点だけQiitaに転写
http://himaratsu.hatenablog.com/entry/swift/tiqav

SwiftでWebAPIアプリを作った時の要点

通信 (NSURLConnection)

通信部分

func reload() {
    // Thanks to tiqav api! ( http://dev.tiqav.com/ )
    let URL = NSURL(string: "http://api.tiqav.com/search/random.json")
    let req = NSURLRequest(URL: URL)
    let connection: NSURLConnection = NSURLConnection(request: req, delegate: self, startImmediately: false)

    // NSURLConnectionを使ってアクセス
    NSURLConnection.sendAsynchronousRequest(Req,
        queue: NSOperationQueue.mainQueue(),
        completionHandler: self.fetchResponse)
}

responseの処理

// responseを処理する
func fetchResponse(res: NSURLResponse?, data: NSData?, error: NSError?) {
    // responseをjsonに変換
    let json: NSArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSArray

    tiqavs = []

    for img in json {
        let imgId = img["id"] as String
        let ext = img["ext"] as String

        let imageUrl = (baseUrl + imgId + "." + ext) as String
        tiqavs.append(imageUrl)
    }

    // tableviewの更新
    dispatch_async(dispatch_get_main_queue(), {
        self.tableView.reloadData()
    })
}

AnyObject! は as String などとして型を指定する必要がある。AnyObject は Obj-C での id 型のようなもの(多分)

非同期での画像の読み込み

GCDをつかう

var q_global: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
var q_main: dispatch_queue_t  = dispatch_get_main_queue();

// imageUrl に画像のURLが入っている
// 非同期でimageUrlの内容を取得
dispatch_async(q_global, {
    var imageURL: NSURL = NSURL.URLWithString(imageUrl)
    var imageData: NSData = NSData(contentsOfURL: imageURL)

    var image: UIImage = UIImage(data: imageData)

    // 更新はmain threadで
    dispatch_async(q_main, {
        cell.tiqavImageView.image = image;
        cell.layoutSubviews()
    })
})

そのまま使える。

delegate実装宣言

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSURLConnectionDelegate {
    ...
}

こんな感じで書く。

ソースコード

GitHubにあげてます。
https://github.com/himaratsu/SwiftTiqavViewer

140
139
1

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
140
139