SwiftとAFNetworkingの簡単サンプル


`rbenv`で`ruby`やらを管理するようになって、改めて`cocoapods`のインストールから始めた覚え書き。

### ※2015/01更新
本記事で動作しない方は[こちら](http://qiita.com/tajihiro/items/294ce7440c8316962da2)の記事へ

#準備

##開発環境

PC: MacOS X 10.9.4
Xcode: Version 6.1
Ruby: 2.1.3
Rails: 4.1.6

##Cocoapodsのインストール

```
$ rbenv exec gem install cocoapods
```

##プロジェクトディレクトリへ移動
```
$ cd /path/to/your/xcode/project
```

##Podfileの作成

```
$ vi Podfile

platform :ios, "7.0"
pod 'AFNetworking', '~> 2.0'
pod "AFNetworkActivityLogger", "~> 2.0"
```

##Cocoapodsのインストール

```
$ pod setup
Setting up CocoaPods master repo
Updating ce725a5..4bf3048

Fast-forward
  
  ・・・中略・・・
  
From https://github.com/CocoaPods/Specs

   ce725a5..4bf3048  master     -> origin/master
Setup completed
```

##外部ライブラリ(AFNetworking等)のインストール

```
$ pod install
Analyzing dependencies
Downloading dependencies
Installing AFNetworkActivityLogger (2.0.3)
Using AFNetworking (2.4.1)
Generating Pods project
Integrating client project

[!] The use of implicit sources has been deprecated. To continue using all of the sources currently on your machine, add the following to the top of your Podfile:

    source 'https://github.com/CocoaPods/Specs.git'
```

##プロジェクトを開く
`Xcode`を起動して、`.xcodeproj`ではなく、`.xcworkspace`のプロジェクトファイルを開く。

![スクリーンショット 2014-10-13 23.41.40.png](https://qiita-image-store.s3.amazonaws.com/0/3184/0d70c5e0-108a-098f-0115-b2ce8aef0797.png "スクリーンショット 2014-10-13 23.41.40.png")

#コーディング

##ロギング設定

```AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //ロギング開始
        AFNetworkActivityLogger.sharedLogger().level = .AFLoggerLevelDebug
        AFNetworkActivityLogger.sharedLogger().startLogging()
        
        return true
    }
}
```

## 通信処理

```FirstViewController.swift
class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NSLog("AFNetwork Starts First Page!!!")
        
        //リクエスト
        let manager:AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
        let serializer:AFJSONRequestSerializer = AFJSONRequestSerializer()
        manager.requestSerializer = serializer
        manager.GET("http://localhost:3000/members.json", parameters: nil,
            success: {(operation: AFHTTPRequestOperation!, responsobject: AnyObject!) in
                        println("Success!!")
                        println(responsobject)
                     },
            failure: {(operation: AFHTTPRequestOperation!, error: NSError!) in
                        println("Error!!")
                     }
        )
        
    }
}
```

##通信ログ

```
2014-10-13 23:53:19.436 CocoapadSample[30736:177940] AFNetwork Starts First Page!!!
2014-10-13 23:53:19.563 CocoapadSample[30736:177940] GET 'http://localhost:3000/members.json': {
    "Accept-Language" = "en;q=1";
    "User-Agent" = "CocoapadSample/1 (iPhone Simulator; iOS 8.1; Scale/2.00)";
} (null)
2014-10-13 23:53:19.564 CocoapadSample[30736:177940] 200 'http://localhost:3000/members.json' [0.0011 s]: {
    "Cache-Control" = "max-age=0, private, must-revalidate";
    Connection = "Keep-Alive";
    "Content-Length" = 80;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Mon, 13 Oct 2014 14:53:19 GMT";
    Etag = "\"e25874e5c93e096f40461ae7ea30c135\"";
    Server = "WEBrick/1.3.1 (Ruby/2.1.3/2014-09-19)";
    "X-Content-Type-Options" = nosniff;
    "X-Frame-Options" = SAMEORIGIN;
    "X-Request-Id" = "13c2e6cf-9b4d-40b7-8ff6-e688527ce991";
    "X-Runtime" = "0.023255";
    "X-Xss-Protection" = "1; mode=block";
} [{"id":1,"name":"ほげほげ","age":99,"url":"http://localhost:3000/members/1.json"}]
Success!!
(
        {
        age = 99;
        id = 1;
        name = "\U7530\U5cf6\U7530\U5cf6";
        url = "http://localhost:3000/members/1.json";
    }
)
```

通信できた。

*Lovely Swift!!!*