LoginSignup
5
5

More than 5 years have passed since last update.

AFNetworkingのNSURLSessionへの置き換えについて

Posted at

http://qiita.com/kenchan1837/items/a9e1de18c7eab75c4145
上記記事の通信周りの説明の補足です。
(主にcocoaPodsが使えなかった時用)

今回作成したアプリでAFNetworkingを利用して通信を行っている部分は
・検索ボタンを押した後のJSONデータの取得
・一覧画面を表示するときのサムネイル画像の取得
の2箇所になっています。

AFNetworkingの利用は必須というわけではないので
標準のframeworkを利用して通信処理を置き換えることも可能です。

標準frameworkを利用する場合iOS7より導入されたNSURLSessionを使うのが一般的ですので
以下に置き換え例を示します。
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/

・検索ボタンを押した後のJSONデータの取得

AFNetworking
AFHTTPSessionManager().GET(
                "https://itunes.apple.com/search?term=\(text)&country=JP&lang=ja_jp&media=music",
                parameters: nil,
                success: { (task: NSURLSessionDataTask!, response: AnyObject!) -> Void in
                    if let data = response as? NSDictionary, results = data["results"] as? [NSDictionary] {
                        self.results = results
                        self.tableView.reloadData()
                    }
                },
                failure: nil)
}

を以下のように書き換えてください。

NSURLSession
var url:NSURL = NSURL(string:"https://itunes.apple.com/search?term=\(text)&country=JP&lang=ja_jp&media=music")!
var req:NSURLRequest  = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)
let task = session.dataTaskWithRequest(req, completionHandler: {(data,response,error) in
    let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
    if let data = json as? NSDictionary, results = data["results"] as? [NSDictionary]{
        self.results = results
        dispatch_async(dispatch_get_main_queue(),{
            self.tableView.reloadData()
        })
    }
})
task.resume()

・一覧画面を表示するときのサムネイル画像の取得

AFNetworking
cell.artworkImageView.setImageWithURL(NSURL(string: artworkUrl))

を以下のように書き換えてください

NSURLSession
let req = NSURLRequest(URL:NSURL(string: artworkUrl)!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil)
let task = session.dataTaskWithRequest(req, completionHandler: {(data,response,error) in
    dispatch_async(dispatch_get_main_queue(),{
        cell.artworkImageView.image = UIImage(data:data)
    })
})
task.resume()

以上でAFNetworkingを利用しないで通信処理を行うことができます。

5
5
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
5
5