Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

全文はこちらで。要点だけ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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away