LoginSignup
67
64

More than 5 years have passed since last update.

Swift用の通信ライブラリAlamofireでcookie付きの通信を行う

Last updated at Posted at 2014-11-12

Swift用の通信ライブラリAlamofireでcookie付きの通信を行う

Alamofire=AFNetworkingのSwift版のようなものらしい

APIのテストアプリで、Swiftを使ってみようかと思いまして。調べたところ、Objective-Cの定番ライブラリAFNetworkingの作者さんがSwift版のライブラリを作成されているとか。

ただ、Cookie付きの通信については資料が少なく、かなり手間取ったのでメモっておきます。

Alamofire.Request

Alamofire.Requestを取得するには、2通りの方法があるようです。

func request(URLRequest: URLRequestConvertible) -> Alamofire.Request
func request(method: Alamofire.Method, URLString: URLStringConvertible, parameters: [String : AnyObject]? = default, encoding: Alamofire.ParameterEncoding = default) -> Alamofire.Request

このうち、後者だと細かい設定が出来ないっぽい(?)んで、前者を使用します。

引数は1つだけで、URLRequestConvertible を継承したクラスを作って渡せばいいようです。Adapterパターン(だったかな?)ですね。

URLRequestConvertible

URLRequestConvertibleは以下のprotocolです。

protocol URLRequestConvertible {
    var URLRequest: NSURLRequest { get }
}

サブクラス"MyRequest"を作成し、URLRequestのgetのところで、Cookie付きのNSURLRequestを返すように仕込んでおきます。

class MyRequest: URLRequestConvertible {

    let SERVER_ADDRESS = "http://www.example.com/"

    init() {
    }

    // URLRequestConvertible protocol
    var URLRequest: NSURLRequest {
        let url = NSURL.URLWithString(SERVER_ADDRESS)
        var request = NSMutableURLRequest(URL: url)

        request.HTTPMethod = "POST"

        // set cookie
        let properties = [NSHTTPCookieOriginURL: SERVER_ADDRESS,
            NSHTTPCookieName: "cookie_name",
            NSHTTPCookieValue: "cookie_value",
            NSHTTPCookiePath : "\\"]

        let cookie : NSHTTPCookie = NSHTTPCookie.cookieWithProperties(properties)!
        let cookies = [cookie]
        let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)

        request.allHTTPHeaderFields = headers

        return request;
    }
}

呼び出し側はこのような感じで。

Alamofire.request(MyRequest())
.responseJSON { (_, _, _, _) in
    /* do something... */
}

これで、Cookie付きの通信ができてるはずです...。

参考リンク

67
64
0

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
67
64